blob: e318a86240543619c7c781aa255355f38e3d68f7 [file] [log] [blame]
Eugene Zelenko076468c2017-09-20 21:35:51 +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"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000017#include "ARMBaseInstrInfo.h"
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +000018#include "ARMBasicBlockInfo.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000020#include "ARMSubtarget.h"
21#include "MCTargetDesc/ARMBaseInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "Thumb2InstrInfo.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000023#include "Utils/ARMBaseInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000024#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000029#include "llvm/ADT/StringRef.h"
30#include "llvm/CodeGen/MachineBasicBlock.h"
Evan Cheng10043e22007-01-19 07:51:42 +000031#include "llvm/CodeGen/MachineConstantPool.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000032#include "llvm/CodeGen/MachineFunction.h"
Evan Cheng10043e22007-01-19 07:51:42 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000034#include "llvm/CodeGen/MachineInstr.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000035#include "llvm/CodeGen/MachineJumpTableInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000036#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000037#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/DataLayout.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000039#include "llvm/IR/DebugLoc.h"
40#include "llvm/MC/MCInstrDesc.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000041#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Support/CommandLine.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000043#include "llvm/Support/Compiler.h"
Evan Cheng10043e22007-01-19 07:51:42 +000044#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000046#include "llvm/Support/Format.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000047#include "llvm/Support/MathExtras.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000048#include "llvm/Support/raw_ostream.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000049#include <algorithm>
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000050#include <cassert>
51#include <cstdint>
52#include <iterator>
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000053#include <utility>
54#include <vector>
55
Evan Cheng10043e22007-01-19 07:51:42 +000056using namespace llvm;
57
Chandler Carruth84e68b22014-04-22 02:41:26 +000058#define DEBUG_TYPE "arm-cp-islands"
59
James Molloy9b3b8992017-02-13 14:07:25 +000060#define ARM_CP_ISLANDS_OPT_NAME \
61 "ARM constant island placement and branch shortening pass"
Evan Chengdb73d682009-08-14 00:32:16 +000062STATISTIC(NumCPEs, "Number of constpool entries");
63STATISTIC(NumSplit, "Number of uncond branches inserted");
64STATISTIC(NumCBrFixed, "Number of cond branches fixed");
65STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
66STATISTIC(NumTBs, "Number of table branches generated");
67STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000068STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000069STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000070STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000071STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000072
Jim Grosbach8d92ec42009-11-11 02:47:19 +000073static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000074AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000075 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000076
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +000077static cl::opt<unsigned>
78CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
79 cl::desc("The max number of iteration for converge"));
80
James Molloy70a3d6d2016-11-01 13:37:41 +000081static cl::opt<bool> SynthesizeThumb1TBB(
82 "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
83 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
84 "equivalent to the TBB/TBH instructions"));
85
Evan Cheng10043e22007-01-19 07:51:42 +000086namespace {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000087
Dale Johannesene18b13b2007-02-23 05:02:36 +000088 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000089 /// requires constant pool entries to be scattered among the instructions
90 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000091 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000092 /// special instructions.
93 ///
94 /// The terminology used in this pass includes:
95 /// Islands - Clumps of constants placed in the function.
96 /// Water - Potential places where an island could be formed.
97 /// CPE - A constant pool entry that has been placed somewhere, which
98 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000099 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000100 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +0000101
Evan Cheng10043e22007-01-19 07:51:42 +0000102 /// WaterList - A sorted list of basic blocks where islands could be placed
103 /// (i.e. blocks that don't fall through to the following block, due
104 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +0000105 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000106
Bob Wilson2f9be502009-10-15 20:49:47 +0000107 /// NewWaterList - The subset of WaterList that was created since the
108 /// previous iteration by inserting unconditional branches.
109 SmallSet<MachineBasicBlock*, 4> NewWaterList;
110
Eugene Zelenko076468c2017-09-20 21:35:51 +0000111 using water_iterator = std::vector<MachineBasicBlock *>::iterator;
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000112
Evan Cheng10043e22007-01-19 07:51:42 +0000113 /// CPUser - One user of a constant pool, keeping the machine instruction
114 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +0000115 /// allowed from the instruction to the CP. The HighWaterMark records the
116 /// highest basic block where a new CPEntry can be placed. To ensure this
117 /// pass terminates, the CP entries are initially placed at the end of the
118 /// function and then move monotonically to lower addresses. The
119 /// exception to this rule is when the current CP entry for a particular
120 /// CPUser is out of range, but there is another CP entry for the same
121 /// constant value in range. We want to use the existing in-range CP
122 /// entry, but if it later moves out of range, the search for new water
123 /// should resume where it left off. The HighWaterMark is used to record
124 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000125 struct CPUser {
126 MachineInstr *MI;
127 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000128 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000129 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000130 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000131 bool IsSoImm;
Eugene Zelenko076468c2017-09-20 21:35:51 +0000132 bool KnownAlignment = false;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000133
Evan Chengd2919a12009-07-23 18:27:47 +0000134 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
135 bool neg, bool soimm)
Eugene Zelenko076468c2017-09-20 21:35:51 +0000136 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000137 HighWaterMark = CPEMI->getParent();
138 }
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000139
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000140 /// getMaxDisp - Returns the maximum displacement supported by MI.
141 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000142 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000143 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000144 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000145 }
Evan Cheng10043e22007-01-19 07:51:42 +0000146 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000147
Evan Cheng10043e22007-01-19 07:51:42 +0000148 /// CPUsers - Keep track of all of the machine instructions that use various
149 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000150 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000151
Evan Cheng8b7700f2007-02-09 20:54:44 +0000152 /// CPEntry - One per constant pool entry, keeping the machine instruction
153 /// pointer, the constpool index, and the number of CPUser's which
154 /// reference this entry.
155 struct CPEntry {
156 MachineInstr *CPEMI;
157 unsigned CPI;
158 unsigned RefCount;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000159
Evan Cheng8b7700f2007-02-09 20:54:44 +0000160 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
161 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
162 };
163
164 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000165 /// instructions. For each original constpool index (i.e. those that existed
166 /// upon entry to this pass), it keeps a vector of entries. Original
167 /// elements are cloned as we go along; the clones are put in the vector of
168 /// the original element, but have distinct CPIs.
169 ///
170 /// The first half of CPEntries contains generic constants, the second half
171 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
172 /// which vector it will be in here.
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000173 std::vector<std::vector<CPEntry>> CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000174
Tim Northovera603c402015-05-31 19:22:07 +0000175 /// Maps a JT index to the offset in CPEntries containing copies of that
176 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
177 DenseMap<int, int> JumpTableEntryIndices;
178
179 /// Maps a JT index to the LEA that actually uses the index to calculate its
180 /// base address.
181 DenseMap<int, int> JumpTableUserIndices;
182
Evan Cheng22c7cf52007-01-25 03:12:46 +0000183 /// ImmBranch - One per immediate branch, keeping the machine instruction
184 /// pointer, conditional or unconditional, the max displacement,
185 /// and (if isCond is true) the corresponding unconditional branch
186 /// opcode.
187 struct ImmBranch {
188 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000189 unsigned MaxDisp : 31;
190 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000191 unsigned UncondBr;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000192
Matthias Braunfa3872e2015-05-18 20:27:55 +0000193 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000194 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000195 };
196
Evan Chengc95f95b2007-05-16 05:14:06 +0000197 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng540f5e02007-02-09 23:59:14 +0000198 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000199
Evan Cheng7fa69642007-01-30 01:18:38 +0000200 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000201 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000202
Evan Chengc6d70ae2009-07-29 02:18:14 +0000203 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
204 SmallVector<MachineInstr*, 4> T2JumpTables;
205
Evan Cheng7fa69642007-01-30 01:18:38 +0000206 /// HasFarJump - True if any far jump instruction has been emitted during
207 /// the branch fix up pass.
208 bool HasFarJump;
209
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000210 MachineFunction *MF;
211 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000212 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000213 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000214 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000215 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000216 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000217 bool isThumb2;
James Molloy70a3d6d2016-11-01 13:37:41 +0000218 bool isPositionIndependentOrROPI;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000219
Evan Cheng10043e22007-01-19 07:51:42 +0000220 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000221 static char ID;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000222
Owen Andersona7aed182010-08-06 18:33:48 +0000223 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000224
Craig Topper6bc27bf2014-03-10 02:09:33 +0000225 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000226
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000227 MachineFunctionProperties getRequiredProperties() const override {
228 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000229 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000230 }
231
Mehdi Amini117296c2016-10-01 02:56:57 +0000232 StringRef getPassName() const override {
James Molloy9b3b8992017-02-13 14:07:25 +0000233 return ARM_CP_ISLANDS_OPT_NAME;
Evan Cheng10043e22007-01-19 07:51:42 +0000234 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000235
Evan Cheng10043e22007-01-19 07:51:42 +0000236 private:
Tim Northovera603c402015-05-31 19:22:07 +0000237 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
238 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000239 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000240 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000241 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000242 void scanFunctionJumpTables();
243 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
244 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
245 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
246 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
247 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000248 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000249 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
250 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000251 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000252 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000253 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000254 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000255 void removeDeadCPEMI(MachineInstr *CPEMI);
256 bool removeUnusedCPEntries();
257 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
258 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
259 bool DoDump = false);
260 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000261 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000262 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
263 bool fixupImmediateBr(ImmBranch &Br);
264 bool fixupConditionalBr(ImmBranch &Br);
265 bool fixupUnconditionalBr(ImmBranch &Br);
266 bool undoLRSpillRestore();
Jim Grosbach190e7b62012-03-23 23:07:03 +0000267 bool optimizeThumb2Instructions();
268 bool optimizeThumb2Branches();
269 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000270 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
271 unsigned &DeadSize, bool &CanDeleteLEA,
272 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000273 bool optimizeThumb2JumpTables();
274 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000275 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000276
Jim Grosbach190e7b62012-03-23 23:07:03 +0000277 unsigned getOffsetOf(MachineInstr *MI) const;
278 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000279 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000280 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000281
Jim Grosbach190e7b62012-03-23 23:07:03 +0000282 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000283 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000284 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000285 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000286 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000287 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000288 }
Evan Cheng10043e22007-01-19 07:51:42 +0000289 };
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000290
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000291} // end anonymous namespace
Evan Cheng10043e22007-01-19 07:51:42 +0000292
Eugene Zelenko076468c2017-09-20 21:35:51 +0000293char ARMConstantIslands::ID = 0;
294
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000295/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000296void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000297#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000298 assert(std::is_sorted(MF->begin(), MF->end(),
299 [this](const MachineBasicBlock &LHS,
300 const MachineBasicBlock &RHS) {
301 return BBInfo[LHS.getNumber()].postOffset() <
302 BBInfo[RHS.getNumber()].postOffset();
303 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000304 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000305 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
306 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000307 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000308 // Verify offset using the real max displacement without the safety
309 // adjustment.
310 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000311 /* DoDump = */ true)) {
312 DEBUG(dbgs() << "OK\n");
313 continue;
314 }
315 DEBUG(dbgs() << "Out of range.\n");
316 dumpBBs();
317 DEBUG(MF->dump());
318 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000319 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000320#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000321}
322
Aaron Ballman615eb472017-10-15 14:32:27 +0000323#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000324/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000325LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000326 DEBUG({
327 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
328 const BasicBlockInfo &BBI = BBInfo[J];
329 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
330 << " kb=" << unsigned(BBI.KnownBits)
331 << " ua=" << unsigned(BBI.Unalign)
332 << " pa=" << unsigned(BBI.PostAlign)
333 << format(" size=%#x\n", BBInfo[J].Size);
334 }
335 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000336}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000337#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000338
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000339bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
340 MF = &mf;
341 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000342
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000343 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000344 << MCP->getConstants().size() << " CP entries, aligned to "
345 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000346
Eric Christopher1b21f002015-01-29 00:19:33 +0000347 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
348 TII = STI->getInstrInfo();
James Molloy70a3d6d2016-11-01 13:37:41 +0000349 isPositionIndependentOrROPI =
350 STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000351 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000352
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000353 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000354 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000355 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000356
357 HasFarJump = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000358 bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
Evan Cheng7fa69642007-01-30 01:18:38 +0000359
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000360 // This pass invalidates liveness information when it splits basic blocks.
361 MF->getRegInfo().invalidateLiveness();
362
Evan Cheng10043e22007-01-19 07:51:42 +0000363 // Renumber all of the machine basic blocks in the function, guaranteeing that
364 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000365 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000366
Jim Grosbach5d577142009-11-12 17:25:07 +0000367 // Try to reorder and otherwise adjust the block layout to make good use
368 // of the TB[BH] instructions.
369 bool MadeChange = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000370 if (GenerateTBB && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000371 scanFunctionJumpTables();
372 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000373 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000374 T2JumpTables.clear();
375 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000376 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000377 }
378
Evan Cheng10043e22007-01-19 07:51:42 +0000379 // Perform the initial placement of the constant pool entries. To start with,
380 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000381 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000382 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000383 doInitialConstPlacement(CPEMIs);
384
385 if (MF->getJumpTableInfo())
386 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000387
Evan Cheng10043e22007-01-19 07:51:42 +0000388 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000389 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000390
Evan Cheng10043e22007-01-19 07:51:42 +0000391 // Do the initial scan of the function, building up information about the
392 // sizes of each block, the location of all the water, and finding all of the
393 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000394 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000395 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000396 DEBUG(dumpBBs());
397
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000398 // Functions with jump tables need an alignment of 4 because they use the ADR
399 // instruction, which aligns the PC to 4 bytes before adding an offset.
400 if (!T2JumpTables.empty())
401 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000402
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000403 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000404 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000405
Evan Cheng7fa69642007-01-30 01:18:38 +0000406 // Iteratively place constant pool entries and fix up branches until there
407 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000408 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000409 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000410 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000411 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000412 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000413 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000414 // If it doesn't end in 10, the input may have huge BB or many CPEs.
415 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000416 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
417 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000418 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000419 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000420
Bob Wilson2f9be502009-10-15 20:49:47 +0000421 // Clear NewWaterList now. If we split a block for branches, it should
422 // appear as "new water" for the next iteration of constant pool placement.
423 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000424
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000425 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000426 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000427 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000428 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000429 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000430 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000431 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000432
433 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000434 break;
435 MadeChange = true;
436 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000437
Bradley Smitha1189102016-01-15 10:26:17 +0000438 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000439 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000440 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000441
Bradley Smitha1189102016-01-15 10:26:17 +0000442 // Shrink 32-bit branch instructions.
443 if (isThumb && STI->hasV8MBaselineOps())
444 MadeChange |= optimizeThumb2Branches();
445
446 // Optimize jump tables using TBB / TBH.
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000447 if (GenerateTBB && !STI->genExecuteOnly())
Bradley Smitha1189102016-01-15 10:26:17 +0000448 MadeChange |= optimizeThumb2JumpTables();
449
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000450 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000451 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000452
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000453 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
454 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000455 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000456 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000457
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000458 // Save the mapping between original and cloned constpool entries.
459 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
460 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
461 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000462 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
463 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000464 }
465 }
466
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000467 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000468
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000469 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000470 WaterList.clear();
471 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000472 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000473 JumpTableEntryIndices.clear();
474 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000475 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000476 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000477 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000478
479 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000480}
481
Tim Northovera603c402015-05-31 19:22:07 +0000482/// \brief Perform the initial placement of the regular constant pool entries.
483/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000484void
Tim Northovera603c402015-05-31 19:22:07 +0000485ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000486 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000487 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
488 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000489
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000490 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000491 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000492
493 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000494 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000495
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000496 // The function needs to be as aligned as the basic blocks. The linker may
497 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000498 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000499
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000500 // Order the entries in BB by descending alignment. That ensures correct
501 // alignment of all entries as long as BB is sufficiently aligned. Keep
502 // track of the insertion point for each alignment. We are going to bucket
503 // sort the entries as they are created.
504 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000505
Evan Cheng10043e22007-01-19 07:51:42 +0000506 // Add all of the constants from the constant pool to the end block, use an
507 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000508 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000509
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000510 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000511 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000512 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000513 assert(Size >= 4 && "Too small constant pool entry");
514 unsigned Align = CPs[i].getAlignment();
515 assert(isPowerOf2_32(Align) && "Invalid alignment");
516 // Verify that all constant pool entries are a multiple of their alignment.
517 // If not, we would have to pad them out so that instructions stay aligned.
518 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
519
520 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
521 unsigned LogAlign = Log2_32(Align);
522 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000523 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000524 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000525 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000526 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000527
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000528 // Ensure that future entries with higher alignment get inserted before
529 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000530 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000531 if (InsPoint[a] == InsAt)
532 InsPoint[a] = CPEMI;
533
Evan Cheng8b7700f2007-02-09 20:54:44 +0000534 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000535 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000536 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000537 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
538 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000539 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000540 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000541}
542
Tim Northovera603c402015-05-31 19:22:07 +0000543/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
544/// instructions can be made more efficient if the jump table immediately
545/// follows the instruction, it's best to place them immediately next to their
546/// jumps to begin with. In almost all cases they'll never be moved from that
547/// position.
548void ARMConstantIslands::doInitialJumpTablePlacement(
549 std::vector<MachineInstr *> &CPEMIs) {
550 unsigned i = CPEntries.size();
551 auto MJTI = MF->getJumpTableInfo();
552 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
553
554 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
555 for (MachineBasicBlock &MBB : *MF) {
556 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000557 if (MI == MBB.end())
558 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000559
560 unsigned JTOpcode;
561 switch (MI->getOpcode()) {
562 default:
563 continue;
564 case ARM::BR_JTadd:
565 case ARM::BR_JTr:
566 case ARM::tBR_JTr:
567 case ARM::BR_JTm:
568 JTOpcode = ARM::JUMPTABLE_ADDRS;
569 break;
570 case ARM::t2BR_JT:
571 JTOpcode = ARM::JUMPTABLE_INSTS;
572 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000573 case ARM::tTBB_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000574 case ARM::t2TBB_JT:
575 JTOpcode = ARM::JUMPTABLE_TBB;
576 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000577 case ARM::tTBH_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000578 case ARM::t2TBH_JT:
579 JTOpcode = ARM::JUMPTABLE_TBH;
580 break;
581 }
582
583 unsigned NumOps = MI->getDesc().getNumOperands();
584 MachineOperand JTOp =
585 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
586 unsigned JTI = JTOp.getIndex();
587 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
588 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
589 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
590 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
591 DebugLoc(), TII->get(JTOpcode))
592 .addImm(i++)
593 .addJumpTableIndex(JTI)
594 .addImm(Size);
595 CPEMIs.push_back(CPEMI);
596 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
597 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
598 if (!LastCorrectlyNumberedBB)
599 LastCorrectlyNumberedBB = &MBB;
600 }
601
602 // If we did anything then we need to renumber the subsequent blocks.
603 if (LastCorrectlyNumberedBB)
604 MF->RenumberBlocks(LastCorrectlyNumberedBB);
605}
606
Dale Johannesene18b13b2007-02-23 05:02:36 +0000607/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000608/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000609bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000610 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000611 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000612 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000613 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000614 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000615
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000616 MachineBasicBlock *NextBB = &*std::next(MBBI);
David Majnemer42531262016-08-12 03:55:06 +0000617 if (!MBB->isSuccessor(NextBB))
Tim Northoverab85dcc2014-11-13 17:58:51 +0000618 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000619
Tim Northoverab85dcc2014-11-13 17:58:51 +0000620 // Try to analyze the end of the block. A potential fallthrough may already
621 // have an unconditional branch for whatever reason.
622 MachineBasicBlock *TBB, *FBB;
623 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000624 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000625 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000626}
627
Evan Cheng8b7700f2007-02-09 20:54:44 +0000628/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
629/// look up the corresponding CPEntry.
Eugene Zelenko076468c2017-09-20 21:35:51 +0000630ARMConstantIslands::CPEntry *
631ARMConstantIslands::findConstPoolEntry(unsigned CPI,
632 const MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +0000633 std::vector<CPEntry> &CPEs = CPEntries[CPI];
634 // Number of entries per constpool index should be small, just do a
635 // linear search.
636 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
637 if (CPEs[i].CPEMI == CPEMI)
638 return &CPEs[i];
639 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000640 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000641}
642
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000643/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000644/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000645unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000646 switch (CPEMI->getOpcode()) {
647 case ARM::CONSTPOOL_ENTRY:
648 break;
649 case ARM::JUMPTABLE_TBB:
James Molloy70a3d6d2016-11-01 13:37:41 +0000650 return isThumb1 ? 2 : 0;
Tim Northovera603c402015-05-31 19:22:07 +0000651 case ARM::JUMPTABLE_TBH:
James Molloy70a3d6d2016-11-01 13:37:41 +0000652 return isThumb1 ? 2 : 1;
Tim Northovera603c402015-05-31 19:22:07 +0000653 case ARM::JUMPTABLE_INSTS:
654 return 1;
655 case ARM::JUMPTABLE_ADDRS:
656 return 2;
657 default:
658 llvm_unreachable("unknown constpool entry kind");
659 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000660
Tim Northovera603c402015-05-31 19:22:07 +0000661 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000662 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
663 unsigned Align = MCP->getConstants()[CPI].getAlignment();
664 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
665 return Log2_32(Align);
666}
667
Jim Grosbach190e7b62012-03-23 23:07:03 +0000668/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000669/// information about the sizes of each block and the locations of all
670/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000671void ARMConstantIslands::scanFunctionJumpTables() {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000672 for (MachineBasicBlock &MBB : *MF) {
673 for (MachineInstr &I : MBB)
James Molloy70a3d6d2016-11-01 13:37:41 +0000674 if (I.isBranch() &&
675 (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000676 T2JumpTables.push_back(&I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000677 }
678}
679
Jim Grosbach190e7b62012-03-23 23:07:03 +0000680/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000681/// information about the sizes of each block, the location of all the water,
682/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000683void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000684initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000685
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000686 BBInfo = computeAllBlockSizes(MF);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000687
688 // The known bits of the entry block offset are determined by the function
689 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000690 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000691
692 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000693 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000694
Bill Wendling18581a42010-12-21 01:54:40 +0000695 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000696 for (MachineBasicBlock &MBB : *MF) {
Evan Cheng10043e22007-01-19 07:51:42 +0000697 // If this block doesn't fall through into the next MBB, then this is
698 // 'water' that a constant pool island could be placed.
699 if (!BBHasFallthrough(&MBB))
700 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000701
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000702 for (MachineInstr &I : MBB) {
703 if (I.isDebugValue())
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000704 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000705
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000706 unsigned Opc = I.getOpcode();
707 if (I.isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000708 bool isCond = false;
709 unsigned Bits = 0;
710 unsigned Scale = 1;
711 int UOpc = Opc;
712 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000713 default:
714 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000715 case ARM::t2BR_JT:
James Molloy70a3d6d2016-11-01 13:37:41 +0000716 case ARM::tBR_JTr:
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000717 T2JumpTables.push_back(&I);
Evan Chengc6d70ae2009-07-29 02:18:14 +0000718 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000719 case ARM::Bcc:
720 isCond = true;
721 UOpc = ARM::B;
Justin Bognerb03fd122016-08-17 05:10:15 +0000722 LLVM_FALLTHROUGH;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000723 case ARM::B:
724 Bits = 24;
725 Scale = 4;
726 break;
727 case ARM::tBcc:
728 isCond = true;
729 UOpc = ARM::tB;
730 Bits = 8;
731 Scale = 2;
732 break;
733 case ARM::tB:
734 Bits = 11;
735 Scale = 2;
736 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000737 case ARM::t2Bcc:
738 isCond = true;
739 UOpc = ARM::t2B;
740 Bits = 20;
741 Scale = 2;
742 break;
743 case ARM::t2B:
744 Bits = 24;
745 Scale = 2;
746 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000747 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000748
749 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000750 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000751 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000752 }
753
Evan Cheng7fa69642007-01-30 01:18:38 +0000754 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000755 PushPopMIs.push_back(&I);
Evan Cheng7fa69642007-01-30 01:18:38 +0000756
Tim Northovera603c402015-05-31 19:22:07 +0000757 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
758 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
759 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000760 continue;
761
Evan Cheng10043e22007-01-19 07:51:42 +0000762 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000763 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
764 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000765 // We found one. The addressing mode tells us the max displacement
766 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000767
Evan Cheng10043e22007-01-19 07:51:42 +0000768 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000769 unsigned Bits = 0;
770 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000771 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000772 bool IsSoImm = false;
773
774 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000775 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000776 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000777
778 // Taking the address of a CP entry.
779 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000780 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000781 // This takes a SoImm, which is 8 bit immediate rotated. We'll
782 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000783 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000784 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000785 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000786 Scale = 4;
787 NegOk = true;
788 IsSoImm = true;
789 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000790 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000791 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000792 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000793 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000794 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000795 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000796 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000797 Bits = 8;
798 Scale = 4;
799 break;
800
David Majnemer452f1f92013-06-04 17:46:15 +0000801 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000802 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000803 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000804 case ARM::t2LDRpci:
James Molloy9abb2fa2016-09-26 07:26:24 +0000805 case ARM::t2LDRHpci:
Kristof Beyls5ac6adb2017-02-23 12:24:55 +0000806 case ARM::t2LDRBpci:
Evan Chengfd522992007-02-01 20:44:52 +0000807 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000808 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000809 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000810
811 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000812 Bits = 8;
813 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000814 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000815
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000816 case ARM::VLDRD:
817 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000818 Bits = 8;
819 Scale = 4; // +-(offset_8*4)
820 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000821 break;
James Molloy9abb2fa2016-09-26 07:26:24 +0000822
823 case ARM::tLDRHi:
824 Bits = 5;
825 Scale = 2; // +(offset_5*2)
826 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000827 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000828
Evan Cheng10043e22007-01-19 07:51:42 +0000829 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000830 unsigned CPI = I.getOperand(op).getIndex();
831 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000832 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
833 CPI = JumpTableEntryIndices[CPI];
834 }
835
Evan Cheng8b7700f2007-02-09 20:54:44 +0000836 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000837 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000838 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000839
840 // Increment corresponding CPEntry reference count.
841 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
842 assert(CPE && "Cannot find a corresponding CPEntry!");
843 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000844
Evan Cheng10043e22007-01-19 07:51:42 +0000845 // Instructions can only use one CP entry, don't bother scanning the
846 // rest of the operands.
847 break;
848 }
849 }
Evan Cheng10043e22007-01-19 07:51:42 +0000850 }
851}
852
Jim Grosbach190e7b62012-03-23 23:07:03 +0000853/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000854/// from the start of the function. This offset changes as stuff is moved
855/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000856unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000857 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000858
Evan Cheng10043e22007-01-19 07:51:42 +0000859 // The offset is composed of two things: the sum of the sizes of all MBB's
860 // before this instruction's block, and the offset from the start of the block
861 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000862 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000863
864 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000865 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000866 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000867 Offset += TII->getInstSizeInBytes(*I);
Evan Cheng10043e22007-01-19 07:51:42 +0000868 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000869 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000870}
871
872/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
873/// ID.
874static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
875 const MachineBasicBlock *RHS) {
876 return LHS->getNumber() < RHS->getNumber();
877}
878
Jim Grosbach190e7b62012-03-23 23:07:03 +0000879/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000880/// machine function, it upsets all of the block numbers. Renumber the blocks
881/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000882void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000883 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000884 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000885
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000886 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000887 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000888 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000889
890 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000891 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000892 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000893 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
894 CompareMBBNumbers);
895 WaterList.insert(IP, NewBB);
896}
897
Evan Cheng10043e22007-01-19 07:51:42 +0000898/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000899/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000900/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000901MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000902 MachineBasicBlock *OrigBB = MI->getParent();
903
904 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000905 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000906 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000907 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000908 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000909
Evan Cheng10043e22007-01-19 07:51:42 +0000910 // Splice the instructions starting with MI over to NewBB.
911 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000912
Evan Cheng10043e22007-01-19 07:51:42 +0000913 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000914 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000915 // There doesn't seem to be meaningful DebugInfo available; this doesn't
916 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000917 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000918 if (!isThumb)
919 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
920 else
Diana Picusbd66b7d2017-01-20 08:15:24 +0000921 BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
922 .addMBB(NewBB)
923 .add(predOps(ARMCC::AL));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000924 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000925
Evan Cheng10043e22007-01-19 07:51:42 +0000926 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000927 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000928
Evan Cheng10043e22007-01-19 07:51:42 +0000929 // OrigBB branches to NewBB.
930 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000931
Evan Cheng10043e22007-01-19 07:51:42 +0000932 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000933 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000934 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000935 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000936
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000937 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000938 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000939 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000940
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000941 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000942 // available water after it (but not if it's already there, which happens
943 // when splitting before a conditional branch that is followed by an
944 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000945 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000946 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
947 CompareMBBNumbers);
948 MachineBasicBlock* WaterBB = *IP;
949 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000950 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000951 else
952 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000953 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000954
Dale Johannesenc17dd572010-07-23 22:50:23 +0000955 // Figure out how large the OrigBB is. As the first half of the original
956 // block, it cannot contain a tablejump. The size includes
957 // the new jump we added. (It should be possible to do this without
958 // recounting everything, but it's very confusing, and this is rarely
959 // executed.)
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000960 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000961
Dale Johannesenc17dd572010-07-23 22:50:23 +0000962 // Figure out how large the NewMBB is. As the second half of the original
963 // block, it may contain a tablejump.
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000964 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000965
Dale Johannesen01ee5752007-02-25 00:47:03 +0000966 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000967 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000968
969 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000970}
971
Jim Grosbach190e7b62012-03-23 23:07:03 +0000972/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000973/// displacement computation. Update U.KnownAlignment to match its current
974/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000975unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
976 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000977 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
978 unsigned KnownBits = BBI.internalKnownBits();
979
980 // The value read from PC is offset from the actual instruction address.
981 UserOffset += (isThumb ? 4 : 8);
982
983 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
984 // Make sure U.getMaxDisp() returns a constrained range.
985 U.KnownAlignment = (KnownBits >= 2);
986
987 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
988 // purposes of the displacement computation; compensate for that here.
989 // For unknown alignments, getMaxDisp() constrains the range instead.
990 if (isThumb && U.KnownAlignment)
991 UserOffset &= ~3u;
992
993 return UserOffset;
994}
995
Jim Grosbach190e7b62012-03-23 23:07:03 +0000996/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000997/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000998/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000999/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001000/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1001/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001002bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +00001003 unsigned TrialOffset, unsigned MaxDisp,
1004 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +00001005 if (UserOffset <= TrialOffset) {
1006 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +00001007 if (TrialOffset - UserOffset <= MaxDisp)
1008 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001009 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001010 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +00001011 if (UserOffset - TrialOffset <= MaxDisp)
1012 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001013 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001014 }
1015 return false;
1016}
1017
Jim Grosbach190e7b62012-03-23 23:07:03 +00001018/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +00001019/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001020///
1021/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001022bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001023 MachineBasicBlock* Water, CPUser &U,
1024 unsigned &Growth) {
1025 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1026 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1027 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001028 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001029 if (++NextBlock == MF->end()) {
1030 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1031 NextBlockAlignment = 0;
1032 } else {
1033 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1034 NextBlockAlignment = NextBlock->getAlignment();
1035 }
1036 unsigned Size = U.CPEMI->getOperand(2).getImm();
1037 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001038
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001039 // The CPE may be able to hide in the alignment padding before the next
1040 // block. It may also cause more padding to be required if it is more aligned
1041 // that the next block.
1042 if (CPEEnd > NextBlockOffset) {
1043 Growth = CPEEnd - NextBlockOffset;
1044 // Compute the padding that would go at the end of the CPE to align the next
1045 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001046 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001047
1048 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001049 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001050 // in blocks between CPE and the user.
1051 if (CPEOffset < UserOffset)
1052 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1053 } else
1054 // CPE fits in existing padding.
1055 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001056
Jim Grosbach190e7b62012-03-23 23:07:03 +00001057 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001058}
1059
Jim Grosbach190e7b62012-03-23 23:07:03 +00001060/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001061/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001062bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001063 MachineInstr *CPEMI, unsigned MaxDisp,
1064 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001065 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001066
Dale Johannesene18b13b2007-02-23 05:02:36 +00001067 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001068 DEBUG({
1069 unsigned Block = MI->getParent()->getNumber();
1070 const BasicBlockInfo &BBI = BBInfo[Block];
1071 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1072 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001073 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001074 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001075 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1076 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1077 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001078 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001079 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001080
Jim Grosbach190e7b62012-03-23 23:07:03 +00001081 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001082}
1083
Evan Chenge4510972009-01-28 00:53:34 +00001084#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001085/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1086/// unconditionally branches to its only successor.
1087static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1088 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1089 return false;
1090
1091 MachineBasicBlock *Succ = *MBB->succ_begin();
1092 MachineBasicBlock *Pred = *MBB->pred_begin();
1093 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001094 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1095 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001096 return PredMI->getOperand(0).getMBB() == Succ;
1097 return false;
1098}
Evan Chenge4510972009-01-28 00:53:34 +00001099#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001100
Jim Grosbach190e7b62012-03-23 23:07:03 +00001101void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001102 unsigned BBNum = BB->getNumber();
1103 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001104 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001105 // Include the alignment of the current block.
1106 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1107 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1108 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001109
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001110 // This is where block i begins. Stop if the offset is already correct,
1111 // and we have updated 2 blocks. This is the maximum number of blocks
1112 // changed before calling this function.
1113 if (i > BBNum + 2 &&
1114 BBInfo[i].Offset == Offset &&
1115 BBInfo[i].KnownBits == KnownBits)
1116 break;
1117
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001118 BBInfo[i].Offset = Offset;
1119 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001120 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001121}
1122
Jim Grosbach190e7b62012-03-23 23:07:03 +00001123/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001124/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001125/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001126/// the entry, false if we didn't.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001127bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1128 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001129 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001130 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1131 assert(CPE && "Unexpected!");
1132 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001133 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001134 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001135 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001136 return true;
1137 }
1138 return false;
1139}
1140
Tim Northovera603c402015-05-31 19:22:07 +00001141unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1142 if (CPEMI->getOperand(1).isCPI())
1143 return CPEMI->getOperand(1).getIndex();
1144
1145 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1146}
1147
Dale Johannesene18b13b2007-02-23 05:02:36 +00001148/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1149/// if not, see if an in-range clone of the CPE is in range, and if so,
1150/// change the data structures so the user references the clone. Returns:
1151/// 0 = no existing entry found
1152/// 1 = entry found, and there were no code insertions or deletions
1153/// 2 = entry found, and there were code insertions or deletions
Eugene Zelenko076468c2017-09-20 21:35:51 +00001154int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001155 MachineInstr *UserMI = U.MI;
1156 MachineInstr *CPEMI = U.CPEMI;
1157
1158 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001159 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1160 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001161 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001162 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001163 }
1164
Dale Johannesene18b13b2007-02-23 05:02:36 +00001165 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001166 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001167 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1168 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1169 // We already tried this one
1170 if (CPEs[i].CPEMI == CPEMI)
1171 continue;
1172 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001173 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001174 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001175 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001176 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001177 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001178 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001179 // Point the CPUser node to the replacement
1180 U.CPEMI = CPEs[i].CPEMI;
1181 // Change the CPI in the instruction operand to refer to the clone.
1182 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001183 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001184 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001185 break;
1186 }
1187 // Adjust the refcount of the clone...
1188 CPEs[i].RefCount++;
1189 // ...and the original. If we didn't remove the old entry, none of the
1190 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001191 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001192 }
1193 }
1194 return 0;
1195}
1196
Dale Johannesen440995b2007-02-28 18:41:23 +00001197/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1198/// the specific unconditional branch instruction.
1199static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001200 switch (Opc) {
1201 case ARM::tB:
1202 return ((1<<10)-1)*2;
1203 case ARM::t2B:
1204 return ((1<<23)-1)*2;
1205 default:
1206 break;
1207 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001208
David Goodwin27303cd2009-06-30 18:04:13 +00001209 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001210}
1211
Jim Grosbach190e7b62012-03-23 23:07:03 +00001212/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001213/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001214/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001215/// is set to the WaterList entry. For Thumb, prefer water that will not
1216/// introduce padding to water that will. To ensure that this pass
1217/// terminates, the CPE location for a particular CPUser is only allowed to
1218/// move to a lower address, so search backward from the end of the list and
1219/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001220bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001221 water_iterator &WaterIter,
1222 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001223 if (WaterList.empty())
1224 return false;
1225
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001226 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001227 // The nearest water without splitting the UserBB is right after it.
1228 // If the distance is still large (we have a big BB), then we need to split it
1229 // if we don't converge after certain iterations. This helps the following
1230 // situation to converge:
1231 // BB0:
1232 // Big BB
1233 // BB1:
1234 // Constant Pool
1235 // When a CP access is out of range, BB0 may be used as water. However,
1236 // inserting islands between BB0 and BB1 makes other accesses out of range.
1237 MachineBasicBlock *UserBB = U.MI->getParent();
1238 unsigned MinNoSplitDisp =
1239 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1240 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1241 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001242 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001243 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001244 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001245 // Check if water is in range and is either at a lower address than the
1246 // current "high water mark" or a new water block that was created since
1247 // the previous iteration by inserting an unconditional branch. In the
1248 // latter case, we want to allow resetting the high water mark back to
1249 // this new water since we haven't seen it before. Inserting branches
1250 // should be relatively uncommon and when it does happen, we want to be
1251 // sure to take advantage of it for all the CPEs near that block, so that
1252 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001253 // When CloserWater is true, we try to find the lowest address after (or
1254 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001255 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001256 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001257 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001258 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1259 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001260 // This is the least amount of required padding seen so far.
1261 BestGrowth = Growth;
1262 WaterIter = IP;
1263 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1264 << " Growth=" << Growth << '\n');
1265
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001266 if (CloserWater && WaterBB == U.MI->getParent())
1267 return true;
1268 // Keep looking unless it is perfect and we're not looking for the lowest
1269 // possible address.
1270 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001271 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001272 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001273 if (IP == B)
1274 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001275 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001276 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001277}
1278
Jim Grosbach190e7b62012-03-23 23:07:03 +00001279/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001280/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1281/// block is used if in range, and the conditional branch munged so control
1282/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001283/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001284/// block following which the new island can be inserted (the WaterList
1285/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001286void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001287 unsigned UserOffset,
1288 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001289 CPUser &U = CPUsers[CPUserIndex];
1290 MachineInstr *UserMI = U.MI;
1291 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001292 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001293 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001294 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001295
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001296 // If the block does not end in an unconditional branch already, and if the
1297 // end of the block is within range, make new water there. (The addition
1298 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001299 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001300 if (BBHasFallthrough(UserMBB)) {
1301 // Size of branch to insert.
1302 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001303 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001304 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001305
Jim Grosbach190e7b62012-03-23 23:07:03 +00001306 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001307 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1308 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001309 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001310 // Add an unconditional branch from UserMBB to fallthrough block. Record
1311 // it for branch lengthening; this new branch will not get out of range,
1312 // but if the preceding conditional branch is out of range, the targets
1313 // will be exchanged, and the altered branch may be out of range, so the
1314 // machinery has to know about it.
1315 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1316 if (!isThumb)
1317 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1318 else
Diana Picusbd66b7d2017-01-20 08:15:24 +00001319 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1320 .addMBB(NewMBB)
1321 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001322 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1323 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1324 MaxDisp, false, UncondBr));
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +00001325 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001326 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001327 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001328 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001329 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001330
1331 // What a big block. Find a place within the block to split it. This is a
1332 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1333 // entries are 4 bytes: if instruction I references island CPE, and
1334 // instruction I+1 references CPE', it will not work well to put CPE as far
1335 // forward as possible, since then CPE' cannot immediately follow it (that
1336 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1337 // need to create a new island. So, we make a first guess, then walk through
1338 // the instructions between the one currently being looked at and the
1339 // possible insertion point, and make sure any other instructions that
1340 // reference CPEs will be able to use the same island area; if not, we back
1341 // up the insertion point.
1342
1343 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001344 // point where we can add a 4-byte branch instruction, and then align to
1345 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001346 unsigned LogAlign = MF->getAlignment();
1347 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1348 unsigned KnownBits = UserBBI.internalKnownBits();
1349 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001350 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001351 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1352 BaseInsertOffset));
1353
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001354 // The 4 in the following is for the unconditional branch we'll be inserting
1355 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001356 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001357 BaseInsertOffset -= 4;
1358
1359 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1360 << " la=" << LogAlign
1361 << " kb=" << KnownBits
1362 << " up=" << UPad << '\n');
1363
1364 // This could point off the end of the block if we've already got constant
1365 // pool entries following this block; only the last one is in the water list.
1366 // Back past any possible branches (allow for a conditional and a maximally
1367 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001368 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001369 // Ensure BaseInsertOffset is larger than the offset of the instruction
1370 // following UserMI so that the loop which searches for the split point
1371 // iterates at least once.
1372 BaseInsertOffset =
1373 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001374 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001375 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1376 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001377 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001378 CPEMI->getOperand(2).getImm();
1379 MachineBasicBlock::iterator MI = UserMI;
1380 ++MI;
1381 unsigned CPUIndex = CPUserIndex+1;
1382 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001383 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001384 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001385 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001386 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001387 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001388 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001389 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001390 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001391 // Shift intertion point by one unit of alignment so it is within reach.
1392 BaseInsertOffset -= 1u << LogAlign;
1393 EndInsertOffset -= 1u << LogAlign;
1394 }
1395 // This is overly conservative, as we don't account for CPEMIs being
1396 // reused within the block, but it doesn't matter much. Also assume CPEs
1397 // are added in order with alignment padding. We may eventually be able
1398 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001399 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001400 CPUIndex++;
1401 }
1402
1403 // Remember the last IT instruction.
1404 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001405 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001406 }
1407
1408 --MI;
1409
1410 // Avoid splitting an IT block.
1411 if (LastIT) {
1412 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001413 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001414 if (CC != ARMCC::AL)
1415 MI = LastIT;
1416 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001417
1418 // We really must not split an IT block.
1419 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001420 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001421
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001422 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001423}
1424
Jim Grosbach190e7b62012-03-23 23:07:03 +00001425/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001426/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001427/// place in-range. Return true if we changed any addresses (thus must run
1428/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001429bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1430 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001431 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001432 MachineInstr *UserMI = U.MI;
1433 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001434 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001435 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001436 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001437 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001438
Dale Johannesene18b13b2007-02-23 05:02:36 +00001439 // See if the current entry is within range, or there is a clone of it
1440 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001441 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001442 if (result==1) return false;
1443 else if (result==2) return true;
1444
1445 // No existing clone of this CPE is within range.
1446 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001447 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001448
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001449 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001450 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001451 MachineBasicBlock *NewMBB;
1452 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001453 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001454 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001455 MachineBasicBlock *WaterBB = *IP;
1456
1457 // If the original WaterList entry was "new water" on this iteration,
1458 // propagate that to the new island. This is just keeping NewWaterList
1459 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001460 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001461 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001462
Bob Wilson2f9be502009-10-15 20:49:47 +00001463 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001464 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001465 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001466 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001467 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001468 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001469
Jim Grosbach190e7b62012-03-23 23:07:03 +00001470 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001471 // called while handling branches so that the water will be seen on the
1472 // next iteration for constant pools, but in this context, we don't want
1473 // it. Check for this so it will be removed from the WaterList.
1474 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001475 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
David Majnemer0d955d02016-08-11 22:21:41 +00001476 IP = find(WaterList, WaterBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001477 if (IP != WaterList.end())
1478 NewWaterList.erase(WaterBB);
1479
1480 // We are adding new water. Update NewWaterList.
1481 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001482 }
1483
Bob Wilson2f9be502009-10-15 20:49:47 +00001484 // Remove the original WaterList entry; we want subsequent insertions in
1485 // this vicinity to go after the one we're about to insert. This
1486 // considerably reduces the number of times we have to move the same CPE
1487 // more than once and is also important to ensure the algorithm terminates.
1488 if (IP != WaterList.end())
1489 WaterList.erase(IP);
1490
Dale Johannesene18b13b2007-02-23 05:02:36 +00001491 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001492 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001493
1494 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001495 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001496
Dale Johannesene18b13b2007-02-23 05:02:36 +00001497 // Now that we have an island to add the CPE to, clone the original CPE and
1498 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001499 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001500 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
Diana Picus116bbab2017-01-13 09:58:52 +00001501 .addImm(ID)
1502 .add(CPEMI->getOperand(1))
1503 .addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001504 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001505 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001506
Tim Northovera603c402015-05-31 19:22:07 +00001507 // Decrement the old entry, and remove it if refcount becomes 0.
1508 decrementCPEReferenceCount(CPI, CPEMI);
1509
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001510 // Mark the basic block as aligned as required by the const-pool entry.
1511 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001512
Evan Cheng10043e22007-01-19 07:51:42 +00001513 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001514 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001515 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001516
Evan Cheng10043e22007-01-19 07:51:42 +00001517 // Finally, change the CPI in the instruction operand to be ID.
1518 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001519 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001520 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001521 break;
1522 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001523
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001524 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001525 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001526
Evan Cheng10043e22007-01-19 07:51:42 +00001527 return true;
1528}
1529
Jim Grosbach190e7b62012-03-23 23:07:03 +00001530/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001531/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001532void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001533 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001534 unsigned Size = CPEMI->getOperand(2).getImm();
1535 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001536 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001537 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001538 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001539 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001540
Evan Chengab28b9a2013-02-21 18:37:54 +00001541 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001542 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001543 } else
1544 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001545 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001546
Jim Grosbach190e7b62012-03-23 23:07:03 +00001547 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001548 // An island has only one predecessor BB and one successor BB. Check if
1549 // this BB's predecessor jumps directly to this BB's successor. This
1550 // shouldn't happen currently.
1551 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1552 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001553}
1554
Jim Grosbach190e7b62012-03-23 23:07:03 +00001555/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001556/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001557bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001558 unsigned MadeChange = false;
1559 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1560 std::vector<CPEntry> &CPEs = CPEntries[i];
1561 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1562 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001563 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001564 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001565 MadeChange = true;
1566 }
1567 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001568 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001569 return MadeChange;
1570}
1571
Jim Grosbach190e7b62012-03-23 23:07:03 +00001572/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001573/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001574bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001575 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001576 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001577 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001578 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001579
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001580 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001581 << " from BB#" << MI->getParent()->getNumber()
1582 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001583 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001584 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001585
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001586 if (BrOffset <= DestOffset) {
1587 // Branch before the Dest.
1588 if (DestOffset-BrOffset <= MaxDisp)
1589 return true;
1590 } else {
1591 if (BrOffset-DestOffset <= MaxDisp)
1592 return true;
1593 }
1594 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001595}
1596
Jim Grosbach190e7b62012-03-23 23:07:03 +00001597/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001598/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001599bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001600 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001601 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001602
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001603 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001604 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001605 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001606
Evan Cheng7fa69642007-01-30 01:18:38 +00001607 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001608 return fixupUnconditionalBr(Br);
1609 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001610}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001611
Jim Grosbach190e7b62012-03-23 23:07:03 +00001612/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001613/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001614/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001615/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001616bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001617ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001618 MachineInstr *MI = Br.MI;
1619 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001620 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001621 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001622
1623 // Use BL to implement far jump.
1624 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001625 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001626 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001627 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001628 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001629 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001630
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001631 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001632
Evan Cheng7fa69642007-01-30 01:18:38 +00001633 return true;
1634}
1635
Jim Grosbach190e7b62012-03-23 23:07:03 +00001636/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001637/// far away to fit in its displacement field. It is converted to an inverse
1638/// conditional branch + an unconditional branch to the destination.
1639bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001640ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001641 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001642 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001643
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001644 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001645 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001646 // blt L1
1647 // =>
1648 // bge L2
1649 // b L1
1650 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001651 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001652 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001653 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001654
1655 // If the branch is at the end of its MBB and that has a fall-through block,
1656 // direct the updated conditional branch to the fall-through block. Otherwise,
1657 // split the MBB before the next instruction.
1658 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001659 MachineInstr *BMI = &MBB->back();
1660 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001661
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001662 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001663 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001664 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001665 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001666 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001667 // condition and swap destinations:
1668 // beq L1
1669 // b L2
1670 // =>
1671 // bne L2
1672 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001673 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001674 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001675 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001676 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001677 BMI->getOperand(0).setMBB(DestBB);
1678 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001679 MI->getOperand(1).setImm(CC);
1680 return true;
1681 }
1682 }
1683 }
1684
1685 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001686 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001687 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001688 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001689 int delta = TII->getInstSizeInBytes(MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001690 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001691 MBB->back().eraseFromParent();
Tim Northover5cdc4f92017-11-14 11:43:54 +00001692
1693 // The conditional successor will be swapped between the BBs after this, so
1694 // update CFG.
1695 MBB->addSuccessor(DestBB);
1696 std::next(MBB->getIterator())->removeSuccessor(DestBB);
1697
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001698 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001699 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001700 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001701
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001702 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001703 << " also invert condition and change dest. to BB#"
1704 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001705
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001706 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001707 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001708 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001709 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001710 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001711 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001712 if (isThumb)
Diana Picusbd66b7d2017-01-20 08:15:24 +00001713 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1714 .addMBB(DestBB)
1715 .add(predOps(ARMCC::AL));
Owen Anderson93cd3182011-09-09 23:05:14 +00001716 else
1717 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001718 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001719 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001720 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001721
1722 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001723 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001724 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001725 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001726 return true;
1727}
Evan Cheng7fa69642007-01-30 01:18:38 +00001728
Jim Grosbach190e7b62012-03-23 23:07:03 +00001729/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001730/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1731/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001732bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001733 bool MadeChange = false;
1734 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1735 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001736 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001737 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001738 MI->getOperand(2).getReg() == ARM::PC &&
1739 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001740 // Create the new insn and copy the predicate from the old.
1741 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
Diana Picus116bbab2017-01-13 09:58:52 +00001742 .add(MI->getOperand(0))
1743 .add(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001744 MI->eraseFromParent();
1745 MadeChange = true;
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001746 } else if (MI->getOpcode() == ARM::tPUSH &&
1747 MI->getOperand(2).getReg() == ARM::LR &&
1748 MI->getNumExplicitOperands() == 3) {
Roger Ferrer Ibanez56db97d2017-02-22 09:06:21 +00001749 // Just remove the push.
1750 MI->eraseFromParent();
1751 MadeChange = true;
1752 }
Evan Cheng7fa69642007-01-30 01:18:38 +00001753 }
1754 return MadeChange;
1755}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001756
Jim Grosbach190e7b62012-03-23 23:07:03 +00001757bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001758 bool MadeChange = false;
1759
1760 // Shrink ADR and LDR from constantpool.
1761 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1762 CPUser &U = CPUsers[i];
1763 unsigned Opcode = U.MI->getOpcode();
1764 unsigned NewOpc = 0;
1765 unsigned Scale = 1;
1766 unsigned Bits = 0;
1767 switch (Opcode) {
1768 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001769 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001770 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1771 NewOpc = ARM::tLEApcrel;
1772 Bits = 8;
1773 Scale = 4;
1774 }
1775 break;
1776 case ARM::t2LDRpci:
1777 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1778 NewOpc = ARM::tLDRpci;
1779 Bits = 8;
1780 Scale = 4;
1781 }
1782 break;
1783 }
1784
1785 if (!NewOpc)
1786 continue;
1787
Jim Grosbach190e7b62012-03-23 23:07:03 +00001788 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001789 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001790
1791 // Be conservative with inline asm.
1792 if (!U.KnownAlignment)
1793 MaxOffs -= 2;
1794
Evan Chengdb73d682009-08-14 00:32:16 +00001795 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001796 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001797 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001798 U.MI->setDesc(TII->get(NewOpc));
1799 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001800 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001801 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001802 ++NumT2CPShrunk;
1803 MadeChange = true;
1804 }
1805 }
1806
Evan Chengdb73d682009-08-14 00:32:16 +00001807 return MadeChange;
1808}
1809
Jim Grosbach190e7b62012-03-23 23:07:03 +00001810bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001811 bool MadeChange = false;
1812
Peter Collingbourne167668f2015-04-23 20:31:35 +00001813 // The order in which branches appear in ImmBranches is approximately their
1814 // order within the function body. By visiting later branches first, we reduce
1815 // the distance between earlier forward branches and their targets, making it
1816 // more likely that the cbn?z optimization, which can only apply to forward
1817 // branches, will succeed.
1818 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1819 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001820 unsigned Opcode = Br.MI->getOpcode();
1821 unsigned NewOpc = 0;
1822 unsigned Scale = 1;
1823 unsigned Bits = 0;
1824 switch (Opcode) {
1825 default: break;
1826 case ARM::t2B:
1827 NewOpc = ARM::tB;
1828 Bits = 11;
1829 Scale = 2;
1830 break;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001831 case ARM::t2Bcc:
Evan Chenge41903b2009-08-14 18:31:44 +00001832 NewOpc = ARM::tBcc;
1833 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001834 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001835 break;
1836 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001837 if (NewOpc) {
1838 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1839 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001840 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001841 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001842 Br.MI->setDesc(TII->get(NewOpc));
1843 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001844 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001845 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001846 ++NumT2BrShrunk;
1847 MadeChange = true;
1848 }
1849 }
1850
1851 Opcode = Br.MI->getOpcode();
1852 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001853 continue;
1854
Evan Cheng6bb95252012-01-14 01:53:46 +00001855 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1856 // so this transformation is not safe.
1857 if (!Br.MI->killsRegister(ARM::CPSR))
1858 continue;
1859
Evan Cheng6f29ad92009-10-31 23:46:45 +00001860 NewOpc = 0;
1861 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001862 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001863 if (Pred == ARMCC::EQ)
1864 NewOpc = ARM::tCBZ;
1865 else if (Pred == ARMCC::NE)
1866 NewOpc = ARM::tCBNZ;
1867 if (!NewOpc)
1868 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001869 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001870 // Check if the distance is within 126. Subtract starting offset by 2
1871 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001872 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001873 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001874 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001875 MachineBasicBlock::iterator CmpMI = Br.MI;
1876 if (CmpMI != Br.MI->getParent()->begin()) {
1877 --CmpMI;
1878 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1879 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001880 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001881 if (Pred == ARMCC::AL &&
1882 CmpMI->getOperand(1).getImm() == 0 &&
1883 isARMLowRegister(Reg)) {
1884 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001885 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001886 MachineInstr *NewBR =
1887 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1888 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1889 CmpMI->eraseFromParent();
1890 Br.MI->eraseFromParent();
1891 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001892 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001893 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001894 ++NumCBZ;
1895 MadeChange = true;
1896 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001897 }
1898 }
Evan Chenge41903b2009-08-14 18:31:44 +00001899 }
1900 }
1901
1902 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001903}
1904
Tim Northovera603c402015-05-31 19:22:07 +00001905static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1906 unsigned BaseReg) {
1907 if (I.getOpcode() != ARM::t2ADDrs)
1908 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001909
Tim Northovera603c402015-05-31 19:22:07 +00001910 if (I.getOperand(0).getReg() != EntryReg)
1911 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001912
Tim Northovera603c402015-05-31 19:22:07 +00001913 if (I.getOperand(1).getReg() != BaseReg)
1914 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001915
Tim Northovera603c402015-05-31 19:22:07 +00001916 // FIXME: what about CC and IdxReg?
1917 return true;
1918}
Tim Northover688f7bb2015-05-13 20:28:32 +00001919
Tim Northovera603c402015-05-31 19:22:07 +00001920/// \brief While trying to form a TBB/TBH instruction, we may (if the table
1921/// doesn't immediately follow the BR_JT) need access to the start of the
1922/// jump-table. We know one instruction that produces such a register; this
1923/// function works out whether that definition can be preserved to the BR_JT,
1924/// possibly by removing an intervening addition (which is usually needed to
1925/// calculate the actual entry to jump to).
1926bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1927 MachineInstr *LEAMI,
1928 unsigned &DeadSize,
1929 bool &CanDeleteLEA,
1930 bool &BaseRegKill) {
1931 if (JumpMI->getParent() != LEAMI->getParent())
1932 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001933
Tim Northovera603c402015-05-31 19:22:07 +00001934 // Now we hope that we have at least these instructions in the basic block:
1935 // BaseReg = t2LEA ...
1936 // [...]
1937 // EntryReg = t2ADDrs BaseReg, ...
1938 // [...]
1939 // t2BR_JT EntryReg
1940 //
1941 // We have to be very conservative about what we recognise here though. The
1942 // main perturbing factors to watch out for are:
1943 // + Spills at any point in the chain: not direct problems but we would
1944 // expect a blocking Def of the spilled register so in practice what we
1945 // can do is limited.
1946 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1947 // of BaseReg, but only if the t2ADDrs can be removed.
1948 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1949 // the wild, but we should be careful.
1950 unsigned EntryReg = JumpMI->getOperand(0).getReg();
1951 unsigned BaseReg = LEAMI->getOperand(0).getReg();
1952
1953 CanDeleteLEA = true;
1954 BaseRegKill = false;
1955 MachineInstr *RemovableAdd = nullptr;
1956 MachineBasicBlock::iterator I(LEAMI);
1957 for (++I; &*I != JumpMI; ++I) {
1958 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1959 RemovableAdd = &*I;
1960 break;
1961 }
1962
1963 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1964 const MachineOperand &MO = I->getOperand(K);
1965 if (!MO.isReg() || !MO.getReg())
1966 continue;
1967 if (MO.isDef() && MO.getReg() == BaseReg)
1968 return false;
1969 if (MO.isUse() && MO.getReg() == BaseReg) {
1970 BaseRegKill = BaseRegKill || MO.isKill();
1971 CanDeleteLEA = false;
1972 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001973 }
1974 }
1975
Tim Northovera603c402015-05-31 19:22:07 +00001976 if (!RemovableAdd)
1977 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00001978
Tim Northovera603c402015-05-31 19:22:07 +00001979 // Check the add really is removable, and that nothing else in the block
1980 // clobbers BaseReg.
1981 for (++I; &*I != JumpMI; ++I) {
1982 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1983 const MachineOperand &MO = I->getOperand(K);
1984 if (!MO.isReg() || !MO.getReg())
1985 continue;
1986 if (MO.isDef() && MO.getReg() == BaseReg)
1987 return false;
1988 if (MO.isUse() && MO.getReg() == EntryReg)
1989 RemovableAdd = nullptr;
1990 }
1991 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001992
Tim Northovera603c402015-05-31 19:22:07 +00001993 if (RemovableAdd) {
1994 RemovableAdd->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00001995 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00001996 } else if (BaseReg == EntryReg) {
1997 // The add wasn't removable, but clobbered the base for the TBB. So we can't
1998 // preserve it.
1999 return false;
2000 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002001
Tim Northovera603c402015-05-31 19:22:07 +00002002 // We reached the end of the block without seeing another definition of
2003 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2004 // used in the TBB/TBH if necessary.
2005 return true;
2006}
Tim Northover688f7bb2015-05-13 20:28:32 +00002007
Tim Northovera603c402015-05-31 19:22:07 +00002008/// \brief Returns whether CPEMI is the first instruction in the block
2009/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2010/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002011/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00002012static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002013 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00002014 MachineFunction *MF = MBB->getParent();
2015 ++MBB;
2016
2017 return MBB != MF->end() && MBB->begin() != MBB->end() &&
2018 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00002019}
2020
David Green1b4b59a2017-04-06 08:32:47 +00002021static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
2022 MachineInstr *JumpMI,
2023 unsigned &DeadSize) {
2024 // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2025 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2026 // and is not clobbered / used.
2027 MachineInstr *RemovableAdd = nullptr;
2028 unsigned EntryReg = JumpMI->getOperand(0).getReg();
2029
2030 // Find the last ADD to set EntryReg
2031 MachineBasicBlock::iterator I(LEAMI);
2032 for (++I; &*I != JumpMI; ++I) {
2033 if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2034 RemovableAdd = &*I;
2035 }
2036
2037 if (!RemovableAdd)
2038 return;
2039
2040 // Ensure EntryReg is not clobbered or used.
2041 MachineBasicBlock::iterator J(RemovableAdd);
2042 for (++J; &*J != JumpMI; ++J) {
2043 for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
2044 const MachineOperand &MO = J->getOperand(K);
2045 if (!MO.isReg() || !MO.getReg())
2046 continue;
2047 if (MO.isDef() && MO.getReg() == EntryReg)
2048 return;
2049 if (MO.isUse() && MO.getReg() == EntryReg)
2050 return;
2051 }
2052 }
2053
2054 DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
2055 RemovableAdd->eraseFromParent();
2056 DeadSize += 4;
2057}
2058
James Molloy92497542017-02-13 14:07:39 +00002059static bool registerDefinedBetween(unsigned Reg,
2060 MachineBasicBlock::iterator From,
2061 MachineBasicBlock::iterator To,
2062 const TargetRegisterInfo *TRI) {
2063 for (auto I = From; I != To; ++I)
2064 if (I->modifiesRegister(Reg, TRI))
2065 return true;
2066 return false;
2067}
2068
Jim Grosbach190e7b62012-03-23 23:07:03 +00002069/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00002070/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002071bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00002072 bool MadeChange = false;
2073
2074 // FIXME: After the tables are shrunk, can we get rid some of the
2075 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002076 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002077 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002078
Evan Chengc6d70ae2009-07-29 02:18:14 +00002079 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2080 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2081 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002082 const MCInstrDesc &MCID = MI->getDesc();
2083 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002084 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002085 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2086 unsigned JTI = JTOP.getIndex();
2087 assert(JTI < JT.size());
2088
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002089 bool ByteOk = true;
2090 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002091 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002092 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002093 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2094 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002095 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002096 // Negative offset is not ok. FIXME: We should change BB layout to make
2097 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002098 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002099 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002100 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002101 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002102 HalfWordOk = false;
2103 if (!ByteOk && !HalfWordOk)
2104 break;
2105 }
2106
Tim Northovera603c402015-05-31 19:22:07 +00002107 if (!ByteOk && !HalfWordOk)
2108 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002109
James Molloy70a3d6d2016-11-01 13:37:41 +00002110 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
Tim Northovera603c402015-05-31 19:22:07 +00002111 MachineBasicBlock *MBB = MI->getParent();
2112 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2113 continue;
Tim Northovera603c402015-05-31 19:22:07 +00002114
Tim Northovera603c402015-05-31 19:22:07 +00002115 unsigned DeadSize = 0;
2116 bool CanDeleteLEA = false;
2117 bool BaseRegKill = false;
James Molloy70a3d6d2016-11-01 13:37:41 +00002118
2119 unsigned IdxReg = ~0U;
2120 bool IdxRegKill = true;
2121 if (isThumb2) {
2122 IdxReg = MI->getOperand(1).getReg();
2123 IdxRegKill = MI->getOperand(1).isKill();
2124
2125 bool PreservedBaseReg =
Tim Northovera603c402015-05-31 19:22:07 +00002126 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
James Molloy70a3d6d2016-11-01 13:37:41 +00002127 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2128 continue;
2129 } else {
2130 // We're in thumb-1 mode, so we must have something like:
2131 // %idx = tLSLri %idx, 2
2132 // %base = tLEApcrelJT
Momchil Velikov842aa902017-11-13 11:56:48 +00002133 // %t = tLDRr %base, %idx
James Molloy70a3d6d2016-11-01 13:37:41 +00002134 unsigned BaseReg = User.MI->getOperand(0).getReg();
James Molloy2bae8642016-10-22 09:58:37 +00002135
James Molloy70a3d6d2016-11-01 13:37:41 +00002136 if (User.MI->getIterator() == User.MI->getParent()->begin())
2137 continue;
2138 MachineInstr *Shift = User.MI->getPrevNode();
2139 if (Shift->getOpcode() != ARM::tLSLri ||
2140 Shift->getOperand(3).getImm() != 2 ||
2141 !Shift->getOperand(2).isKill())
2142 continue;
2143 IdxReg = Shift->getOperand(2).getReg();
2144 unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
Tim Northovera603c402015-05-31 19:22:07 +00002145
Tim Northover0d98b032017-03-15 18:38:13 +00002146 // It's important that IdxReg is live until the actual TBB/TBH. Most of
2147 // the range is checked later, but the LEA might still clobber it and not
2148 // actually get removed.
2149 if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
2150 continue;
2151
James Molloy70a3d6d2016-11-01 13:37:41 +00002152 MachineInstr *Load = User.MI->getNextNode();
2153 if (Load->getOpcode() != ARM::tLDRr)
2154 continue;
Momchil Velikov842aa902017-11-13 11:56:48 +00002155 if (Load->getOperand(1).getReg() != BaseReg ||
2156 Load->getOperand(2).getReg() != ShiftedIdxReg ||
2157 !Load->getOperand(2).isKill())
James Molloy70a3d6d2016-11-01 13:37:41 +00002158 continue;
2159
2160 // If we're in PIC mode, there should be another ADD following.
James Molloy92497542017-02-13 14:07:39 +00002161 auto *TRI = STI->getRegisterInfo();
Weiming Zhao962c5a32017-04-20 18:37:14 +00002162
2163 // %base cannot be redefined after the load as it will appear before
2164 // TBB/TBH like:
2165 // %base =
2166 // %base =
2167 // tBB %base, %idx
2168 if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
2169 continue;
2170
James Molloy70a3d6d2016-11-01 13:37:41 +00002171 if (isPositionIndependentOrROPI) {
2172 MachineInstr *Add = Load->getNextNode();
2173 if (Add->getOpcode() != ARM::tADDrr ||
Momchil Velikov842aa902017-11-13 11:56:48 +00002174 Add->getOperand(2).getReg() != BaseReg ||
2175 Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
2176 !Add->getOperand(3).isKill())
James Molloy70a3d6d2016-11-01 13:37:41 +00002177 continue;
2178 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2179 continue;
James Molloy92497542017-02-13 14:07:39 +00002180 if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
2181 // IdxReg gets redefined in the middle of the sequence.
2182 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002183 Add->eraseFromParent();
2184 DeadSize += 2;
2185 } else {
2186 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2187 continue;
James Molloy92497542017-02-13 14:07:39 +00002188 if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
2189 // IdxReg gets redefined in the middle of the sequence.
2190 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002191 }
Tim Northover0d98b032017-03-15 18:38:13 +00002192
James Molloy70a3d6d2016-11-01 13:37:41 +00002193 // Now safe to delete the load and lsl. The LEA will be removed later.
2194 CanDeleteLEA = true;
2195 Shift->eraseFromParent();
2196 Load->eraseFromParent();
2197 DeadSize += 4;
2198 }
Tim Northover0d98b032017-03-15 18:38:13 +00002199
Tim Northovera603c402015-05-31 19:22:07 +00002200 DEBUG(dbgs() << "Shrink JT: " << *MI);
2201 MachineInstr *CPEMI = User.CPEMI;
2202 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
James Molloy70a3d6d2016-11-01 13:37:41 +00002203 if (!isThumb2)
2204 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2205
Tim Northovera603c402015-05-31 19:22:07 +00002206 MachineBasicBlock::iterator MI_JT = MI;
2207 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002208 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002209 .addReg(User.MI->getOperand(0).getReg(),
2210 getKillRegState(BaseRegKill))
2211 .addReg(IdxReg, getKillRegState(IdxRegKill))
2212 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2213 .addImm(CPEMI->getOperand(0).getImm());
2214 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002215
Tim Northovera603c402015-05-31 19:22:07 +00002216 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2217 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002218
Tim Northovera603c402015-05-31 19:22:07 +00002219 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2220 NewJTMI->getOperand(0).setReg(ARM::PC);
2221 NewJTMI->getOperand(0).setIsKill(false);
2222
David Green1b4b59a2017-04-06 08:32:47 +00002223 if (CanDeleteLEA) {
2224 if (isThumb2)
2225 RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
2226
Tim Northovera603c402015-05-31 19:22:07 +00002227 User.MI->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00002228 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00002229
2230 // The LEA was eliminated, the TBB instruction becomes the only new user
2231 // of the jump table.
2232 User.MI = NewJTMI;
2233 User.MaxDisp = 4;
2234 User.NegOk = false;
2235 User.IsSoImm = false;
2236 User.KnownAlignment = false;
2237 } else {
2238 // The LEA couldn't be eliminated, so we must add another CPUser to
2239 // record the TBB or TBH use.
2240 int CPEntryIdx = JumpTableEntryIndices[JTI];
2241 auto &CPEs = CPEntries[CPEntryIdx];
David Majnemer562e8292016-08-12 00:18:03 +00002242 auto Entry =
2243 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
Tim Northovera603c402015-05-31 19:22:07 +00002244 ++Entry->RefCount;
2245 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2246 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002247 }
Tim Northovera603c402015-05-31 19:22:07 +00002248
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002249 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2250 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002251 MI->eraseFromParent();
2252
2253 int Delta = OrigSize - NewSize + DeadSize;
2254 BBInfo[MBB->getNumber()].Size -= Delta;
2255 adjustBBOffsetsAfter(MBB);
2256
2257 ++NumTBs;
2258 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002259 }
2260
2261 return MadeChange;
2262}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002263
Jim Grosbach190e7b62012-03-23 23:07:03 +00002264/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002265/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002266bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002267 bool MadeChange = false;
2268
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002269 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002270 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002271
Jim Grosbach5d577142009-11-12 17:25:07 +00002272 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2273 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2274 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002275 const MCInstrDesc &MCID = MI->getDesc();
2276 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002277 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002278 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2279 unsigned JTI = JTOP.getIndex();
2280 assert(JTI < JT.size());
2281
2282 // We prefer if target blocks for the jump table come after the jump
2283 // instruction so we can use TB[BH]. Loop through the target blocks
2284 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002285 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002286 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2287 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2288 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002289 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002290
Jim Grosbach9785e592009-11-16 18:58:52 +00002291 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002292 // The destination precedes the switch. Try to move the block forward
2293 // so we have a positive offset.
2294 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002295 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002296 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002297 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002298 MadeChange = true;
2299 }
2300 }
2301 }
2302
2303 return MadeChange;
2304}
2305
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002306MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002307adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002308 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002309 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002310 // table that branches back to the actual target. This is a very simple
2311 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002312 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002313 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002314 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002315 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002316 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002317
Jim Grosbach47d5e332009-11-16 17:10:56 +00002318 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002319 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002320
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002321 // If the block ends in an unconditional branch, move it. The prior block
2322 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002323 // 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 +00002324 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002325 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002326 BB->moveAfter(JTBB);
2327 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002328 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002329 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002330 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002331 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002332 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002333 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002334
2335 // Create a new MBB for the code after the jump BB.
2336 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002337 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002338 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002339 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002340
2341 // Add an unconditional branch from NewBB to BB.
2342 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2343 // correspond directly to anything in the source.
James Molloy70a3d6d2016-11-01 13:37:41 +00002344 if (isThumb2)
2345 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2346 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002347 .add(predOps(ARMCC::AL));
James Molloy70a3d6d2016-11-01 13:37:41 +00002348 else
2349 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2350 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002351 .add(predOps(ARMCC::AL));
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002352
Jim Grosbach43d21082009-11-14 20:10:18 +00002353 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002354 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002355
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002356 // Update the CFG.
2357 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002358 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002359
Jim Grosbach5d577142009-11-12 17:25:07 +00002360 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002361 return NewBB;
2362}
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00002363
2364/// createARMConstantIslandPass - returns an instance of the constpool
2365/// island pass.
2366FunctionPass *llvm::createARMConstantIslandPass() {
2367 return new ARMConstantIslands();
2368}
James Molloy9b3b8992017-02-13 14:07:25 +00002369
2370INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
2371 false, false)