blob: 60e5d7bf6098dbba021fcb67955cc03be0577a83 [file] [log] [blame]
Eugene Zelenko076468c2017-09-20 21:35:51 +00001//===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
Evan Cheng10043e22007-01-19 07:51:42 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Evan Cheng10043e22007-01-19 07:51:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass that splits the constant pool up into 'islands'
10// which are scattered through-out the function. This is required due to the
11// limited pc-relative displacements that ARM has.
12//
13//===----------------------------------------------------------------------===//
14
Evan Cheng10043e22007-01-19 07:51:42 +000015#include "ARM.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000016#include "ARMBaseInstrInfo.h"
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +000017#include "ARMBasicBlockInfo.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000019#include "ARMSubtarget.h"
20#include "MCTargetDesc/ARMBaseInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "Thumb2InstrInfo.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000022#include "Utils/ARMBaseInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000023#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000028#include "llvm/ADT/StringRef.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
Evan Cheng10043e22007-01-19 07:51:42 +000030#include "llvm/CodeGen/MachineConstantPool.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000031#include "llvm/CodeGen/MachineFunction.h"
Evan Cheng10043e22007-01-19 07:51:42 +000032#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000033#include "llvm/CodeGen/MachineInstr.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000034#include "llvm/CodeGen/MachineJumpTableInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000035#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000037#include "llvm/Config/llvm-config.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 {
Sam Parker966f4e82019-06-17 08:49:09 +0000100 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
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);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000246 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000247 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000248 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
249 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000250 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000251 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000252 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000253 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000254 void removeDeadCPEMI(MachineInstr *CPEMI);
255 bool removeUnusedCPEntries();
256 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
257 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
258 bool DoDump = false);
259 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000260 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000261 bool fixupImmediateBr(ImmBranch &Br);
262 bool fixupConditionalBr(ImmBranch &Br);
263 bool fixupUnconditionalBr(ImmBranch &Br);
264 bool undoLRSpillRestore();
Jim Grosbach190e7b62012-03-23 23:07:03 +0000265 bool optimizeThumb2Instructions();
266 bool optimizeThumb2Branches();
267 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000268 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
269 unsigned &DeadSize, bool &CanDeleteLEA,
270 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000271 bool optimizeThumb2JumpTables();
272 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000273 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000274
Jim Grosbach190e7b62012-03-23 23:07:03 +0000275 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000276 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000277 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000278
Jim Grosbach190e7b62012-03-23 23:07:03 +0000279 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000280 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000281 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000282 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000283 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000284 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000285 }
Evan Cheng10043e22007-01-19 07:51:42 +0000286 };
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000287
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000288} // end anonymous namespace
Evan Cheng10043e22007-01-19 07:51:42 +0000289
Eugene Zelenko076468c2017-09-20 21:35:51 +0000290char ARMConstantIslands::ID = 0;
291
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000292/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000293void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000294#ifndef NDEBUG
Fangrui Song89d69052019-06-17 09:26:50 +0000295 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Craig Toppere30b8ca2016-01-03 19:43:40 +0000296 assert(std::is_sorted(MF->begin(), MF->end(),
Sam Parker966f4e82019-06-17 08:49:09 +0000297 [&BBInfo](const MachineBasicBlock &LHS,
298 const MachineBasicBlock &RHS) {
Craig Toppere30b8ca2016-01-03 19:43:40 +0000299 return BBInfo[LHS.getNumber()].postOffset() <
300 BBInfo[RHS.getNumber()].postOffset();
301 }));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000302 LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000303 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
304 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000305 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000306 // Verify offset using the real max displacement without the safety
307 // adjustment.
308 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000309 /* DoDump = */ true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000310 LLVM_DEBUG(dbgs() << "OK\n");
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000311 continue;
312 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000313 LLVM_DEBUG(dbgs() << "Out of range.\n");
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000314 dumpBBs();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000315 LLVM_DEBUG(MF->dump());
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000316 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000317 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000318#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000319}
320
Aaron Ballman615eb472017-10-15 14:32:27 +0000321#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000322/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000323LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
Sam Parker966f4e82019-06-17 08:49:09 +0000324 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000325 LLVM_DEBUG({
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000326 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
327 const BasicBlockInfo &BBI = BBInfo[J];
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000328 dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000329 << " kb=" << unsigned(BBI.KnownBits)
330 << " ua=" << unsigned(BBI.Unalign)
331 << " pa=" << unsigned(BBI.PostAlign)
332 << format(" size=%#x\n", BBInfo[J].Size);
333 }
334 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000335}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000336#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000337
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000338bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
339 MF = &mf;
340 MCP = mf.getConstantPool();
Sam Parker966f4e82019-06-17 08:49:09 +0000341 BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(mf));
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000342
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000343 LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
344 << 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();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000396 LLVM_DEBUG(dumpBBs());
Dale Johannesenc17dd572010-07-23 22:50:23 +0000397
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) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000410 LLVM_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!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000419 LLVM_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
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000425 LLVM_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!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000431 LLVM_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
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000467 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000468
Sam Parker966f4e82019-06-17 08:49:09 +0000469 BBUtils->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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000482/// Perform the initial placement of the regular constant pool entries.
Tim Northovera603c402015-05-31 19:22:07 +0000483/// 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 unsigned Align = CPs[i].getAlignment();
514 assert(isPowerOf2_32(Align) && "Invalid alignment");
515 // Verify that all constant pool entries are a multiple of their alignment.
516 // If not, we would have to pad them out so that instructions stay aligned.
517 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
518
519 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
520 unsigned LogAlign = Log2_32(Align);
521 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000522 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000523 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000524 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000525 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000526
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000527 // Ensure that future entries with higher alignment get inserted before
528 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000529 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000530 if (InsPoint[a] == InsAt)
531 InsPoint[a] = CPEMI;
532
Evan Cheng8b7700f2007-02-09 20:54:44 +0000533 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000534 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000535 ++NumCPEs;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000536 LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
537 << Size << ", align = " << Align << '\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000538 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000539 LLVM_DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000540}
541
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000542/// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
Tim Northovera603c402015-05-31 19:22:07 +0000543/// instructions can be made more efficient if the jump table immediately
544/// follows the instruction, it's best to place them immediately next to their
545/// jumps to begin with. In almost all cases they'll never be moved from that
546/// position.
547void ARMConstantIslands::doInitialJumpTablePlacement(
548 std::vector<MachineInstr *> &CPEMIs) {
549 unsigned i = CPEntries.size();
550 auto MJTI = MF->getJumpTableInfo();
551 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
552
553 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
554 for (MachineBasicBlock &MBB : *MF) {
555 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000556 if (MI == MBB.end())
557 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000558
559 unsigned JTOpcode;
560 switch (MI->getOpcode()) {
561 default:
562 continue;
563 case ARM::BR_JTadd:
564 case ARM::BR_JTr:
565 case ARM::tBR_JTr:
Momchil Velikov4a91fb92017-11-15 12:02:55 +0000566 case ARM::BR_JTm_i12:
567 case ARM::BR_JTm_rs:
Tim Northovera603c402015-05-31 19:22:07 +0000568 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
Sam Parker966f4e82019-06-17 08:49:09 +0000686 BBUtils->computeAllBlockSizes();
687 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000688 // 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.
Sam Parker966f4e82019-06-17 08:49:09 +0000693 BBUtils->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) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000703 if (I.isDebugInstr())
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;
Sjoerd Meijerf4a7fa72018-02-13 15:34:09 +0000822 case ARM::VLDRH:
823 Bits = 8;
824 Scale = 2; // +-(offset_8*2)
825 NegOk = true;
826 break;
James Molloy9abb2fa2016-09-26 07:26:24 +0000827
828 case ARM::tLDRHi:
829 Bits = 5;
830 Scale = 2; // +(offset_5*2)
831 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000832 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000833
Evan Cheng10043e22007-01-19 07:51:42 +0000834 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000835 unsigned CPI = I.getOperand(op).getIndex();
836 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000837 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
838 CPI = JumpTableEntryIndices[CPI];
839 }
840
Evan Cheng8b7700f2007-02-09 20:54:44 +0000841 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000842 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000843 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000844
845 // Increment corresponding CPEntry reference count.
846 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
847 assert(CPE && "Cannot find a corresponding CPEntry!");
848 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000849
Evan Cheng10043e22007-01-19 07:51:42 +0000850 // Instructions can only use one CP entry, don't bother scanning the
851 // rest of the operands.
852 break;
853 }
854 }
Evan Cheng10043e22007-01-19 07:51:42 +0000855 }
856}
857
Evan Cheng10043e22007-01-19 07:51:42 +0000858/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
859/// ID.
860static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
861 const MachineBasicBlock *RHS) {
862 return LHS->getNumber() < RHS->getNumber();
863}
864
Jim Grosbach190e7b62012-03-23 23:07:03 +0000865/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000866/// machine function, it upsets all of the block numbers. Renumber the blocks
867/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000868void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000869 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000870 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000871
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000872 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000873 // renumbered) block numbers.
Sam Parker966f4e82019-06-17 08:49:09 +0000874 BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000875
876 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000877 // available water after it.
Fangrui Songdc8de602019-06-21 05:40:31 +0000878 water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
Evan Cheng10043e22007-01-19 07:51:42 +0000879 WaterList.insert(IP, NewBB);
880}
881
Evan Cheng10043e22007-01-19 07:51:42 +0000882/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000883/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000884/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000885MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000886 MachineBasicBlock *OrigBB = MI->getParent();
887
888 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000889 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000890 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000891 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000892 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000893
Evan Cheng10043e22007-01-19 07:51:42 +0000894 // Splice the instructions starting with MI over to NewBB.
895 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000896
Evan Cheng10043e22007-01-19 07:51:42 +0000897 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000898 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000899 // There doesn't seem to be meaningful DebugInfo available; this doesn't
900 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000901 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000902 if (!isThumb)
903 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
904 else
Diana Picusbd66b7d2017-01-20 08:15:24 +0000905 BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
906 .addMBB(NewBB)
907 .add(predOps(ARMCC::AL));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000908 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000909
Evan Cheng10043e22007-01-19 07:51:42 +0000910 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000911 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000912
Evan Cheng10043e22007-01-19 07:51:42 +0000913 // OrigBB branches to NewBB.
914 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000915
Evan Cheng10043e22007-01-19 07:51:42 +0000916 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000917 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000918 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000919 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000920
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000921 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000922 // renumbered) block numbers.
Sam Parker966f4e82019-06-17 08:49:09 +0000923 BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000924
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000925 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000926 // available water after it (but not if it's already there, which happens
927 // when splitting before a conditional branch that is followed by an
928 // unconditional branch - in that case we want to insert NewBB).
Fangrui Songdc8de602019-06-21 05:40:31 +0000929 water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000930 MachineBasicBlock* WaterBB = *IP;
931 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000932 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000933 else
934 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000935 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000936
Dale Johannesenc17dd572010-07-23 22:50:23 +0000937 // Figure out how large the OrigBB is. As the first half of the original
938 // block, it cannot contain a tablejump. The size includes
939 // the new jump we added. (It should be possible to do this without
940 // recounting everything, but it's very confusing, and this is rarely
941 // executed.)
Sam Parker966f4e82019-06-17 08:49:09 +0000942 BBUtils->computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000943
Dale Johannesenc17dd572010-07-23 22:50:23 +0000944 // Figure out how large the NewMBB is. As the second half of the original
945 // block, it may contain a tablejump.
Sam Parker966f4e82019-06-17 08:49:09 +0000946 BBUtils->computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000947
Dale Johannesen01ee5752007-02-25 00:47:03 +0000948 // All BBOffsets following these blocks must be modified.
Sam Parker966f4e82019-06-17 08:49:09 +0000949 BBUtils->adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000950
951 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000952}
953
Jim Grosbach190e7b62012-03-23 23:07:03 +0000954/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000955/// displacement computation. Update U.KnownAlignment to match its current
956/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000957unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
Sam Parker966f4e82019-06-17 08:49:09 +0000958 unsigned UserOffset = BBUtils->getOffsetOf(U.MI);
959
960 SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000961 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
962 unsigned KnownBits = BBI.internalKnownBits();
963
964 // The value read from PC is offset from the actual instruction address.
965 UserOffset += (isThumb ? 4 : 8);
966
967 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
968 // Make sure U.getMaxDisp() returns a constrained range.
969 U.KnownAlignment = (KnownBits >= 2);
970
971 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
972 // purposes of the displacement computation; compensate for that here.
973 // For unknown alignments, getMaxDisp() constrains the range instead.
974 if (isThumb && U.KnownAlignment)
975 UserOffset &= ~3u;
976
977 return UserOffset;
978}
979
Jim Grosbach190e7b62012-03-23 23:07:03 +0000980/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000981/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000982/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000983/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000984/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
985/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000986bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000987 unsigned TrialOffset, unsigned MaxDisp,
988 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000989 if (UserOffset <= TrialOffset) {
990 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000991 if (TrialOffset - UserOffset <= MaxDisp)
992 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000993 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000994 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000995 if (UserOffset - TrialOffset <= MaxDisp)
996 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000997 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000998 }
999 return false;
1000}
1001
Jim Grosbach190e7b62012-03-23 23:07:03 +00001002/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +00001003/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001004///
1005/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001006bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001007 MachineBasicBlock* Water, CPUser &U,
1008 unsigned &Growth) {
Sam Parker966f4e82019-06-17 08:49:09 +00001009 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001010 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1011 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1012 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001013 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001014 if (++NextBlock == MF->end()) {
1015 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1016 NextBlockAlignment = 0;
1017 } else {
1018 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1019 NextBlockAlignment = NextBlock->getAlignment();
1020 }
1021 unsigned Size = U.CPEMI->getOperand(2).getImm();
1022 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001023
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001024 // The CPE may be able to hide in the alignment padding before the next
1025 // block. It may also cause more padding to be required if it is more aligned
1026 // that the next block.
1027 if (CPEEnd > NextBlockOffset) {
1028 Growth = CPEEnd - NextBlockOffset;
1029 // Compute the padding that would go at the end of the CPE to align the next
1030 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001031 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001032
1033 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001034 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001035 // in blocks between CPE and the user.
1036 if (CPEOffset < UserOffset)
1037 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1038 } else
1039 // CPE fits in existing padding.
1040 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001041
Jim Grosbach190e7b62012-03-23 23:07:03 +00001042 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001043}
1044
Jim Grosbach190e7b62012-03-23 23:07:03 +00001045/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001046/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001047bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001048 MachineInstr *CPEMI, unsigned MaxDisp,
1049 bool NegOk, bool DoDump) {
Sam Parker966f4e82019-06-17 08:49:09 +00001050 unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001051
Dale Johannesene18b13b2007-02-23 05:02:36 +00001052 if (DoDump) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001053 LLVM_DEBUG({
Fangrui Song4bde5d32019-06-17 09:29:50 +00001054 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001055 unsigned Block = MI->getParent()->getNumber();
1056 const BasicBlockInfo &BBI = BBInfo[Block];
1057 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1058 << " max delta=" << MaxDisp
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001059 << format(" insn address=%#x", UserOffset) << " in "
1060 << printMBBReference(*MI->getParent()) << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001061 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1062 << format("CPE address=%#x offset=%+d: ", CPEOffset,
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001063 int(CPEOffset - UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001064 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001065 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001066
Jim Grosbach190e7b62012-03-23 23:07:03 +00001067 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001068}
1069
Evan Chenge4510972009-01-28 00:53:34 +00001070#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001071/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1072/// unconditionally branches to its only successor.
1073static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1074 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1075 return false;
1076
1077 MachineBasicBlock *Succ = *MBB->succ_begin();
1078 MachineBasicBlock *Pred = *MBB->pred_begin();
1079 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001080 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1081 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001082 return PredMI->getOperand(0).getMBB() == Succ;
1083 return false;
1084}
Evan Chenge4510972009-01-28 00:53:34 +00001085#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001086
Jim Grosbach190e7b62012-03-23 23:07:03 +00001087/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001088/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001089/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001090/// the entry, false if we didn't.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001091bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1092 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001093 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001094 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1095 assert(CPE && "Unexpected!");
1096 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001097 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001098 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001099 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001100 return true;
1101 }
1102 return false;
1103}
1104
Tim Northovera603c402015-05-31 19:22:07 +00001105unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1106 if (CPEMI->getOperand(1).isCPI())
1107 return CPEMI->getOperand(1).getIndex();
1108
1109 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1110}
1111
Dale Johannesene18b13b2007-02-23 05:02:36 +00001112/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1113/// if not, see if an in-range clone of the CPE is in range, and if so,
1114/// change the data structures so the user references the clone. Returns:
1115/// 0 = no existing entry found
1116/// 1 = entry found, and there were no code insertions or deletions
1117/// 2 = entry found, and there were code insertions or deletions
Eugene Zelenko076468c2017-09-20 21:35:51 +00001118int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001119 MachineInstr *UserMI = U.MI;
1120 MachineInstr *CPEMI = U.CPEMI;
1121
1122 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001123 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1124 true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001125 LLVM_DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001126 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001127 }
1128
Dale Johannesene18b13b2007-02-23 05:02:36 +00001129 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001130 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001131 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1132 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1133 // We already tried this one
1134 if (CPEs[i].CPEMI == CPEMI)
1135 continue;
1136 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001137 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001138 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001139 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001140 U.NegOk)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001141 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1142 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001143 // Point the CPUser node to the replacement
1144 U.CPEMI = CPEs[i].CPEMI;
1145 // Change the CPI in the instruction operand to refer to the clone.
1146 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001147 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001148 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001149 break;
1150 }
1151 // Adjust the refcount of the clone...
1152 CPEs[i].RefCount++;
1153 // ...and the original. If we didn't remove the old entry, none of the
1154 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001155 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001156 }
1157 }
1158 return 0;
1159}
1160
Dale Johannesen440995b2007-02-28 18:41:23 +00001161/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1162/// the specific unconditional branch instruction.
1163static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001164 switch (Opc) {
1165 case ARM::tB:
1166 return ((1<<10)-1)*2;
1167 case ARM::t2B:
1168 return ((1<<23)-1)*2;
1169 default:
1170 break;
1171 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001172
David Goodwin27303cd2009-06-30 18:04:13 +00001173 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001174}
1175
Jim Grosbach190e7b62012-03-23 23:07:03 +00001176/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001177/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001178/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001179/// is set to the WaterList entry. For Thumb, prefer water that will not
1180/// introduce padding to water that will. To ensure that this pass
1181/// terminates, the CPE location for a particular CPUser is only allowed to
1182/// move to a lower address, so search backward from the end of the list and
1183/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001184bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001185 water_iterator &WaterIter,
1186 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001187 if (WaterList.empty())
1188 return false;
1189
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001190 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001191 // The nearest water without splitting the UserBB is right after it.
1192 // If the distance is still large (we have a big BB), then we need to split it
1193 // if we don't converge after certain iterations. This helps the following
1194 // situation to converge:
1195 // BB0:
1196 // Big BB
1197 // BB1:
1198 // Constant Pool
1199 // When a CP access is out of range, BB0 may be used as water. However,
1200 // inserting islands between BB0 and BB1 makes other accesses out of range.
1201 MachineBasicBlock *UserBB = U.MI->getParent();
Sam Parker966f4e82019-06-17 08:49:09 +00001202 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001203 unsigned MinNoSplitDisp =
1204 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1205 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1206 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001207 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001208 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001209 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001210 // Check if water is in range and is either at a lower address than the
1211 // current "high water mark" or a new water block that was created since
1212 // the previous iteration by inserting an unconditional branch. In the
1213 // latter case, we want to allow resetting the high water mark back to
1214 // this new water since we haven't seen it before. Inserting branches
1215 // should be relatively uncommon and when it does happen, we want to be
1216 // sure to take advantage of it for all the CPEs near that block, so that
1217 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001218 // When CloserWater is true, we try to find the lowest address after (or
1219 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001220 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001221 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001222 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001223 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1224 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001225 // This is the least amount of required padding seen so far.
1226 BestGrowth = Growth;
1227 WaterIter = IP;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001228 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1229 << " Growth=" << Growth << '\n');
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001230
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001231 if (CloserWater && WaterBB == U.MI->getParent())
1232 return true;
1233 // Keep looking unless it is perfect and we're not looking for the lowest
1234 // possible address.
1235 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001236 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001237 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001238 if (IP == B)
1239 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001240 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001241 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001242}
1243
Jim Grosbach190e7b62012-03-23 23:07:03 +00001244/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001245/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1246/// block is used if in range, and the conditional branch munged so control
1247/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001248/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001249/// block following which the new island can be inserted (the WaterList
1250/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001251void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001252 unsigned UserOffset,
1253 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001254 CPUser &U = CPUsers[CPUserIndex];
1255 MachineInstr *UserMI = U.MI;
1256 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001257 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001258 MachineBasicBlock *UserMBB = UserMI->getParent();
Sam Parker966f4e82019-06-17 08:49:09 +00001259 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001260 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001261
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001262 // If the block does not end in an unconditional branch already, and if the
1263 // end of the block is within range, make new water there. (The addition
1264 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001265 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001266 if (BBHasFallthrough(UserMBB)) {
1267 // Size of branch to insert.
1268 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001269 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001270 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001271
Jim Grosbach190e7b62012-03-23 23:07:03 +00001272 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001273 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1274 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001275 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001276 // Add an unconditional branch from UserMBB to fallthrough block. Record
1277 // it for branch lengthening; this new branch will not get out of range,
1278 // but if the preceding conditional branch is out of range, the targets
1279 // will be exchanged, and the altered branch may be out of range, so the
1280 // machinery has to know about it.
1281 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1282 if (!isThumb)
1283 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1284 else
Diana Picusbd66b7d2017-01-20 08:15:24 +00001285 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1286 .addMBB(NewMBB)
1287 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001288 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1289 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1290 MaxDisp, false, UncondBr));
Sam Parker966f4e82019-06-17 08:49:09 +00001291 BBUtils->computeBlockSize(UserMBB);
1292 BBUtils->adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001293 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001294 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001295 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001296
1297 // What a big block. Find a place within the block to split it. This is a
1298 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1299 // entries are 4 bytes: if instruction I references island CPE, and
1300 // instruction I+1 references CPE', it will not work well to put CPE as far
1301 // forward as possible, since then CPE' cannot immediately follow it (that
1302 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1303 // need to create a new island. So, we make a first guess, then walk through
1304 // the instructions between the one currently being looked at and the
1305 // possible insertion point, and make sure any other instructions that
1306 // reference CPEs will be able to use the same island area; if not, we back
1307 // up the insertion point.
1308
1309 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001310 // point where we can add a 4-byte branch instruction, and then align to
1311 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001312 unsigned LogAlign = MF->getAlignment();
1313 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1314 unsigned KnownBits = UserBBI.internalKnownBits();
1315 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001316 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001317 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1318 BaseInsertOffset));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001319
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001320 // The 4 in the following is for the unconditional branch we'll be inserting
1321 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001322 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001323 BaseInsertOffset -= 4;
1324
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001325 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1326 << " la=" << LogAlign << " kb=" << KnownBits
1327 << " up=" << UPad << '\n');
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001328
1329 // This could point off the end of the block if we've already got constant
1330 // pool entries following this block; only the last one is in the water list.
1331 // Back past any possible branches (allow for a conditional and a maximally
1332 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001333 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001334 // Ensure BaseInsertOffset is larger than the offset of the instruction
1335 // following UserMI so that the loop which searches for the split point
1336 // iterates at least once.
1337 BaseInsertOffset =
1338 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001339 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001340 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001341 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001342 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001343 CPEMI->getOperand(2).getImm();
1344 MachineBasicBlock::iterator MI = UserMI;
1345 ++MI;
1346 unsigned CPUIndex = CPUserIndex+1;
1347 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001348 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001349 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001350 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001351 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001352 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001353 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001354 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001355 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001356 // Shift intertion point by one unit of alignment so it is within reach.
1357 BaseInsertOffset -= 1u << LogAlign;
1358 EndInsertOffset -= 1u << LogAlign;
1359 }
1360 // This is overly conservative, as we don't account for CPEMIs being
1361 // reused within the block, but it doesn't matter much. Also assume CPEs
1362 // are added in order with alignment padding. We may eventually be able
1363 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001364 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001365 CPUIndex++;
1366 }
1367
1368 // Remember the last IT instruction.
1369 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001370 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001371 }
1372
1373 --MI;
1374
1375 // Avoid splitting an IT block.
1376 if (LastIT) {
1377 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001378 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001379 if (CC != ARMCC::AL)
1380 MI = LastIT;
1381 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001382
Martin Storsjo5ab1d102018-08-22 20:34:12 +00001383 // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
1384 // On Windows, this instruction pair is covered by one single
1385 // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
1386 // constant island is injected inbetween them, the relocation will clobber
1387 // the instruction and fail to update the MOVT instruction.
1388 // (These instructions are bundled up until right before the ConstantIslands
1389 // pass.)
1390 if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
1391 (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1392 ARMII::MO_HI16) {
1393 --MI;
1394 assert(MI->getOpcode() == ARM::t2MOVi16 &&
1395 (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1396 ARMII::MO_LO16);
1397 }
1398
Tim Northover631cc9c2014-11-13 17:58:53 +00001399 // We really must not split an IT block.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001400 LLVM_DEBUG(unsigned PredReg; assert(
1401 !isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001402
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001403 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001404}
1405
Jim Grosbach190e7b62012-03-23 23:07:03 +00001406/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001407/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001408/// place in-range. Return true if we changed any addresses (thus must run
1409/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001410bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1411 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001412 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001413 MachineInstr *UserMI = U.MI;
1414 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001415 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001416 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001417 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001418 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001419
Dale Johannesene18b13b2007-02-23 05:02:36 +00001420 // See if the current entry is within range, or there is a clone of it
1421 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001422 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001423 if (result==1) return false;
1424 else if (result==2) return true;
1425
1426 // No existing clone of this CPE is within range.
1427 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001428 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001429
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001430 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001431 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001432 MachineBasicBlock *NewMBB;
1433 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001434 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001435 LLVM_DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001436 MachineBasicBlock *WaterBB = *IP;
1437
1438 // If the original WaterList entry was "new water" on this iteration,
1439 // propagate that to the new island. This is just keeping NewWaterList
1440 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001441 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001442 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001443
Bob Wilson2f9be502009-10-15 20:49:47 +00001444 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001445 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001446 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001447 // No water found.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001448 LLVM_DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001449 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001450
Jim Grosbach190e7b62012-03-23 23:07:03 +00001451 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001452 // called while handling branches so that the water will be seen on the
1453 // next iteration for constant pools, but in this context, we don't want
1454 // it. Check for this so it will be removed from the WaterList.
1455 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001456 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
David Majnemer0d955d02016-08-11 22:21:41 +00001457 IP = find(WaterList, WaterBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001458 if (IP != WaterList.end())
1459 NewWaterList.erase(WaterBB);
1460
1461 // We are adding new water. Update NewWaterList.
1462 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001463 }
Sjoerd Meijerfc0d02c2018-02-27 19:26:02 +00001464 // Always align the new block because CP entries can be smaller than 4
1465 // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
1466 // be an already aligned constant pool block.
1467 const unsigned Align = isThumb ? 1 : 2;
1468 if (NewMBB->getAlignment() < Align)
1469 NewMBB->setAlignment(Align);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001470
Bob Wilson2f9be502009-10-15 20:49:47 +00001471 // Remove the original WaterList entry; we want subsequent insertions in
1472 // this vicinity to go after the one we're about to insert. This
1473 // considerably reduces the number of times we have to move the same CPE
1474 // more than once and is also important to ensure the algorithm terminates.
1475 if (IP != WaterList.end())
1476 WaterList.erase(IP);
1477
Dale Johannesene18b13b2007-02-23 05:02:36 +00001478 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001479 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001480
1481 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001482 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001483
Dale Johannesene18b13b2007-02-23 05:02:36 +00001484 // Now that we have an island to add the CPE to, clone the original CPE and
1485 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001486 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001487 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
Diana Picus116bbab2017-01-13 09:58:52 +00001488 .addImm(ID)
1489 .add(CPEMI->getOperand(1))
1490 .addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001491 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001492 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001493
Tim Northovera603c402015-05-31 19:22:07 +00001494 // Decrement the old entry, and remove it if refcount becomes 0.
1495 decrementCPEReferenceCount(CPI, CPEMI);
1496
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001497 // Mark the basic block as aligned as required by the const-pool entry.
1498 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001499
Evan Cheng10043e22007-01-19 07:51:42 +00001500 // Increase the size of the island block to account for the new entry.
Sam Parker966f4e82019-06-17 08:49:09 +00001501 BBUtils->adjustBBSize(NewIsland, Size);
1502 BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001503
Evan Cheng10043e22007-01-19 07:51:42 +00001504 // Finally, change the CPI in the instruction operand to be ID.
1505 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001506 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001507 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001508 break;
1509 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001510
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001511 LLVM_DEBUG(
1512 dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Sam Parker966f4e82019-06-17 08:49:09 +00001513 << format(" offset=%#x\n",
1514 BBUtils->getBBInfo()[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001515
Evan Cheng10043e22007-01-19 07:51:42 +00001516 return true;
1517}
1518
Jim Grosbach190e7b62012-03-23 23:07:03 +00001519/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001520/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001521void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001522 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001523 unsigned Size = CPEMI->getOperand(2).getImm();
1524 CPEMI->eraseFromParent();
Sam Parker966f4e82019-06-17 08:49:09 +00001525 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1526 BBUtils->adjustBBSize(CPEBB, -Size);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001527 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001528 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001529 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001530
Evan Chengab28b9a2013-02-21 18:37:54 +00001531 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001532 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001533 } else
1534 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001535 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001536
Sam Parker966f4e82019-06-17 08:49:09 +00001537 BBUtils->adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001538 // An island has only one predecessor BB and one successor BB. Check if
1539 // this BB's predecessor jumps directly to this BB's successor. This
1540 // shouldn't happen currently.
1541 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1542 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001543}
1544
Jim Grosbach190e7b62012-03-23 23:07:03 +00001545/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001546/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001547bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001548 unsigned MadeChange = false;
1549 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1550 std::vector<CPEntry> &CPEs = CPEntries[i];
1551 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1552 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001553 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001554 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001555 MadeChange = true;
1556 }
1557 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001558 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001559 return MadeChange;
1560}
1561
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001562
Jim Grosbach190e7b62012-03-23 23:07:03 +00001563/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001564/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001565bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001566 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001567 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001568
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001569 // Check to see if the DestBB is already in-range.
Sam Parker966f4e82019-06-17 08:49:09 +00001570 if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001571 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001572
Evan Cheng7fa69642007-01-30 01:18:38 +00001573 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001574 return fixupUnconditionalBr(Br);
1575 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001576}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001577
Jim Grosbach190e7b62012-03-23 23:07:03 +00001578/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001579/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001580/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001581/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001582bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001583ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001584 MachineInstr *MI = Br.MI;
1585 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001586 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001587 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001588
Eli Friedman2596e8b2019-03-19 21:48:08 +00001589 if (!AFI->isLRSpilled())
1590 report_fatal_error("underestimated function size");
1591
Evan Cheng7fa69642007-01-30 01:18:38 +00001592 // Use BL to implement far jump.
1593 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001594 MI->setDesc(TII->get(ARM::tBfar));
Sam Parker966f4e82019-06-17 08:49:09 +00001595 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001596 BBInfo[MBB->getNumber()].Size += 2;
Sam Parker966f4e82019-06-17 08:49:09 +00001597 BBUtils->adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001598 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001599 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001600
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001601 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001602
Evan Cheng7fa69642007-01-30 01:18:38 +00001603 return true;
1604}
1605
Jim Grosbach190e7b62012-03-23 23:07:03 +00001606/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001607/// far away to fit in its displacement field. It is converted to an inverse
1608/// conditional branch + an unconditional branch to the destination.
1609bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001610ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001611 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001612 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001613
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001614 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001615 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001616 // blt L1
1617 // =>
1618 // bge L2
1619 // b L1
1620 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001621 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001622 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001623 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001624
1625 // If the branch is at the end of its MBB and that has a fall-through block,
1626 // direct the updated conditional branch to the fall-through block. Otherwise,
1627 // split the MBB before the next instruction.
1628 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001629 MachineInstr *BMI = &MBB->back();
1630 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001631
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001632 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001633 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001634 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001635 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001636 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001637 // condition and swap destinations:
1638 // beq L1
1639 // b L2
1640 // =>
1641 // bne L2
1642 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001643 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Sam Parker966f4e82019-06-17 08:49:09 +00001644 if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001645 LLVM_DEBUG(
1646 dbgs() << " Invert Bcc condition and swap its destination with "
1647 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001648 BMI->getOperand(0).setMBB(DestBB);
1649 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001650 MI->getOperand(1).setImm(CC);
1651 return true;
1652 }
1653 }
1654 }
1655
1656 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001657 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001658 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001659 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001660 int delta = TII->getInstSizeInBytes(MBB->back());
Sam Parker966f4e82019-06-17 08:49:09 +00001661 BBUtils->adjustBBSize(MBB, -delta);
Evan Cheng1e270b62007-01-26 02:02:39 +00001662 MBB->back().eraseFromParent();
Tim Northover5cdc4f92017-11-14 11:43:54 +00001663
1664 // The conditional successor will be swapped between the BBs after this, so
1665 // update CFG.
1666 MBB->addSuccessor(DestBB);
1667 std::next(MBB->getIterator())->removeSuccessor(DestBB);
1668
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001669 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001670 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001671 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001672
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001673 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
1674 << " also invert condition and change dest. to "
1675 << printMBBReference(*NextBB) << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001676
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001677 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001678 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001679 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001680 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001681 Br.MI = &MBB->back();
Sam Parker966f4e82019-06-17 08:49:09 +00001682 BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
Owen Anderson93cd3182011-09-09 23:05:14 +00001683 if (isThumb)
Diana Picusbd66b7d2017-01-20 08:15:24 +00001684 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1685 .addMBB(DestBB)
1686 .add(predOps(ARMCC::AL));
Owen Anderson93cd3182011-09-09 23:05:14 +00001687 else
1688 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sam Parker966f4e82019-06-17 08:49:09 +00001689 BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
Evan Cheng7169bd82007-01-31 18:29:27 +00001690 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001691 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001692
1693 // Remove the old conditional branch. It may or may not still be in MBB.
Sam Parker966f4e82019-06-17 08:49:09 +00001694 BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI));
Evan Cheng22c7cf52007-01-25 03:12:46 +00001695 MI->eraseFromParent();
Sam Parker966f4e82019-06-17 08:49:09 +00001696 BBUtils->adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001697 return true;
1698}
Evan Cheng7fa69642007-01-30 01:18:38 +00001699
Jim Grosbach190e7b62012-03-23 23:07:03 +00001700/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001701/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1702/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001703bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001704 bool MadeChange = false;
1705 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1706 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001707 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001708 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001709 MI->getOperand(2).getReg() == ARM::PC &&
1710 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001711 // Create the new insn and copy the predicate from the old.
1712 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
Diana Picus116bbab2017-01-13 09:58:52 +00001713 .add(MI->getOperand(0))
1714 .add(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001715 MI->eraseFromParent();
1716 MadeChange = true;
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001717 } else if (MI->getOpcode() == ARM::tPUSH &&
1718 MI->getOperand(2).getReg() == ARM::LR &&
1719 MI->getNumExplicitOperands() == 3) {
Roger Ferrer Ibanez56db97d2017-02-22 09:06:21 +00001720 // Just remove the push.
1721 MI->eraseFromParent();
1722 MadeChange = true;
1723 }
Evan Cheng7fa69642007-01-30 01:18:38 +00001724 }
1725 return MadeChange;
1726}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001727
Jim Grosbach190e7b62012-03-23 23:07:03 +00001728bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001729 bool MadeChange = false;
1730
1731 // Shrink ADR and LDR from constantpool.
1732 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1733 CPUser &U = CPUsers[i];
1734 unsigned Opcode = U.MI->getOpcode();
1735 unsigned NewOpc = 0;
1736 unsigned Scale = 1;
1737 unsigned Bits = 0;
1738 switch (Opcode) {
1739 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001740 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001741 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1742 NewOpc = ARM::tLEApcrel;
1743 Bits = 8;
1744 Scale = 4;
1745 }
1746 break;
1747 case ARM::t2LDRpci:
1748 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1749 NewOpc = ARM::tLDRpci;
1750 Bits = 8;
1751 Scale = 4;
1752 }
1753 break;
1754 }
1755
1756 if (!NewOpc)
1757 continue;
1758
Jim Grosbach190e7b62012-03-23 23:07:03 +00001759 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001760 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001761
1762 // Be conservative with inline asm.
1763 if (!U.KnownAlignment)
1764 MaxOffs -= 2;
1765
Evan Chengdb73d682009-08-14 00:32:16 +00001766 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001767 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001768 LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001769 U.MI->setDesc(TII->get(NewOpc));
1770 MachineBasicBlock *MBB = U.MI->getParent();
Sam Parker966f4e82019-06-17 08:49:09 +00001771 BBUtils->adjustBBSize(MBB, -2);
1772 BBUtils->adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001773 ++NumT2CPShrunk;
1774 MadeChange = true;
1775 }
1776 }
1777
Evan Chengdb73d682009-08-14 00:32:16 +00001778 return MadeChange;
1779}
1780
Jim Grosbach190e7b62012-03-23 23:07:03 +00001781bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001782 bool MadeChange = false;
1783
Peter Collingbourne167668f2015-04-23 20:31:35 +00001784 // The order in which branches appear in ImmBranches is approximately their
1785 // order within the function body. By visiting later branches first, we reduce
1786 // the distance between earlier forward branches and their targets, making it
1787 // more likely that the cbn?z optimization, which can only apply to forward
1788 // branches, will succeed.
1789 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1790 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001791 unsigned Opcode = Br.MI->getOpcode();
1792 unsigned NewOpc = 0;
1793 unsigned Scale = 1;
1794 unsigned Bits = 0;
1795 switch (Opcode) {
1796 default: break;
1797 case ARM::t2B:
1798 NewOpc = ARM::tB;
1799 Bits = 11;
1800 Scale = 2;
1801 break;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001802 case ARM::t2Bcc:
Evan Chenge41903b2009-08-14 18:31:44 +00001803 NewOpc = ARM::tBcc;
1804 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001805 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001806 break;
1807 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001808 if (NewOpc) {
1809 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1810 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Sam Parker966f4e82019-06-17 08:49:09 +00001811 if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001812 LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001813 Br.MI->setDesc(TII->get(NewOpc));
1814 MachineBasicBlock *MBB = Br.MI->getParent();
Sam Parker966f4e82019-06-17 08:49:09 +00001815 BBUtils->adjustBBSize(MBB, -2);
1816 BBUtils->adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001817 ++NumT2BrShrunk;
1818 MadeChange = true;
1819 }
1820 }
1821
1822 Opcode = Br.MI->getOpcode();
1823 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001824 continue;
1825
Evan Cheng6bb95252012-01-14 01:53:46 +00001826 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1827 // so this transformation is not safe.
1828 if (!Br.MI->killsRegister(ARM::CPSR))
1829 continue;
1830
Evan Cheng6f29ad92009-10-31 23:46:45 +00001831 NewOpc = 0;
1832 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001833 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001834 if (Pred == ARMCC::EQ)
1835 NewOpc = ARM::tCBZ;
1836 else if (Pred == ARMCC::NE)
1837 NewOpc = ARM::tCBNZ;
1838 if (!NewOpc)
1839 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001840 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001841 // Check if the distance is within 126. Subtract starting offset by 2
1842 // because the cmp will be eliminated.
Sam Parker966f4e82019-06-17 08:49:09 +00001843 unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2;
1844 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001845 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
David Greene0b48a82019-03-17 16:11:22 +00001846 if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)
1847 continue;
1848
David Greenc519d3c2019-04-23 12:11:26 +00001849 // Search backwards to find a tCMPi8
David Greene0b48a82019-03-17 16:11:22 +00001850 auto *TRI = STI->getRegisterInfo();
David Greenc519d3c2019-04-23 12:11:26 +00001851 MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);
1852 if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)
1853 continue;
David Greene0b48a82019-03-17 16:11:22 +00001854
David Greene0b48a82019-03-17 16:11:22 +00001855 unsigned Reg = CmpMI->getOperand(0).getReg();
David Greene0b48a82019-03-17 16:11:22 +00001856
1857 // Check for Kill flags on Reg. If they are present remove them and set kill
1858 // on the new CBZ.
1859 MachineBasicBlock::iterator KillMI = Br.MI;
1860 bool RegKilled = false;
1861 do {
1862 --KillMI;
1863 if (KillMI->killsRegister(Reg, TRI)) {
1864 KillMI->clearRegisterKills(Reg, TRI);
1865 RegKilled = true;
1866 break;
1867 }
1868 } while (KillMI != CmpMI);
1869
1870 // Create the new CBZ/CBNZ
1871 MachineBasicBlock *MBB = Br.MI->getParent();
1872 LLVM_DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1873 MachineInstr *NewBR =
1874 BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1875 .addReg(Reg, getKillRegState(RegKilled))
1876 .addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1877 CmpMI->eraseFromParent();
1878 Br.MI->eraseFromParent();
1879 Br.MI = NewBR;
1880 BBInfo[MBB->getNumber()].Size -= 2;
Sam Parker966f4e82019-06-17 08:49:09 +00001881 BBUtils->adjustBBOffsetsAfter(MBB);
David Greene0b48a82019-03-17 16:11:22 +00001882 ++NumCBZ;
1883 MadeChange = true;
Evan Chenge41903b2009-08-14 18:31:44 +00001884 }
1885
1886 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001887}
1888
Tim Northovera603c402015-05-31 19:22:07 +00001889static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1890 unsigned BaseReg) {
1891 if (I.getOpcode() != ARM::t2ADDrs)
1892 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001893
Tim Northovera603c402015-05-31 19:22:07 +00001894 if (I.getOperand(0).getReg() != EntryReg)
1895 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001896
Tim Northovera603c402015-05-31 19:22:07 +00001897 if (I.getOperand(1).getReg() != BaseReg)
1898 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001899
Tim Northovera603c402015-05-31 19:22:07 +00001900 // FIXME: what about CC and IdxReg?
1901 return true;
1902}
Tim Northover688f7bb2015-05-13 20:28:32 +00001903
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001904/// While trying to form a TBB/TBH instruction, we may (if the table
Tim Northovera603c402015-05-31 19:22:07 +00001905/// doesn't immediately follow the BR_JT) need access to the start of the
1906/// jump-table. We know one instruction that produces such a register; this
1907/// function works out whether that definition can be preserved to the BR_JT,
1908/// possibly by removing an intervening addition (which is usually needed to
1909/// calculate the actual entry to jump to).
1910bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1911 MachineInstr *LEAMI,
1912 unsigned &DeadSize,
1913 bool &CanDeleteLEA,
1914 bool &BaseRegKill) {
1915 if (JumpMI->getParent() != LEAMI->getParent())
1916 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001917
Tim Northovera603c402015-05-31 19:22:07 +00001918 // Now we hope that we have at least these instructions in the basic block:
1919 // BaseReg = t2LEA ...
1920 // [...]
1921 // EntryReg = t2ADDrs BaseReg, ...
1922 // [...]
1923 // t2BR_JT EntryReg
1924 //
1925 // We have to be very conservative about what we recognise here though. The
1926 // main perturbing factors to watch out for are:
1927 // + Spills at any point in the chain: not direct problems but we would
1928 // expect a blocking Def of the spilled register so in practice what we
1929 // can do is limited.
1930 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1931 // of BaseReg, but only if the t2ADDrs can be removed.
1932 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1933 // the wild, but we should be careful.
1934 unsigned EntryReg = JumpMI->getOperand(0).getReg();
1935 unsigned BaseReg = LEAMI->getOperand(0).getReg();
1936
1937 CanDeleteLEA = true;
1938 BaseRegKill = false;
1939 MachineInstr *RemovableAdd = nullptr;
1940 MachineBasicBlock::iterator I(LEAMI);
1941 for (++I; &*I != JumpMI; ++I) {
1942 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1943 RemovableAdd = &*I;
1944 break;
1945 }
1946
1947 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1948 const MachineOperand &MO = I->getOperand(K);
1949 if (!MO.isReg() || !MO.getReg())
1950 continue;
1951 if (MO.isDef() && MO.getReg() == BaseReg)
1952 return false;
1953 if (MO.isUse() && MO.getReg() == BaseReg) {
1954 BaseRegKill = BaseRegKill || MO.isKill();
1955 CanDeleteLEA = false;
1956 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001957 }
1958 }
1959
Tim Northovera603c402015-05-31 19:22:07 +00001960 if (!RemovableAdd)
1961 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00001962
Tim Northovera603c402015-05-31 19:22:07 +00001963 // Check the add really is removable, and that nothing else in the block
1964 // clobbers BaseReg.
1965 for (++I; &*I != JumpMI; ++I) {
1966 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1967 const MachineOperand &MO = I->getOperand(K);
1968 if (!MO.isReg() || !MO.getReg())
1969 continue;
1970 if (MO.isDef() && MO.getReg() == BaseReg)
1971 return false;
1972 if (MO.isUse() && MO.getReg() == EntryReg)
1973 RemovableAdd = nullptr;
1974 }
1975 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001976
Tim Northovera603c402015-05-31 19:22:07 +00001977 if (RemovableAdd) {
1978 RemovableAdd->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00001979 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00001980 } else if (BaseReg == EntryReg) {
1981 // The add wasn't removable, but clobbered the base for the TBB. So we can't
1982 // preserve it.
1983 return false;
1984 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001985
Tim Northovera603c402015-05-31 19:22:07 +00001986 // We reached the end of the block without seeing another definition of
1987 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
1988 // used in the TBB/TBH if necessary.
1989 return true;
1990}
Tim Northover688f7bb2015-05-13 20:28:32 +00001991
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001992/// Returns whether CPEMI is the first instruction in the block
Tim Northovera603c402015-05-31 19:22:07 +00001993/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
1994/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001995/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00001996static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001997 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00001998 MachineFunction *MF = MBB->getParent();
1999 ++MBB;
2000
2001 return MBB != MF->end() && MBB->begin() != MBB->end() &&
2002 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00002003}
2004
David Green1b4b59a2017-04-06 08:32:47 +00002005static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,
2006 MachineInstr *JumpMI,
2007 unsigned &DeadSize) {
2008 // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2009 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2010 // and is not clobbered / used.
2011 MachineInstr *RemovableAdd = nullptr;
2012 unsigned EntryReg = JumpMI->getOperand(0).getReg();
2013
2014 // Find the last ADD to set EntryReg
2015 MachineBasicBlock::iterator I(LEAMI);
2016 for (++I; &*I != JumpMI; ++I) {
2017 if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2018 RemovableAdd = &*I;
2019 }
2020
2021 if (!RemovableAdd)
2022 return;
2023
2024 // Ensure EntryReg is not clobbered or used.
2025 MachineBasicBlock::iterator J(RemovableAdd);
2026 for (++J; &*J != JumpMI; ++J) {
2027 for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
2028 const MachineOperand &MO = J->getOperand(K);
2029 if (!MO.isReg() || !MO.getReg())
2030 continue;
2031 if (MO.isDef() && MO.getReg() == EntryReg)
2032 return;
2033 if (MO.isUse() && MO.getReg() == EntryReg)
2034 return;
2035 }
2036 }
2037
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002038 LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
David Green1b4b59a2017-04-06 08:32:47 +00002039 RemovableAdd->eraseFromParent();
2040 DeadSize += 4;
2041}
2042
Jim Grosbach190e7b62012-03-23 23:07:03 +00002043/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00002044/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002045bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00002046 bool MadeChange = false;
2047
2048 // FIXME: After the tables are shrunk, can we get rid some of the
2049 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002050 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002051 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002052
Evan Chengc6d70ae2009-07-29 02:18:14 +00002053 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2054 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2055 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002056 const MCInstrDesc &MCID = MI->getDesc();
2057 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002058 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002059 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2060 unsigned JTI = JTOP.getIndex();
2061 assert(JTI < JT.size());
2062
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002063 bool ByteOk = true;
2064 bool HalfWordOk = true;
Sam Parker966f4e82019-06-17 08:49:09 +00002065 unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002066 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Sam Parker966f4e82019-06-17 08:49:09 +00002067 BBInfoVector &BBInfo = BBUtils->getBBInfo();
Evan Chengc6d70ae2009-07-29 02:18:14 +00002068 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2069 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002070 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002071 // Negative offset is not ok. FIXME: We should change BB layout to make
2072 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002073 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002074 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002075 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002076 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002077 HalfWordOk = false;
2078 if (!ByteOk && !HalfWordOk)
2079 break;
2080 }
2081
Tim Northovera603c402015-05-31 19:22:07 +00002082 if (!ByteOk && !HalfWordOk)
2083 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002084
James Molloy70a3d6d2016-11-01 13:37:41 +00002085 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
Tim Northovera603c402015-05-31 19:22:07 +00002086 MachineBasicBlock *MBB = MI->getParent();
2087 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2088 continue;
Tim Northovera603c402015-05-31 19:22:07 +00002089
Tim Northovera603c402015-05-31 19:22:07 +00002090 unsigned DeadSize = 0;
2091 bool CanDeleteLEA = false;
2092 bool BaseRegKill = false;
Fangrui Songf78650a2018-07-30 19:41:25 +00002093
James Molloy70a3d6d2016-11-01 13:37:41 +00002094 unsigned IdxReg = ~0U;
2095 bool IdxRegKill = true;
2096 if (isThumb2) {
2097 IdxReg = MI->getOperand(1).getReg();
2098 IdxRegKill = MI->getOperand(1).isKill();
2099
2100 bool PreservedBaseReg =
Tim Northovera603c402015-05-31 19:22:07 +00002101 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
James Molloy70a3d6d2016-11-01 13:37:41 +00002102 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2103 continue;
2104 } else {
2105 // We're in thumb-1 mode, so we must have something like:
2106 // %idx = tLSLri %idx, 2
2107 // %base = tLEApcrelJT
Momchil Velikov842aa902017-11-13 11:56:48 +00002108 // %t = tLDRr %base, %idx
James Molloy70a3d6d2016-11-01 13:37:41 +00002109 unsigned BaseReg = User.MI->getOperand(0).getReg();
James Molloy2bae8642016-10-22 09:58:37 +00002110
James Molloy70a3d6d2016-11-01 13:37:41 +00002111 if (User.MI->getIterator() == User.MI->getParent()->begin())
2112 continue;
2113 MachineInstr *Shift = User.MI->getPrevNode();
2114 if (Shift->getOpcode() != ARM::tLSLri ||
2115 Shift->getOperand(3).getImm() != 2 ||
2116 !Shift->getOperand(2).isKill())
2117 continue;
2118 IdxReg = Shift->getOperand(2).getReg();
2119 unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
Tim Northovera603c402015-05-31 19:22:07 +00002120
Tim Northover0d98b032017-03-15 18:38:13 +00002121 // It's important that IdxReg is live until the actual TBB/TBH. Most of
2122 // the range is checked later, but the LEA might still clobber it and not
2123 // actually get removed.
2124 if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
2125 continue;
2126
James Molloy70a3d6d2016-11-01 13:37:41 +00002127 MachineInstr *Load = User.MI->getNextNode();
2128 if (Load->getOpcode() != ARM::tLDRr)
2129 continue;
Momchil Velikov842aa902017-11-13 11:56:48 +00002130 if (Load->getOperand(1).getReg() != BaseReg ||
2131 Load->getOperand(2).getReg() != ShiftedIdxReg ||
2132 !Load->getOperand(2).isKill())
James Molloy70a3d6d2016-11-01 13:37:41 +00002133 continue;
2134
2135 // If we're in PIC mode, there should be another ADD following.
James Molloy92497542017-02-13 14:07:39 +00002136 auto *TRI = STI->getRegisterInfo();
Weiming Zhao962c5a32017-04-20 18:37:14 +00002137
2138 // %base cannot be redefined after the load as it will appear before
2139 // TBB/TBH like:
2140 // %base =
2141 // %base =
2142 // tBB %base, %idx
2143 if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
2144 continue;
2145
James Molloy70a3d6d2016-11-01 13:37:41 +00002146 if (isPositionIndependentOrROPI) {
2147 MachineInstr *Add = Load->getNextNode();
2148 if (Add->getOpcode() != ARM::tADDrr ||
Momchil Velikov842aa902017-11-13 11:56:48 +00002149 Add->getOperand(2).getReg() != BaseReg ||
2150 Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
2151 !Add->getOperand(3).isKill())
James Molloy70a3d6d2016-11-01 13:37:41 +00002152 continue;
2153 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2154 continue;
James Molloy92497542017-02-13 14:07:39 +00002155 if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
2156 // IdxReg gets redefined in the middle of the sequence.
2157 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002158 Add->eraseFromParent();
2159 DeadSize += 2;
2160 } else {
2161 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2162 continue;
James Molloy92497542017-02-13 14:07:39 +00002163 if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
2164 // IdxReg gets redefined in the middle of the sequence.
2165 continue;
James Molloy70a3d6d2016-11-01 13:37:41 +00002166 }
Tim Northover0d98b032017-03-15 18:38:13 +00002167
James Molloy70a3d6d2016-11-01 13:37:41 +00002168 // Now safe to delete the load and lsl. The LEA will be removed later.
2169 CanDeleteLEA = true;
2170 Shift->eraseFromParent();
2171 Load->eraseFromParent();
2172 DeadSize += 4;
2173 }
Tim Northover0d98b032017-03-15 18:38:13 +00002174
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002175 LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
Tim Northovera603c402015-05-31 19:22:07 +00002176 MachineInstr *CPEMI = User.CPEMI;
2177 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
James Molloy70a3d6d2016-11-01 13:37:41 +00002178 if (!isThumb2)
2179 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2180
Tim Northovera603c402015-05-31 19:22:07 +00002181 MachineBasicBlock::iterator MI_JT = MI;
2182 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002183 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002184 .addReg(User.MI->getOperand(0).getReg(),
2185 getKillRegState(BaseRegKill))
2186 .addReg(IdxReg, getKillRegState(IdxRegKill))
2187 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2188 .addImm(CPEMI->getOperand(0).getImm());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002189 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002190
Tim Northovera603c402015-05-31 19:22:07 +00002191 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2192 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002193
Tim Northovera603c402015-05-31 19:22:07 +00002194 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2195 NewJTMI->getOperand(0).setReg(ARM::PC);
2196 NewJTMI->getOperand(0).setIsKill(false);
2197
David Green1b4b59a2017-04-06 08:32:47 +00002198 if (CanDeleteLEA) {
2199 if (isThumb2)
2200 RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
2201
Tim Northovera603c402015-05-31 19:22:07 +00002202 User.MI->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00002203 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00002204
2205 // The LEA was eliminated, the TBB instruction becomes the only new user
2206 // of the jump table.
2207 User.MI = NewJTMI;
2208 User.MaxDisp = 4;
2209 User.NegOk = false;
2210 User.IsSoImm = false;
2211 User.KnownAlignment = false;
2212 } else {
2213 // The LEA couldn't be eliminated, so we must add another CPUser to
2214 // record the TBB or TBH use.
2215 int CPEntryIdx = JumpTableEntryIndices[JTI];
2216 auto &CPEs = CPEntries[CPEntryIdx];
David Majnemer562e8292016-08-12 00:18:03 +00002217 auto Entry =
2218 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
Tim Northovera603c402015-05-31 19:22:07 +00002219 ++Entry->RefCount;
2220 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2221 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002222 }
Tim Northovera603c402015-05-31 19:22:07 +00002223
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002224 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2225 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002226 MI->eraseFromParent();
2227
2228 int Delta = OrigSize - NewSize + DeadSize;
2229 BBInfo[MBB->getNumber()].Size -= Delta;
Sam Parker966f4e82019-06-17 08:49:09 +00002230 BBUtils->adjustBBOffsetsAfter(MBB);
Tim Northovera603c402015-05-31 19:22:07 +00002231
2232 ++NumTBs;
2233 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002234 }
2235
2236 return MadeChange;
2237}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002238
Jim Grosbach190e7b62012-03-23 23:07:03 +00002239/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002240/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002241bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002242 bool MadeChange = false;
2243
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002244 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002245 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002246
Jim Grosbach5d577142009-11-12 17:25:07 +00002247 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2248 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2249 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002250 const MCInstrDesc &MCID = MI->getDesc();
2251 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002252 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002253 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2254 unsigned JTI = JTOP.getIndex();
2255 assert(JTI < JT.size());
2256
2257 // We prefer if target blocks for the jump table come after the jump
2258 // instruction so we can use TB[BH]. Loop through the target blocks
2259 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002260 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002261 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2262 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2263 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002264 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002265
Jim Grosbach9785e592009-11-16 18:58:52 +00002266 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002267 // The destination precedes the switch. Try to move the block forward
2268 // so we have a positive offset.
2269 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002270 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002271 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002272 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002273 MadeChange = true;
2274 }
2275 }
2276 }
2277
2278 return MadeChange;
2279}
2280
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002281MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002282adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002283 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002284 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002285 // table that branches back to the actual target. This is a very simple
2286 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002287 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002288 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002289 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002290 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002291 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002292
Jim Grosbach47d5e332009-11-16 17:10:56 +00002293 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002294 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002295
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002296 // If the block ends in an unconditional branch, move it. The prior block
2297 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002298 // 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 +00002299 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002300 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002301 BB->moveAfter(JTBB);
2302 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002303 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002304 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002305 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002306 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002307 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002308 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002309
2310 // Create a new MBB for the code after the jump BB.
2311 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002312 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002313 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002314 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002315
2316 // Add an unconditional branch from NewBB to BB.
2317 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2318 // correspond directly to anything in the source.
James Molloy70a3d6d2016-11-01 13:37:41 +00002319 if (isThumb2)
2320 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2321 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002322 .add(predOps(ARMCC::AL));
James Molloy70a3d6d2016-11-01 13:37:41 +00002323 else
2324 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2325 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002326 .add(predOps(ARMCC::AL));
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002327
Jim Grosbach43d21082009-11-14 20:10:18 +00002328 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002329 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002330
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002331 // Update the CFG.
2332 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002333 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002334
Jim Grosbach5d577142009-11-12 17:25:07 +00002335 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002336 return NewBB;
2337}
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00002338
2339/// createARMConstantIslandPass - returns an instance of the constpool
2340/// island pass.
2341FunctionPass *llvm::createARMConstantIslandPass() {
2342 return new ARMConstantIslands();
2343}
James Molloy9b3b8992017-02-13 14:07:25 +00002344
2345INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
2346 false, false)