MachineFunction.cpp revision ae73dc1448d25b02cabc7c64c86c64371453dda8
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/DerivedTypes.h"
17#include "llvm/CodeGen/MachineConstantPool.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/MachineJumpTableInfo.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Target/TargetFrameInfo.h"
27#include "llvm/Function.h"
28#include "llvm/Instructions.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/GraphWriter.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/Config/config.h"
34#include <fstream>
35#include <sstream>
36using namespace llvm;
37
38static AnnotationID MF_AID(
39  AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
40
41// Out of line virtual function to home classes.
42void MachineFunctionPass::virtfn() {}
43
44namespace {
45  struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
46    static char ID;
47
48    std::ostream *OS;
49    const std::string Banner;
50
51    Printer (std::ostream *os, const std::string &banner)
52      : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
53
54    const char *getPassName() const { return "MachineFunction Printer"; }
55
56    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57      AU.setPreservesAll();
58    }
59
60    bool runOnMachineFunction(MachineFunction &MF) {
61      (*OS) << Banner;
62      MF.print (*OS);
63      return false;
64    }
65  };
66  char Printer::ID = 0;
67}
68
69/// Returns a newly-created MachineFunction Printer pass. The default output
70/// stream is std::cerr; the default banner is empty.
71///
72FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
73                                                     const std::string &Banner){
74  return new Printer(OS, Banner);
75}
76
77namespace {
78  struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
79    static char ID;
80    Deleter() : MachineFunctionPass(&ID) {}
81
82    const char *getPassName() const { return "Machine Code Deleter"; }
83
84    bool runOnMachineFunction(MachineFunction &MF) {
85      // Delete the annotation from the function now.
86      MachineFunction::destruct(MF.getFunction());
87      return true;
88    }
89  };
90  char Deleter::ID = 0;
91}
92
93/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
94/// the current function, which should happen after the function has been
95/// emitted to a .s file or to memory.
96FunctionPass *llvm::createMachineCodeDeleter() {
97  return new Deleter();
98}
99
100
101
102//===---------------------------------------------------------------------===//
103// MachineFunction implementation
104//===---------------------------------------------------------------------===//
105
106void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
107  MBB->getParent()->DeleteMachineBasicBlock(MBB);
108}
109
110MachineFunction::MachineFunction(const Function *F,
111                                 const TargetMachine &TM)
112  : Annotation(MF_AID), Fn(F), Target(TM) {
113  RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
114                MachineRegisterInfo(*TM.getRegisterInfo());
115  MFInfo = 0;
116  FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
117                  MachineFrameInfo(*TM.getFrameInfo());
118  ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
119                     MachineConstantPool(TM.getTargetData());
120
121  // Set up jump table.
122  const TargetData &TD = *TM.getTargetData();
123  bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
124  unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
125  unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
126                             : TD.getPointerABIAlignment();
127  JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
128                      MachineJumpTableInfo(EntrySize, Alignment);
129}
130
131MachineFunction::~MachineFunction() {
132  BasicBlocks.clear();
133  InstructionRecycler.clear(Allocator);
134  BasicBlockRecycler.clear(Allocator);
135  RegInfo->~MachineRegisterInfo();        Allocator.Deallocate(RegInfo);
136  if (MFInfo) {
137    MFInfo->~MachineFunctionInfo();       Allocator.Deallocate(MFInfo);
138  }
139  FrameInfo->~MachineFrameInfo();         Allocator.Deallocate(FrameInfo);
140  ConstantPool->~MachineConstantPool();   Allocator.Deallocate(ConstantPool);
141  JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
142}
143
144
145/// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
146/// recomputes them.  This guarantees that the MBB numbers are sequential,
147/// dense, and match the ordering of the blocks within the function.  If a
148/// specific MachineBasicBlock is specified, only that block and those after
149/// it are renumbered.
150void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
151  if (empty()) { MBBNumbering.clear(); return; }
152  MachineFunction::iterator MBBI, E = end();
153  if (MBB == 0)
154    MBBI = begin();
155  else
156    MBBI = MBB;
157
158  // Figure out the block number this should have.
159  unsigned BlockNo = 0;
160  if (MBBI != begin())
161    BlockNo = prior(MBBI)->getNumber()+1;
162
163  for (; MBBI != E; ++MBBI, ++BlockNo) {
164    if (MBBI->getNumber() != (int)BlockNo) {
165      // Remove use of the old number.
166      if (MBBI->getNumber() != -1) {
167        assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
168               "MBB number mismatch!");
169        MBBNumbering[MBBI->getNumber()] = 0;
170      }
171
172      // If BlockNo is already taken, set that block's number to -1.
173      if (MBBNumbering[BlockNo])
174        MBBNumbering[BlockNo]->setNumber(-1);
175
176      MBBNumbering[BlockNo] = MBBI;
177      MBBI->setNumber(BlockNo);
178    }
179  }
180
181  // Okay, all the blocks are renumbered.  If we have compactified the block
182  // numbering, shrink MBBNumbering now.
183  assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
184  MBBNumbering.resize(BlockNo);
185}
186
187/// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
188/// of `new MachineInstr'.
189///
190MachineInstr *
191MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID, bool NoImp) {
192  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
193             MachineInstr(TID, NoImp);
194}
195
196/// CloneMachineInstr - Create a new MachineInstr which is a copy of the
197/// 'Orig' instruction, identical in all ways except the the instruction
198/// has no parent, prev, or next.
199///
200MachineInstr *
201MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
202  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
203             MachineInstr(*this, *Orig);
204}
205
206/// DeleteMachineInstr - Delete the given MachineInstr.
207///
208void
209MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
210  // Clear the instructions memoperands. This must be done manually because
211  // the instruction's parent pointer is now null, so it can't properly
212  // deallocate them on its own.
213  MI->clearMemOperands(*this);
214
215  MI->~MachineInstr();
216  InstructionRecycler.Deallocate(Allocator, MI);
217}
218
219/// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
220/// instead of `new MachineBasicBlock'.
221///
222MachineBasicBlock *
223MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
224  return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
225             MachineBasicBlock(*this, bb);
226}
227
228/// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
229///
230void
231MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
232  assert(MBB->getParent() == this && "MBB parent mismatch!");
233  MBB->~MachineBasicBlock();
234  BasicBlockRecycler.Deallocate(Allocator, MBB);
235}
236
237void MachineFunction::dump() const {
238  print(*cerr.stream());
239}
240
241void MachineFunction::print(std::ostream &OS) const {
242  OS << "# Machine code for " << Fn->getName () << "():\n";
243
244  // Print Frame Information
245  FrameInfo->print(*this, OS);
246
247  // Print JumpTable Information
248  JumpTableInfo->print(OS);
249
250  // Print Constant Pool
251  {
252    raw_os_ostream OSS(OS);
253    ConstantPool->print(OSS);
254  }
255
256  const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
257
258  if (!RegInfo->livein_empty()) {
259    OS << "Live Ins:";
260    for (MachineRegisterInfo::livein_iterator
261         I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
262      if (TRI)
263        OS << " " << TRI->getName(I->first);
264      else
265        OS << " Reg #" << I->first;
266
267      if (I->second)
268        OS << " in VR#" << I->second << " ";
269    }
270    OS << "\n";
271  }
272  if (!RegInfo->liveout_empty()) {
273    OS << "Live Outs:";
274    for (MachineRegisterInfo::liveout_iterator
275         I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
276      if (TRI)
277        OS << " " << TRI->getName(*I);
278      else
279        OS << " Reg #" << *I;
280    OS << "\n";
281  }
282
283  for (const_iterator BB = begin(); BB != end(); ++BB)
284    BB->print(OS);
285
286  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
287}
288
289/// CFGOnly flag - This is used to control whether or not the CFG graph printer
290/// prints out the contents of basic blocks or not.  This is acceptable because
291/// this code is only really used for debugging purposes.
292///
293static bool CFGOnly = false;
294
295namespace llvm {
296  template<>
297  struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
298    static std::string getGraphName(const MachineFunction *F) {
299      return "CFG for '" + F->getFunction()->getName() + "' function";
300    }
301
302    static std::string getNodeLabel(const MachineBasicBlock *Node,
303                                    const MachineFunction *Graph) {
304      if (CFGOnly && Node->getBasicBlock() &&
305          !Node->getBasicBlock()->getName().empty())
306        return Node->getBasicBlock()->getName() + ":";
307
308      std::ostringstream Out;
309      if (CFGOnly) {
310        Out << Node->getNumber() << ':';
311        return Out.str();
312      }
313
314      Node->print(Out);
315
316      std::string OutStr = Out.str();
317      if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
318
319      // Process string output to make it nicer...
320      for (unsigned i = 0; i != OutStr.length(); ++i)
321        if (OutStr[i] == '\n') {                            // Left justify
322          OutStr[i] = '\\';
323          OutStr.insert(OutStr.begin()+i+1, 'l');
324        }
325      return OutStr;
326    }
327  };
328}
329
330void MachineFunction::viewCFG() const
331{
332#ifndef NDEBUG
333  ViewGraph(this, "mf" + getFunction()->getName());
334#else
335  cerr << "SelectionDAG::viewGraph is only available in debug builds on "
336       << "systems with Graphviz or gv!\n";
337#endif // NDEBUG
338}
339
340void MachineFunction::viewCFGOnly() const
341{
342  CFGOnly = true;
343  viewCFG();
344  CFGOnly = false;
345}
346
347// The next two methods are used to construct and to retrieve
348// the MachineCodeForFunction object for the given function.
349// construct() -- Allocates and initializes for a given function and target
350// get()       -- Returns a handle to the object.
351//                This should not be called before "construct()"
352//                for a given Function.
353//
354MachineFunction&
355MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
356{
357  assert(Fn->getAnnotation(MF_AID) == 0 &&
358         "Object already exists for this function!");
359  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
360  Fn->addAnnotation(mcInfo);
361  return *mcInfo;
362}
363
364void MachineFunction::destruct(const Function *Fn) {
365  bool Deleted = Fn->deleteAnnotation(MF_AID);
366  assert(Deleted && "Machine code did not exist for function!");
367  Deleted = Deleted; // silence warning when no assertions.
368}
369
370MachineFunction& MachineFunction::get(const Function *F)
371{
372  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
373  assert(mc && "Call construct() method first to allocate the object");
374  return *mc;
375}
376
377//===----------------------------------------------------------------------===//
378//  MachineFrameInfo implementation
379//===----------------------------------------------------------------------===//
380
381/// CreateFixedObject - Create a new object at a fixed location on the stack.
382/// All fixed objects should be created before other objects are created for
383/// efficiency. By default, fixed objects are immutable. This returns an
384/// index with a negative value.
385///
386int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
387                                        bool Immutable) {
388  assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
389  Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
390  return -++NumFixedObjects;
391}
392
393
394void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
395  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
396
397  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
398    const StackObject &SO = Objects[i];
399    OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
400    if (SO.Size == ~0ULL) {
401      OS << "dead\n";
402      continue;
403    }
404    if (SO.Size == 0)
405      OS << "variable sized";
406    else
407      OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
408    OS << " alignment is " << SO.Alignment << " byte"
409       << (SO.Alignment != 1 ? "s," : ",");
410
411    if (i < NumFixedObjects)
412      OS << " fixed";
413    if (i < NumFixedObjects || SO.SPOffset != -1) {
414      int64_t Off = SO.SPOffset - ValOffset;
415      OS << " at location [SP";
416      if (Off > 0)
417        OS << "+" << Off;
418      else if (Off < 0)
419        OS << Off;
420      OS << "]";
421    }
422    OS << "\n";
423  }
424
425  if (HasVarSizedObjects)
426    OS << "  Stack frame contains variable sized objects\n";
427}
428
429void MachineFrameInfo::dump(const MachineFunction &MF) const {
430  print(MF, *cerr.stream());
431}
432
433
434//===----------------------------------------------------------------------===//
435//  MachineJumpTableInfo implementation
436//===----------------------------------------------------------------------===//
437
438/// getJumpTableIndex - Create a new jump table entry in the jump table info
439/// or return an existing one.
440///
441unsigned MachineJumpTableInfo::getJumpTableIndex(
442                               const std::vector<MachineBasicBlock*> &DestBBs) {
443  assert(!DestBBs.empty() && "Cannot create an empty jump table!");
444  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
445    if (JumpTables[i].MBBs == DestBBs)
446      return i;
447
448  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
449  return JumpTables.size()-1;
450}
451
452
453void MachineJumpTableInfo::print(std::ostream &OS) const {
454  // FIXME: this is lame, maybe we could print out the MBB numbers or something
455  // like {1, 2, 4, 5, 3, 0}
456  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
457    OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size()
458       << " entries\n";
459  }
460}
461
462void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
463
464
465//===----------------------------------------------------------------------===//
466//  MachineConstantPool implementation
467//===----------------------------------------------------------------------===//
468
469const Type *MachineConstantPoolEntry::getType() const {
470  if (isMachineConstantPoolEntry())
471      return Val.MachineCPVal->getType();
472  return Val.ConstVal->getType();
473}
474
475MachineConstantPool::~MachineConstantPool() {
476  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
477    if (Constants[i].isMachineConstantPoolEntry())
478      delete Constants[i].Val.MachineCPVal;
479}
480
481/// getConstantPoolIndex - Create a new entry in the constant pool or return
482/// an existing one.  User must specify an alignment in bytes for the object.
483///
484unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
485                                                   unsigned Alignment) {
486  assert(Alignment && "Alignment must be specified!");
487  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
488
489  // Check to see if we already have this constant.
490  //
491  // FIXME, this could be made much more efficient for large constant pools.
492  unsigned AlignMask = (1 << Alignment)-1;
493  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
494    if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
495      return i;
496
497  unsigned Offset = 0;
498  if (!Constants.empty()) {
499    Offset = Constants.back().getOffset();
500    Offset += TD->getABITypeSize(Constants.back().getType());
501    Offset = (Offset+AlignMask)&~AlignMask;
502  }
503
504  Constants.push_back(MachineConstantPoolEntry(C, Offset));
505  return Constants.size()-1;
506}
507
508unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
509                                                   unsigned Alignment) {
510  assert(Alignment && "Alignment must be specified!");
511  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
512
513  // Check to see if we already have this constant.
514  //
515  // FIXME, this could be made much more efficient for large constant pools.
516  unsigned AlignMask = (1 << Alignment)-1;
517  int Idx = V->getExistingMachineCPValue(this, Alignment);
518  if (Idx != -1)
519    return (unsigned)Idx;
520
521  unsigned Offset = 0;
522  if (!Constants.empty()) {
523    Offset = Constants.back().getOffset();
524    Offset += TD->getABITypeSize(Constants.back().getType());
525    Offset = (Offset+AlignMask)&~AlignMask;
526  }
527
528  Constants.push_back(MachineConstantPoolEntry(V, Offset));
529  return Constants.size()-1;
530}
531
532void MachineConstantPool::print(raw_ostream &OS) const {
533  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
534    OS << "  <cp #" << i << "> is";
535    if (Constants[i].isMachineConstantPoolEntry())
536      Constants[i].Val.MachineCPVal->print(OS);
537    else
538      OS << *(Value*)Constants[i].Val.ConstVal;
539    OS << " , offset=" << Constants[i].getOffset();
540    OS << "\n";
541  }
542}
543
544void MachineConstantPool::dump() const { print(errs()); errs().flush(); }
545