1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function. This is required due to the
12 // limited pc-relative displacements that ARM has.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "arm-cp-islands"
18 #include "ARMInstrInfo.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/Target/TargetAsmInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
33 STATISTIC(NumSplit, "Number of uncond branches inserted");
36 /// ARMConstantIslands - Due to limited pc-relative displacements, ARM
37 /// requires constant pool entries to be scattered among the instructions
38 /// inside a function. To do this, it completely ignores the normal LLVM
39 /// constant pool, instead, it places constants where-ever it feels like with
40 /// special instructions.
42 /// The terminology used in this pass includes:
43 /// Islands - Clumps of constants placed in the function.
44 /// Water - Potential places where an island could be formed.
45 /// CPE - A constant pool entry that has been placed somewhere, which
46 /// tracks a list of users.
47 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
48 /// NextUID - Assign unique ID's to CPE's.
51 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
53 std::vector<unsigned> BBSizes;
55 /// WaterList - A sorted list of basic blocks where islands could be placed
56 /// (i.e. blocks that don't fall through to the following block, due
57 /// to a return, unreachable, or unconditional branch).
58 std::vector<MachineBasicBlock*> WaterList;
60 /// CPUser - One user of a constant pool, keeping the machine instruction
61 /// pointer, the constant pool being referenced, and the max displacement
62 /// allowed from the instruction to the CP.
67 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
68 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
71 /// CPUsers - Keep track of all of the machine instructions that use various
72 /// constant pools and their max displacement.
73 std::vector<CPUser> CPUsers;
75 const TargetInstrInfo *TII;
76 const TargetAsmInfo *TAI;
78 virtual bool runOnMachineFunction(MachineFunction &Fn);
80 virtual const char *getPassName() const {
81 return "ARM constant island placement pass";
85 void DoInitialPlacement(MachineFunction &Fn,
86 std::vector<MachineInstr*> &CPEMIs);
87 void InitialFunctionScan(MachineFunction &Fn,
88 const std::vector<MachineInstr*> &CPEMIs);
89 void SplitBlockBeforeInstr(MachineInstr *MI);
90 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
91 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
93 unsigned GetInstSize(MachineInstr *MI) const;
94 unsigned GetOffsetOf(MachineInstr *MI) const;
98 /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
99 /// optimization pass.
100 FunctionPass *llvm::createARMConstantIslandPass() {
101 return new ARMConstantIslands();
104 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
105 // If there are no constants, there is nothing to do.
106 MachineConstantPool &MCP = *Fn.getConstantPool();
107 if (MCP.isEmpty()) return false;
109 TII = Fn.getTarget().getInstrInfo();
110 TAI = Fn.getTarget().getTargetAsmInfo();
112 // Renumber all of the machine basic blocks in the function, guaranteeing that
113 // the numbers agree with the position of the block in the function.
116 // Perform the initial placement of the constant pool entries. To start with,
117 // we put them all at the end of the function.
118 std::vector<MachineInstr*> CPEMIs;
119 DoInitialPlacement(Fn, CPEMIs);
121 /// The next UID to take is the first unused one.
122 NextUID = CPEMIs.size();
124 // Do the initial scan of the function, building up information about the
125 // sizes of each block, the location of all the water, and finding all of the
126 // constant pool users.
127 InitialFunctionScan(Fn, CPEMIs);
130 // Iteratively place constant pool entries until there is no change.
134 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
135 MadeChange |= HandleConstantPoolUser(Fn, CPUsers[i]);
136 } while (MadeChange);
145 /// DoInitialPlacement - Perform the initial placement of the constant pool
146 /// entries. To start with, we put them all at the end of the function.
147 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
148 std::vector<MachineInstr*> &CPEMIs){
149 // Create the basic block to hold the CPE's.
150 MachineBasicBlock *BB = new MachineBasicBlock();
151 Fn.getBasicBlockList().push_back(BB);
153 // Add all of the constants from the constant pool to the end block, use an
154 // identity mapping of CPI's to CPE's.
155 const std::vector<MachineConstantPoolEntry> &CPs =
156 Fn.getConstantPool()->getConstants();
158 const TargetData &TD = *Fn.getTarget().getTargetData();
159 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
160 unsigned Size = TD.getTypeSize(CPs[i].getType());
161 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
162 // we would have to pad them out or something so that instructions stay
164 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
165 MachineInstr *CPEMI =
166 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
167 .addImm(i).addConstantPoolIndex(i).addImm(Size);
168 CPEMIs.push_back(CPEMI);
169 DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
174 /// BBHasFallthrough - Return true of the specified basic block can fallthrough
175 /// into the block immediately after it.
176 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
177 // Get the next machine basic block in the function.
178 MachineFunction::iterator MBBI = MBB;
179 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
182 MachineBasicBlock *NextBB = next(MBBI);
183 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
184 E = MBB->succ_end(); I != E; ++I)
191 /// InitialFunctionScan - Do the initial scan of the function, building up
192 /// information about the sizes of each block, the location of all the water,
193 /// and finding all of the constant pool users.
194 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
195 const std::vector<MachineInstr*> &CPEMIs) {
196 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
198 MachineBasicBlock &MBB = *MBBI;
200 // If this block doesn't fall through into the next MBB, then this is
201 // 'water' that a constant pool island could be placed.
202 if (!BBHasFallthrough(&MBB))
203 WaterList.push_back(&MBB);
205 unsigned MBBSize = 0;
206 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
208 // Add instruction size to MBBSize.
209 MBBSize += GetInstSize(I);
211 // Scan the instructions for constant pool operands.
212 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
213 if (I->getOperand(op).isConstantPoolIndex()) {
214 // We found one. The addressing mode tells us the max displacement
215 // from the PC that this instruction permits.
216 unsigned MaxOffs = 0;
218 // Basic size info comes from the TSFlags field.
219 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
220 switch (TSFlags & ARMII::AddrModeMask) {
222 // Constant pool entries can reach anything.
223 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
225 assert(0 && "Unknown addressing mode for CP reference!");
226 case ARMII::AddrMode1: // AM1: 8 bits << 2
227 MaxOffs = 1 << (8+2); // Taking the address of a CP entry.
229 case ARMII::AddrMode2:
230 MaxOffs = 1 << 12; // +-offset_12
232 case ARMII::AddrMode3:
233 MaxOffs = 1 << 8; // +-offset_8
235 // addrmode4 has no immediate offset.
236 case ARMII::AddrMode5:
237 MaxOffs = 1 << (8+2); // +-(offset_8*4)
239 case ARMII::AddrModeT1:
242 case ARMII::AddrModeT2:
243 MaxOffs = 1 << (5+1);
245 case ARMII::AddrModeT4:
246 MaxOffs = 1 << (5+2);
250 // Remember that this is a user of a CP entry.
251 MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
252 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
254 // Instructions can only use one CP entry, don't bother scanning the
255 // rest of the operands.
259 BBSizes.push_back(MBBSize);
263 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
264 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
265 unsigned JTI) DISABLE_INLINE;
266 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
268 return JT[JTI].MBBs.size();
271 /// GetInstSize - Return the size of the specified MachineInstr.
273 unsigned ARMConstantIslands::GetInstSize(MachineInstr *MI) const {
274 // Basic size info comes from the TSFlags field.
275 unsigned TSFlags = MI->getInstrDescriptor()->TSFlags;
277 switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
279 // If this machine instr is an inline asm, measure it.
280 if (MI->getOpcode() == ARM::INLINEASM)
281 return TAI->getInlineAsmLength(MI->getOperand(0).getSymbolName());
282 assert(0 && "Unknown or unset size field for instr!");
284 case ARMII::Size8Bytes: return 8; // Arm instruction x 2.
285 case ARMII::Size4Bytes: return 4; // Arm instruction.
286 case ARMII::Size2Bytes: return 2; // Thumb instruction.
287 case ARMII::SizeSpecial: {
288 switch (MI->getOpcode()) {
289 case ARM::CONSTPOOL_ENTRY:
290 // If this machine instr is a constant pool entry, its size is recorded as
292 return MI->getOperand(2).getImm();
295 case ARM::BR_JTadd: {
296 // These are jumptable branches, i.e. a branch followed by an inlined
297 // jumptable. The size is 4 + 4 * number of entries.
298 unsigned JTI = MI->getOperand(MI->getNumOperands()-2).getJumpTableIndex();
299 const MachineFunction *MF = MI->getParent()->getParent();
300 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
301 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
302 assert(JTI < JT.size());
303 return getNumJTEntries(JT, JTI) * 4 + 4;
306 // Otherwise, pseudo-instruction sizes are zero.
313 /// GetOffsetOf - Return the current offset of the specified machine instruction
314 /// from the start of the function. This offset changes as stuff is moved
315 /// around inside the function.
316 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
317 MachineBasicBlock *MBB = MI->getParent();
319 // The offset is composed of two things: the sum of the sizes of all MBB's
320 // before this instruction's block, and the offset from the start of the block
324 // Sum block sizes before MBB.
325 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
326 Offset += BBSizes[BB];
328 // Sum instructions before MI in MBB.
329 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
330 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
331 if (&*I == MI) return Offset;
332 Offset += GetInstSize(I);
336 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
338 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
339 const MachineBasicBlock *RHS) {
340 return LHS->getNumber() < RHS->getNumber();
343 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
344 /// machine function, it upsets all of the block numbers. Renumber the blocks
345 /// and update the arrays that parallel this numbering.
346 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
347 // Renumber the MBB's to keep them consequtive.
348 NewBB->getParent()->RenumberBlocks(NewBB);
350 // Insert a size into BBSizes to align it properly with the (newly
351 // renumbered) block numbers.
352 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
354 // Next, update WaterList. Specifically, we need to add NewMBB as having
355 // available water after it.
356 std::vector<MachineBasicBlock*>::iterator IP =
357 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
359 WaterList.insert(IP, NewBB);
363 /// Split the basic block containing MI into two blocks, which are joined by
364 /// an unconditional branch. Update datastructures and renumber blocks to
365 /// account for this change.
366 void ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
367 MachineBasicBlock *OrigBB = MI->getParent();
369 // Create a new MBB for the code after the OrigBB.
370 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
371 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
372 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
374 // Splice the instructions starting with MI over to NewBB.
375 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
377 // Add an unconditional branch from OrigBB to NewBB.
378 BuildMI(OrigBB, TII->get(ARM::B)).addMBB(NewBB);
381 // Update the CFG. All succs of OrigBB are now succs of NewBB.
382 while (!OrigBB->succ_empty()) {
383 MachineBasicBlock *Succ = *OrigBB->succ_begin();
384 OrigBB->removeSuccessor(Succ);
385 NewBB->addSuccessor(Succ);
387 // This pass should be run after register allocation, so there should be no
388 // PHI nodes to update.
389 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
390 && "PHI nodes should be eliminated by now!");
393 // OrigBB branches to NewBB.
394 OrigBB->addSuccessor(NewBB);
396 // Update internal data structures to account for the newly inserted MBB.
397 UpdateForInsertedWaterBlock(NewBB);
399 // Figure out how large the first NewMBB is.
400 unsigned NewBBSize = 0;
401 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
403 NewBBSize += GetInstSize(I);
405 // Set the size of NewBB in BBSizes.
406 BBSizes[NewBB->getNumber()] = NewBBSize;
408 // We removed instructions from UserMBB, subtract that off from its size.
409 // Add 4 to the block to count the unconditional branch we added to it.
410 BBSizes[OrigBB->getNumber()] -= NewBBSize-4;
413 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
414 /// is out-of-range. If so, pick it up the constant pool value and move it some
416 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
417 MachineInstr *UserMI = U.MI;
418 MachineInstr *CPEMI = U.CPEMI;
420 unsigned UserOffset = GetOffsetOf(UserMI);
421 unsigned CPEOffset = GetOffsetOf(CPEMI);
423 DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
424 << " max delta=" << U.MaxDisp
425 << " at offset " << int(UserOffset-CPEOffset) << "\t"
428 // Check to see if the CPE is already in-range.
429 if (UserOffset < CPEOffset) {
430 // User before the CPE.
431 if (CPEOffset-UserOffset <= U.MaxDisp)
434 if (UserOffset-CPEOffset <= U.MaxDisp)
439 // Solution guaranteed to work: split the user's MBB right before the user and
440 // insert a clone the CPE into the newly created water.
442 // If the user isn't at the start of its MBB, or if there is a fall-through
443 // into the user's MBB, split the MBB before the User.
444 MachineBasicBlock *UserMBB = UserMI->getParent();
445 if (&UserMBB->front() != UserMI ||
446 UserMBB == &Fn.front() || // entry MBB of function.
447 BBHasFallthrough(prior(MachineFunction::iterator(UserMBB)))) {
448 // TODO: Search for the best place to split the code. In practice, using
449 // loop nesting information to insert these guys outside of loops would be
451 SplitBlockBeforeInstr(UserMI);
453 // UserMI's BB may have changed.
454 UserMBB = UserMI->getParent();
457 // Okay, we know we can put an island before UserMBB now, do it!
458 MachineBasicBlock *NewIsland = new MachineBasicBlock();
459 Fn.getBasicBlockList().insert(UserMBB, NewIsland);
461 // Update internal data structures to account for the newly inserted MBB.
462 UpdateForInsertedWaterBlock(NewIsland);
464 // Now that we have an island to add the CPE to, clone the original CPE and
465 // add it to the island.
466 unsigned ID = NextUID++;
467 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
468 unsigned Size = CPEMI->getOperand(2).getImm();
470 // Build a new CPE for this user.
471 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
472 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
474 // Increase the size of the island block to account for the new entry.
475 BBSizes[NewIsland->getNumber()] += Size;
477 // Finally, change the CPI in the instruction operand to be ID.
478 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
479 if (UserMI->getOperand(i).isConstantPoolIndex()) {
480 UserMI->getOperand(i).setConstantPoolIndex(ID);
484 DEBUG(std::cerr << " Moved CPE to #" << ID << " CPI=" << CPI << "\t"