0bbacd02f0d7c9fa6abad86796fc5608275183e7
[oota-llvm.git] / lib / CodeGen / MachineFunction.cpp
1 //===-- MachineFunction.cpp -----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect native machine code information for a function.  This allows
11 // target-specific information about the generated code to be stored with each
12 // function.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/DataLayout.h"
29 #include "llvm/DebugInfo.h"
30 #include "llvm/Function.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/GraphWriter.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace llvm;
40
41 //===----------------------------------------------------------------------===//
42 // MachineFunction implementation
43 //===----------------------------------------------------------------------===//
44
45 // Out of line virtual method.
46 MachineFunctionInfo::~MachineFunctionInfo() {}
47
48 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
49   MBB->getParent()->DeleteMachineBasicBlock(MBB);
50 }
51
52 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
53                                  unsigned FunctionNum, MachineModuleInfo &mmi,
54                                  GCModuleInfo* gmi)
55   : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
56   if (TM.getRegisterInfo())
57     RegInfo = new (Allocator) MachineRegisterInfo(*TM.getRegisterInfo());
58   else
59     RegInfo = 0;
60   MFInfo = 0;
61   FrameInfo = new (Allocator) MachineFrameInfo(*TM.getFrameLowering(),
62                                                TM.Options.RealignStack);
63   if (Fn->getFnAttributes().hasAttribute(Attribute::StackAlignment))
64     FrameInfo->ensureMaxAlignment(Fn->getAttributes().
65                                   getFnAttributes().getStackAlignment());
66   ConstantPool = new (Allocator) MachineConstantPool(TM.getDataLayout());
67   Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
68   // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
69   if (!Fn->getFnAttributes().hasAttribute(Attribute::OptimizeForSize))
70     Alignment = std::max(Alignment,
71                          TM.getTargetLowering()->getPrefFunctionAlignment());
72   FunctionNumber = FunctionNum;
73   JumpTableInfo = 0;
74 }
75
76 MachineFunction::~MachineFunction() {
77   BasicBlocks.clear();
78   InstructionRecycler.clear(Allocator);
79   BasicBlockRecycler.clear(Allocator);
80   if (RegInfo) {
81     RegInfo->~MachineRegisterInfo();
82     Allocator.Deallocate(RegInfo);
83   }
84   if (MFInfo) {
85     MFInfo->~MachineFunctionInfo();
86     Allocator.Deallocate(MFInfo);
87   }
88
89   FrameInfo->~MachineFrameInfo();
90   Allocator.Deallocate(FrameInfo);
91
92   ConstantPool->~MachineConstantPool();
93   Allocator.Deallocate(ConstantPool);
94
95   if (JumpTableInfo) {
96     JumpTableInfo->~MachineJumpTableInfo();
97     Allocator.Deallocate(JumpTableInfo);
98   }
99 }
100
101 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
102 /// does already exist, allocate one.
103 MachineJumpTableInfo *MachineFunction::
104 getOrCreateJumpTableInfo(unsigned EntryKind) {
105   if (JumpTableInfo) return JumpTableInfo;
106
107   JumpTableInfo = new (Allocator)
108     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
109   return JumpTableInfo;
110 }
111
112 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
113 /// recomputes them.  This guarantees that the MBB numbers are sequential,
114 /// dense, and match the ordering of the blocks within the function.  If a
115 /// specific MachineBasicBlock is specified, only that block and those after
116 /// it are renumbered.
117 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
118   if (empty()) { MBBNumbering.clear(); return; }
119   MachineFunction::iterator MBBI, E = end();
120   if (MBB == 0)
121     MBBI = begin();
122   else
123     MBBI = MBB;
124
125   // Figure out the block number this should have.
126   unsigned BlockNo = 0;
127   if (MBBI != begin())
128     BlockNo = prior(MBBI)->getNumber()+1;
129
130   for (; MBBI != E; ++MBBI, ++BlockNo) {
131     if (MBBI->getNumber() != (int)BlockNo) {
132       // Remove use of the old number.
133       if (MBBI->getNumber() != -1) {
134         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
135                "MBB number mismatch!");
136         MBBNumbering[MBBI->getNumber()] = 0;
137       }
138
139       // If BlockNo is already taken, set that block's number to -1.
140       if (MBBNumbering[BlockNo])
141         MBBNumbering[BlockNo]->setNumber(-1);
142
143       MBBNumbering[BlockNo] = MBBI;
144       MBBI->setNumber(BlockNo);
145     }
146   }
147
148   // Okay, all the blocks are renumbered.  If we have compactified the block
149   // numbering, shrink MBBNumbering now.
150   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
151   MBBNumbering.resize(BlockNo);
152 }
153
154 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
155 /// of `new MachineInstr'.
156 ///
157 MachineInstr *
158 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
159                                     DebugLoc DL, bool NoImp) {
160   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
161     MachineInstr(*this, MCID, DL, NoImp);
162 }
163
164 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
165 /// 'Orig' instruction, identical in all ways except the instruction
166 /// has no parent, prev, or next.
167 ///
168 MachineInstr *
169 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
170   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
171              MachineInstr(*this, *Orig);
172 }
173
174 /// DeleteMachineInstr - Delete the given MachineInstr.
175 ///
176 void
177 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
178   MI->~MachineInstr();
179   InstructionRecycler.Deallocate(Allocator, MI);
180 }
181
182 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
183 /// instead of `new MachineBasicBlock'.
184 ///
185 MachineBasicBlock *
186 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
187   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
188              MachineBasicBlock(*this, bb);
189 }
190
191 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
192 ///
193 void
194 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
195   assert(MBB->getParent() == this && "MBB parent mismatch!");
196   MBB->~MachineBasicBlock();
197   BasicBlockRecycler.Deallocate(Allocator, MBB);
198 }
199
200 MachineMemOperand *
201 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
202                                       uint64_t s, unsigned base_alignment,
203                                       const MDNode *TBAAInfo,
204                                       const MDNode *Ranges) {
205   return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
206                                            TBAAInfo, Ranges);
207 }
208
209 MachineMemOperand *
210 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
211                                       int64_t Offset, uint64_t Size) {
212   return new (Allocator)
213              MachineMemOperand(MachinePointerInfo(MMO->getValue(),
214                                                   MMO->getOffset()+Offset),
215                                MMO->getFlags(), Size,
216                                MMO->getBaseAlignment(), 0);
217 }
218
219 MachineInstr::mmo_iterator
220 MachineFunction::allocateMemRefsArray(unsigned long Num) {
221   return Allocator.Allocate<MachineMemOperand *>(Num);
222 }
223
224 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
225 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
226                                     MachineInstr::mmo_iterator End) {
227   // Count the number of load mem refs.
228   unsigned Num = 0;
229   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
230     if ((*I)->isLoad())
231       ++Num;
232
233   // Allocate a new array and populate it with the load information.
234   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
235   unsigned Index = 0;
236   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
237     if ((*I)->isLoad()) {
238       if (!(*I)->isStore())
239         // Reuse the MMO.
240         Result[Index] = *I;
241       else {
242         // Clone the MMO and unset the store flag.
243         MachineMemOperand *JustLoad =
244           getMachineMemOperand((*I)->getPointerInfo(),
245                                (*I)->getFlags() & ~MachineMemOperand::MOStore,
246                                (*I)->getSize(), (*I)->getBaseAlignment(),
247                                (*I)->getTBAAInfo());
248         Result[Index] = JustLoad;
249       }
250       ++Index;
251     }
252   }
253   return std::make_pair(Result, Result + Num);
254 }
255
256 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
257 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
258                                      MachineInstr::mmo_iterator End) {
259   // Count the number of load mem refs.
260   unsigned Num = 0;
261   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
262     if ((*I)->isStore())
263       ++Num;
264
265   // Allocate a new array and populate it with the store information.
266   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
267   unsigned Index = 0;
268   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
269     if ((*I)->isStore()) {
270       if (!(*I)->isLoad())
271         // Reuse the MMO.
272         Result[Index] = *I;
273       else {
274         // Clone the MMO and unset the load flag.
275         MachineMemOperand *JustStore =
276           getMachineMemOperand((*I)->getPointerInfo(),
277                                (*I)->getFlags() & ~MachineMemOperand::MOLoad,
278                                (*I)->getSize(), (*I)->getBaseAlignment(),
279                                (*I)->getTBAAInfo());
280         Result[Index] = JustStore;
281       }
282       ++Index;
283     }
284   }
285   return std::make_pair(Result, Result + Num);
286 }
287
288 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
289 void MachineFunction::dump() const {
290   print(dbgs());
291 }
292 #endif
293
294 StringRef MachineFunction::getName() const {
295   assert(getFunction() && "No function!");
296   return getFunction()->getName();
297 }
298
299 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
300   OS << "# Machine code for function " << getName() << ": ";
301   if (RegInfo) {
302     OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
303     if (!RegInfo->tracksLiveness())
304       OS << ", not tracking liveness";
305   }
306   OS << '\n';
307
308   // Print Frame Information
309   FrameInfo->print(*this, OS);
310
311   // Print JumpTable Information
312   if (JumpTableInfo)
313     JumpTableInfo->print(OS);
314
315   // Print Constant Pool
316   ConstantPool->print(OS);
317
318   const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
319
320   if (RegInfo && !RegInfo->livein_empty()) {
321     OS << "Function Live Ins: ";
322     for (MachineRegisterInfo::livein_iterator
323          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
324       OS << PrintReg(I->first, TRI);
325       if (I->second)
326         OS << " in " << PrintReg(I->second, TRI);
327       if (llvm::next(I) != E)
328         OS << ", ";
329     }
330     OS << '\n';
331   }
332   if (RegInfo && !RegInfo->liveout_empty()) {
333     OS << "Function Live Outs:";
334     for (MachineRegisterInfo::liveout_iterator
335          I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
336       OS << ' ' << PrintReg(*I, TRI);
337     OS << '\n';
338   }
339
340   for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
341     OS << '\n';
342     BB->print(OS, Indexes);
343   }
344
345   OS << "\n# End machine code for function " << getName() << ".\n\n";
346 }
347
348 namespace llvm {
349   template<>
350   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
351
352   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
353
354     static std::string getGraphName(const MachineFunction *F) {
355       return "CFG for '" + F->getName().str() + "' function";
356     }
357
358     std::string getNodeLabel(const MachineBasicBlock *Node,
359                              const MachineFunction *Graph) {
360       std::string OutStr;
361       {
362         raw_string_ostream OSS(OutStr);
363
364         if (isSimple()) {
365           OSS << "BB#" << Node->getNumber();
366           if (const BasicBlock *BB = Node->getBasicBlock())
367             OSS << ": " << BB->getName();
368         } else
369           Node->print(OSS);
370       }
371
372       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
373
374       // Process string output to make it nicer...
375       for (unsigned i = 0; i != OutStr.length(); ++i)
376         if (OutStr[i] == '\n') {                            // Left justify
377           OutStr[i] = '\\';
378           OutStr.insert(OutStr.begin()+i+1, 'l');
379         }
380       return OutStr;
381     }
382   };
383 }
384
385 void MachineFunction::viewCFG() const
386 {
387 #ifndef NDEBUG
388   ViewGraph(this, "mf" + getName());
389 #else
390   errs() << "MachineFunction::viewCFG is only available in debug builds on "
391          << "systems with Graphviz or gv!\n";
392 #endif // NDEBUG
393 }
394
395 void MachineFunction::viewCFGOnly() const
396 {
397 #ifndef NDEBUG
398   ViewGraph(this, "mf" + getName(), true);
399 #else
400   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
401          << "systems with Graphviz or gv!\n";
402 #endif // NDEBUG
403 }
404
405 /// addLiveIn - Add the specified physical register as a live-in value and
406 /// create a corresponding virtual register for it.
407 unsigned MachineFunction::addLiveIn(unsigned PReg,
408                                     const TargetRegisterClass *RC) {
409   MachineRegisterInfo &MRI = getRegInfo();
410   unsigned VReg = MRI.getLiveInVirtReg(PReg);
411   if (VReg) {
412     assert(MRI.getRegClass(VReg) == RC && "Register class mismatch!");
413     return VReg;
414   }
415   VReg = MRI.createVirtualRegister(RC);
416   MRI.addLiveIn(PReg, VReg);
417   return VReg;
418 }
419
420 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
421 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
422 /// normal 'L' label is returned.
423 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 
424                                         bool isLinkerPrivate) const {
425   assert(JumpTableInfo && "No jump tables");
426   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
427   const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
428
429   const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
430                                          MAI.getPrivateGlobalPrefix();
431   SmallString<60> Name;
432   raw_svector_ostream(Name)
433     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
434   return Ctx.GetOrCreateSymbol(Name.str());
435 }
436
437 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
438 /// base.
439 MCSymbol *MachineFunction::getPICBaseSymbol() const {
440   const MCAsmInfo &MAI = *Target.getMCAsmInfo();
441   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
442                                Twine(getFunctionNumber())+"$pb");
443 }
444
445 //===----------------------------------------------------------------------===//
446 //  MachineFrameInfo implementation
447 //===----------------------------------------------------------------------===//
448
449 /// ensureMaxAlignment - Make sure the function is at least Align bytes
450 /// aligned.
451 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
452   if (!TFI.isStackRealignable() || !RealignOption)
453     assert(Align <= TFI.getStackAlignment() &&
454            "For targets without stack realignment, Align is out of limit!");
455   if (MaxAlignment < Align) MaxAlignment = Align;
456 }
457
458 /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
459 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
460                                            unsigned StackAlign) {
461   if (!ShouldClamp || Align <= StackAlign)
462     return Align;
463   DEBUG(dbgs() << "Warning: requested alignment " << Align
464                << " exceeds the stack alignment " << StackAlign
465                << " when stack realignment is off" << '\n');
466   return StackAlign;
467 }
468
469 /// CreateStackObject - Create a new statically sized stack object, returning
470 /// a nonnegative identifier to represent it.
471 ///
472 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
473                       bool isSS, bool MayNeedSP, const AllocaInst *Alloca) {
474   assert(Size != 0 && "Cannot allocate zero size stack objects!");
475   Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
476                                   Alignment, TFI.getStackAlignment());
477   Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
478                                 Alloca));
479   int Index = (int)Objects.size() - NumFixedObjects - 1;
480   assert(Index >= 0 && "Bad frame index!");
481   ensureMaxAlignment(Alignment);
482   return Index;
483 }
484
485 /// CreateSpillStackObject - Create a new statically sized stack object that
486 /// represents a spill slot, returning a nonnegative identifier to represent
487 /// it.
488 ///
489 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
490                                              unsigned Alignment) {
491   Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
492                                   Alignment, TFI.getStackAlignment()); 
493   CreateStackObject(Size, Alignment, true, false);
494   int Index = (int)Objects.size() - NumFixedObjects - 1;
495   ensureMaxAlignment(Alignment);
496   return Index;
497 }
498
499 /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
500 /// variable sized object has been created.  This must be created whenever a
501 /// variable sized object is created, whether or not the index returned is
502 /// actually used.
503 ///
504 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment) {
505   HasVarSizedObjects = true;
506   Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
507                                   Alignment, TFI.getStackAlignment()); 
508   Objects.push_back(StackObject(0, Alignment, 0, false, false, true, 0));
509   ensureMaxAlignment(Alignment);
510   return (int)Objects.size()-NumFixedObjects-1;
511 }
512
513 /// CreateFixedObject - Create a new object at a fixed location on the stack.
514 /// All fixed objects should be created before other objects are created for
515 /// efficiency. By default, fixed objects are immutable. This returns an
516 /// index with a negative value.
517 ///
518 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
519                                         bool Immutable) {
520   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
521   // The alignment of the frame index can be determined from its offset from
522   // the incoming frame position.  If the frame object is at offset 32 and
523   // the stack is guaranteed to be 16-byte aligned, then we know that the
524   // object is 16-byte aligned.
525   unsigned StackAlign = TFI.getStackAlignment();
526   unsigned Align = MinAlign(SPOffset, StackAlign);
527   Align = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
528                               Align, TFI.getStackAlignment()); 
529   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
530                                               /*isSS*/   false,
531                                               /*NeedSP*/ false,
532                                               /*Alloca*/ 0));
533   return -++NumFixedObjects;
534 }
535
536
537 BitVector
538 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
539   assert(MBB && "MBB must be valid");
540   const MachineFunction *MF = MBB->getParent();
541   assert(MF && "MBB must be part of a MachineFunction");
542   const TargetMachine &TM = MF->getTarget();
543   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
544   BitVector BV(TRI->getNumRegs());
545
546   // Before CSI is calculated, no registers are considered pristine. They can be
547   // freely used and PEI will make sure they are saved.
548   if (!isCalleeSavedInfoValid())
549     return BV;
550
551   for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
552     BV.set(*CSR);
553
554   // The entry MBB always has all CSRs pristine.
555   if (MBB == &MF->front())
556     return BV;
557
558   // On other MBBs the saved CSRs are not pristine.
559   const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
560   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
561          E = CSI.end(); I != E; ++I)
562     BV.reset(I->getReg());
563
564   return BV;
565 }
566
567
568 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
569   if (Objects.empty()) return;
570
571   const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
572   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
573
574   OS << "Frame Objects:\n";
575
576   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
577     const StackObject &SO = Objects[i];
578     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
579     if (SO.Size == ~0ULL) {
580       OS << "dead\n";
581       continue;
582     }
583     if (SO.Size == 0)
584       OS << "variable sized";
585     else
586       OS << "size=" << SO.Size;
587     OS << ", align=" << SO.Alignment;
588
589     if (i < NumFixedObjects)
590       OS << ", fixed";
591     if (i < NumFixedObjects || SO.SPOffset != -1) {
592       int64_t Off = SO.SPOffset - ValOffset;
593       OS << ", at location [SP";
594       if (Off > 0)
595         OS << "+" << Off;
596       else if (Off < 0)
597         OS << Off;
598       OS << "]";
599     }
600     OS << "\n";
601   }
602 }
603
604 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
605 void MachineFrameInfo::dump(const MachineFunction &MF) const {
606   print(MF, dbgs());
607 }
608 #endif
609
610 //===----------------------------------------------------------------------===//
611 //  MachineJumpTableInfo implementation
612 //===----------------------------------------------------------------------===//
613
614 /// getEntrySize - Return the size of each entry in the jump table.
615 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
616   // The size of a jump table entry is 4 bytes unless the entry is just the
617   // address of a block, in which case it is the pointer size.
618   switch (getEntryKind()) {
619   case MachineJumpTableInfo::EK_BlockAddress:
620     return TD.getPointerSize();
621   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
622     return 8;
623   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
624   case MachineJumpTableInfo::EK_LabelDifference32:
625   case MachineJumpTableInfo::EK_Custom32:
626     return 4;
627   case MachineJumpTableInfo::EK_Inline:
628     return 0;
629   }
630   llvm_unreachable("Unknown jump table encoding!");
631 }
632
633 /// getEntryAlignment - Return the alignment of each entry in the jump table.
634 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
635   // The alignment of a jump table entry is the alignment of int32 unless the
636   // entry is just the address of a block, in which case it is the pointer
637   // alignment.
638   switch (getEntryKind()) {
639   case MachineJumpTableInfo::EK_BlockAddress:
640     return TD.getPointerABIAlignment();
641   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
642     return TD.getABIIntegerTypeAlignment(64);
643   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
644   case MachineJumpTableInfo::EK_LabelDifference32:
645   case MachineJumpTableInfo::EK_Custom32:
646     return TD.getABIIntegerTypeAlignment(32);
647   case MachineJumpTableInfo::EK_Inline:
648     return 1;
649   }
650   llvm_unreachable("Unknown jump table encoding!");
651 }
652
653 /// createJumpTableIndex - Create a new jump table entry in the jump table info.
654 ///
655 unsigned MachineJumpTableInfo::createJumpTableIndex(
656                                const std::vector<MachineBasicBlock*> &DestBBs) {
657   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
658   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
659   return JumpTables.size()-1;
660 }
661
662 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
663 /// the jump tables to branch to New instead.
664 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
665                                                   MachineBasicBlock *New) {
666   assert(Old != New && "Not making a change?");
667   bool MadeChange = false;
668   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
669     ReplaceMBBInJumpTable(i, Old, New);
670   return MadeChange;
671 }
672
673 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
674 /// the jump table to branch to New instead.
675 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
676                                                  MachineBasicBlock *Old,
677                                                  MachineBasicBlock *New) {
678   assert(Old != New && "Not making a change?");
679   bool MadeChange = false;
680   MachineJumpTableEntry &JTE = JumpTables[Idx];
681   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
682     if (JTE.MBBs[j] == Old) {
683       JTE.MBBs[j] = New;
684       MadeChange = true;
685     }
686   return MadeChange;
687 }
688
689 void MachineJumpTableInfo::print(raw_ostream &OS) const {
690   if (JumpTables.empty()) return;
691
692   OS << "Jump Tables:\n";
693
694   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
695     OS << "  jt#" << i << ": ";
696     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
697       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
698   }
699
700   OS << '\n';
701 }
702
703 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
704 void MachineJumpTableInfo::dump() const { print(dbgs()); }
705 #endif
706
707
708 //===----------------------------------------------------------------------===//
709 //  MachineConstantPool implementation
710 //===----------------------------------------------------------------------===//
711
712 void MachineConstantPoolValue::anchor() { }
713
714 Type *MachineConstantPoolEntry::getType() const {
715   if (isMachineConstantPoolEntry())
716     return Val.MachineCPVal->getType();
717   return Val.ConstVal->getType();
718 }
719
720
721 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
722   if (isMachineConstantPoolEntry())
723     return Val.MachineCPVal->getRelocationInfo();
724   return Val.ConstVal->getRelocationInfo();
725 }
726
727 MachineConstantPool::~MachineConstantPool() {
728   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
729     if (Constants[i].isMachineConstantPoolEntry())
730       delete Constants[i].Val.MachineCPVal;
731   for (DenseSet<MachineConstantPoolValue*>::iterator I =
732        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
733        I != E; ++I)
734     delete *I;
735 }
736
737 /// CanShareConstantPoolEntry - Test whether the given two constants
738 /// can be allocated the same constant pool entry.
739 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
740                                       const DataLayout *TD) {
741   // Handle the trivial case quickly.
742   if (A == B) return true;
743
744   // If they have the same type but weren't the same constant, quickly
745   // reject them.
746   if (A->getType() == B->getType()) return false;
747
748   // We can't handle structs or arrays.
749   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
750       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
751     return false;
752   
753   // For now, only support constants with the same size.
754   uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
755   if (StoreSize != TD->getTypeStoreSize(B->getType()) || 
756       StoreSize > 128)
757     return false;
758
759   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
760
761   // Try constant folding a bitcast of both instructions to an integer.  If we
762   // get two identical ConstantInt's, then we are good to share them.  We use
763   // the constant folding APIs to do this so that we get the benefit of
764   // DataLayout.
765   if (isa<PointerType>(A->getType()))
766     A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
767                                  const_cast<Constant*>(A), TD);
768   else if (A->getType() != IntTy)
769     A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
770                                  const_cast<Constant*>(A), TD);
771   if (isa<PointerType>(B->getType()))
772     B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
773                                  const_cast<Constant*>(B), TD);
774   else if (B->getType() != IntTy)
775     B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
776                                  const_cast<Constant*>(B), TD);
777
778   return A == B;
779 }
780
781 /// getConstantPoolIndex - Create a new entry in the constant pool or return
782 /// an existing one.  User must specify the log2 of the minimum required
783 /// alignment for the object.
784 ///
785 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 
786                                                    unsigned Alignment) {
787   assert(Alignment && "Alignment must be specified!");
788   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
789
790   // Check to see if we already have this constant.
791   //
792   // FIXME, this could be made much more efficient for large constant pools.
793   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
794     if (!Constants[i].isMachineConstantPoolEntry() &&
795         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
796       if ((unsigned)Constants[i].getAlignment() < Alignment)
797         Constants[i].Alignment = Alignment;
798       return i;
799     }
800
801   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
802   return Constants.size()-1;
803 }
804
805 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
806                                                    unsigned Alignment) {
807   assert(Alignment && "Alignment must be specified!");
808   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
809
810   // Check to see if we already have this constant.
811   //
812   // FIXME, this could be made much more efficient for large constant pools.
813   int Idx = V->getExistingMachineCPValue(this, Alignment);
814   if (Idx != -1) {
815     MachineCPVsSharingEntries.insert(V);
816     return (unsigned)Idx;
817   }
818
819   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
820   return Constants.size()-1;
821 }
822
823 void MachineConstantPool::print(raw_ostream &OS) const {
824   if (Constants.empty()) return;
825
826   OS << "Constant Pool:\n";
827   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
828     OS << "  cp#" << i << ": ";
829     if (Constants[i].isMachineConstantPoolEntry())
830       Constants[i].Val.MachineCPVal->print(OS);
831     else
832       OS << *(const Value*)Constants[i].Val.ConstVal;
833     OS << ", align=" << Constants[i].getAlignment();
834     OS << "\n";
835   }
836 }
837
838 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
839 void MachineConstantPool::dump() const { print(dbgs()); }
840 #endif