183bde88243e9700fc9fd8ea5b7c4acacc0cb7c9
[oota-llvm.git] / lib / Target / ARM / ARMConstantIslandPass.cpp
1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function.  This is required due to the
12 // limited pc-relative displacements that ARM has.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "arm-cp-islands"
17 #include "ARM.h"
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"
30 #include <iostream>
31 using namespace llvm;
32
33 STATISTIC(NumSplit, "Number of uncond branches inserted");
34
35 namespace {
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.
41   ///
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.
49     unsigned NextUID;
50     
51     /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
52     /// by MBB Number.
53     std::vector<unsigned> BBSizes;
54     
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;
59     
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.
63     struct CPUser {
64       MachineInstr *MI;
65       MachineInstr *CPEMI;
66       unsigned MaxDisp;
67       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
68         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
69     };
70     
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;
74     
75     const TargetInstrInfo *TII;
76     const TargetAsmInfo   *TAI;
77   public:
78     virtual bool runOnMachineFunction(MachineFunction &Fn);
79
80     virtual const char *getPassName() const {
81       return "ARM constant island placement pass";
82     }
83     
84   private:
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);
92
93     unsigned GetInstSize(MachineInstr *MI) const;
94     unsigned GetOffsetOf(MachineInstr *MI) const;
95   };
96 }
97
98 /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
99 /// optimization pass.
100 FunctionPass *llvm::createARMConstantIslandPass() {
101   return new ARMConstantIslands();
102 }
103
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;
108   
109   TII = Fn.getTarget().getInstrInfo();
110   TAI = Fn.getTarget().getTargetAsmInfo();
111   
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.
114   Fn.RenumberBlocks();
115
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);
120   
121   /// The next UID to take is the first unused one.
122   NextUID = CPEMIs.size();
123   
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);
128   CPEMIs.clear();
129   
130   // Iteratively place constant pool entries until there is no change.
131   bool MadeChange;
132   do {
133     MadeChange = false;
134     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
135       MadeChange |= HandleConstantPoolUser(Fn, CPUsers[i]);
136   } while (MadeChange);
137   
138   BBSizes.clear();
139   WaterList.clear();
140   CPUsers.clear();
141     
142   return true;
143 }
144
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);
152   
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();
157   
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
163     // aligned.
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 #"
170                     << i << "\n");
171   }
172 }
173
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.
180     return false;
181   
182   MachineBasicBlock *NextBB = next(MBBI);
183   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
184        E = MBB->succ_end(); I != E; ++I)
185     if (*I == NextBB)
186       return true;
187   
188   return false;
189 }
190
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();
197        MBBI != E; ++MBBI) {
198     MachineBasicBlock &MBB = *MBBI;
199     
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);
204     
205     unsigned MBBSize = 0;
206     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
207          I != E; ++I) {
208       // Add instruction size to MBBSize.
209       MBBSize += GetInstSize(I);
210
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;
217           
218           // Basic size info comes from the TSFlags field.
219           unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
220           switch (TSFlags & ARMII::AddrModeMask) {
221           default: 
222             // Constant pool entries can reach anything.
223             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
224               continue;
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.
228             break;
229           case ARMII::AddrMode2:
230             MaxOffs = 1 << 12;   // +-offset_12
231             break;
232           case ARMII::AddrMode3:
233             MaxOffs = 1 << 8;   // +-offset_8
234             break;
235             // addrmode4 has no immediate offset.
236           case ARMII::AddrMode5:
237             MaxOffs = 1 << (8+2);   // +-(offset_8*4)
238             break;
239           case ARMII::AddrModeT1:
240             MaxOffs = 1 << 5;
241             break;
242           case ARMII::AddrModeT2:
243             MaxOffs = 1 << (5+1);
244             break;
245           case ARMII::AddrModeT4:
246             MaxOffs = 1 << (5+2);
247             break;
248           }
249           
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));
253           
254           // Instructions can only use one CP entry, don't bother scanning the
255           // rest of the operands.
256           break;
257         }
258     }
259     BBSizes.push_back(MBBSize);
260   }
261 }
262
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,
267                                 unsigned JTI) {
268   return JT[JTI].MBBs.size();
269 }
270
271 /// GetInstSize - Return the size of the specified MachineInstr.
272 ///
273 unsigned ARMConstantIslands::GetInstSize(MachineInstr *MI) const {
274   // Basic size info comes from the TSFlags field.
275   unsigned TSFlags = MI->getInstrDescriptor()->TSFlags;
276   
277   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
278   default:
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!");
283     break;
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
291       // operand #2.
292       return MI->getOperand(2).getImm();
293     case ARM::BR_JTr:
294     case ARM::BR_JTm:
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;
304     }
305     default:
306       // Otherwise, pseudo-instruction sizes are zero.
307       return 0;
308     }
309   }
310   }
311 }
312
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();
318   
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
321   // it is in.
322   unsigned Offset = 0;
323   
324   // Sum block sizes before MBB.
325   for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
326     Offset += BBSizes[BB];
327
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);
333   }
334 }
335
336 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
337 /// ID.
338 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
339                               const MachineBasicBlock *RHS) {
340   return LHS->getNumber() < RHS->getNumber();
341 }
342
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);
349   
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);
353   
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,
358                      CompareMBBNumbers);
359   WaterList.insert(IP, NewBB);
360 }
361
362
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();
368
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);
373   
374   // Splice the instructions starting with MI over to NewBB.
375   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
376   
377   // Add an unconditional branch from OrigBB to NewBB.
378   BuildMI(OrigBB, TII->get(ARM::B)).addMBB(NewBB);
379   NumSplit++;
380   
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);
386     
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!");
391   }
392   
393   // OrigBB branches to NewBB.
394   OrigBB->addSuccessor(NewBB);
395   
396   // Update internal data structures to account for the newly inserted MBB.
397   UpdateForInsertedWaterBlock(NewBB);
398   
399   // Figure out how large the first NewMBB is.
400   unsigned NewBBSize = 0;
401   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
402        I != E; ++I)
403     NewBBSize += GetInstSize(I);
404   
405   // Set the size of NewBB in BBSizes.
406   BBSizes[NewBB->getNumber()] = NewBBSize;
407   
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;
411 }
412
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
415 /// place in-range.
416 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
417   MachineInstr *UserMI = U.MI;
418   MachineInstr *CPEMI  = U.CPEMI;
419
420   unsigned UserOffset = GetOffsetOf(UserMI);
421   unsigned CPEOffset  = GetOffsetOf(CPEMI);
422   
423   DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
424                   << " max delta=" << U.MaxDisp
425                   << " at offset " << int(UserOffset-CPEOffset) << "\t"
426                   << *UserMI);
427
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)
432       return false;
433   } else {
434     if (UserOffset-CPEOffset <= U.MaxDisp)
435       return false;
436   }
437   
438  
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.
441   
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
450     // sufficient.    
451     SplitBlockBeforeInstr(UserMI);
452     
453     // UserMI's BB may have changed.
454     UserMBB = UserMI->getParent();
455   }
456   
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);
460
461   // Update internal data structures to account for the newly inserted MBB.
462   UpdateForInsertedWaterBlock(NewIsland);
463
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();
469   
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);
473   
474   // Increase the size of the island block to account for the new entry.
475   BBSizes[NewIsland->getNumber()] += Size;
476   
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);
481       break;
482     }
483       
484   DEBUG(std::cerr << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t"
485                   << *UserMI);
486   
487       
488   return true;
489 }
490