MachineFunction.cpp revision 9abd7c38675ad305c733b7e90578255271afc6bd
1//===-- MachineFunction.cpp -----------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/MachineFunctionPass.h"
17#include "llvm/CodeGen/MachineInstr.h"
18#include "llvm/CodeGen/SSARegMap.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineJumpTableInfo.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Target/TargetFrameInfo.h"
26#include "llvm/Function.h"
27#include "llvm/Instructions.h"
28#include "llvm/Support/LeakDetector.h"
29#include "llvm/Support/GraphWriter.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Config/config.h"
32#include <fstream>
33#include <iostream>
34#include <sstream>
35
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    std::ostream *OS;
47    const std::string Banner;
48
49    Printer (std::ostream *_OS, const std::string &_Banner) :
50      OS (_OS), Banner (_Banner) { }
51
52    const char *getPassName() const { return "MachineFunction Printer"; }
53
54    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55      AU.setPreservesAll();
56    }
57
58    bool runOnMachineFunction(MachineFunction &MF) {
59      (*OS) << Banner;
60      MF.print (*OS);
61      return false;
62    }
63  };
64}
65
66/// Returns a newly-created MachineFunction Printer pass. The default output
67/// stream is std::cerr; the default banner is empty.
68///
69FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
70                                                     const std::string &Banner){
71  return new Printer(OS, Banner);
72}
73
74namespace {
75  struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
76    const char *getPassName() const { return "Machine Code Deleter"; }
77
78    bool runOnMachineFunction(MachineFunction &MF) {
79      // Delete the annotation from the function now.
80      MachineFunction::destruct(MF.getFunction());
81      return true;
82    }
83  };
84}
85
86/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
87/// the current function, which should happen after the function has been
88/// emitted to a .s file or to memory.
89FunctionPass *llvm::createMachineCodeDeleter() {
90  return new Deleter();
91}
92
93
94
95//===---------------------------------------------------------------------===//
96// MachineFunction implementation
97//===---------------------------------------------------------------------===//
98
99MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
100  MachineBasicBlock* dummy = new MachineBasicBlock();
101  LeakDetector::removeGarbageObject(dummy);
102  return dummy;
103}
104
105void ilist_traits<MachineBasicBlock>::transferNodesFromList(
106  iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
107  ilist_iterator<MachineBasicBlock> first,
108  ilist_iterator<MachineBasicBlock> last) {
109  if (Parent != toList.Parent)
110    for (; first != last; ++first)
111      first->Parent = toList.Parent;
112}
113
114MachineFunction::MachineFunction(const Function *F,
115                                 const TargetMachine &TM)
116  : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
117  SSARegMapping = new SSARegMap();
118  MFInfo = 0;
119  FrameInfo = new MachineFrameInfo();
120  ConstantPool = new MachineConstantPool(TM.getTargetData());
121  JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
122  BasicBlocks.Parent = this;
123}
124
125MachineFunction::~MachineFunction() {
126  BasicBlocks.clear();
127  delete SSARegMapping;
128  delete MFInfo;
129  delete FrameInfo;
130  delete ConstantPool;
131  delete JumpTableInfo;
132  delete[] UsedPhysRegs;
133}
134
135void MachineFunction::dump() const { print(std::cerr); }
136
137void MachineFunction::print(std::ostream &OS) const {
138  OS << "# Machine code for " << Fn->getName () << "():\n";
139
140  // Print Frame Information
141  getFrameInfo()->print(*this, OS);
142
143  // Print JumpTable Information
144  getJumpTableInfo()->print(OS);
145
146  // Print Constant Pool
147  getConstantPool()->print(OS);
148
149  const MRegisterInfo *MRI = getTarget().getRegisterInfo();
150
151  if (livein_begin() != livein_end()) {
152    OS << "Live Ins:";
153    for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
154      if (MRI)
155        OS << " " << MRI->getName(I->first);
156      else
157        OS << " Reg #" << I->first;
158
159      if (I->second)
160        OS << " in VR#" << I->second << " ";
161    }
162    OS << "\n";
163  }
164  if (liveout_begin() != liveout_end()) {
165    OS << "Live Outs:";
166    for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
167      if (MRI)
168        OS << " " << MRI->getName(*I);
169      else
170        OS << " Reg #" << *I;
171    OS << "\n";
172  }
173
174  for (const_iterator BB = begin(); BB != end(); ++BB)
175    BB->print(OS);
176
177  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
178}
179
180/// CFGOnly flag - This is used to control whether or not the CFG graph printer
181/// prints out the contents of basic blocks or not.  This is acceptable because
182/// this code is only really used for debugging purposes.
183///
184static bool CFGOnly = false;
185
186namespace llvm {
187  template<>
188  struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
189    static std::string getGraphName(const MachineFunction *F) {
190      return "CFG for '" + F->getFunction()->getName() + "' function";
191    }
192
193    static std::string getNodeLabel(const MachineBasicBlock *Node,
194                                    const MachineFunction *Graph) {
195      if (CFGOnly && Node->getBasicBlock() &&
196          !Node->getBasicBlock()->getName().empty())
197        return Node->getBasicBlock()->getName() + ":";
198
199      std::ostringstream Out;
200      if (CFGOnly) {
201        Out << Node->getNumber() << ':';
202        return Out.str();
203      }
204
205      Node->print(Out);
206
207      std::string OutStr = Out.str();
208      if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
209
210      // Process string output to make it nicer...
211      for (unsigned i = 0; i != OutStr.length(); ++i)
212        if (OutStr[i] == '\n') {                            // Left justify
213          OutStr[i] = '\\';
214          OutStr.insert(OutStr.begin()+i+1, 'l');
215        }
216      return OutStr;
217    }
218  };
219}
220
221void MachineFunction::viewCFG() const
222{
223#ifndef NDEBUG
224  ViewGraph(this, "mf" + getFunction()->getName());
225#else
226  std::cerr << "SelectionDAG::viewGraph is only available in debug builds on "
227            << "systems with Graphviz or gv!\n";
228#endif // NDEBUG
229}
230
231void MachineFunction::viewCFGOnly() const
232{
233  CFGOnly = true;
234  viewCFG();
235  CFGOnly = false;
236}
237
238// The next two methods are used to construct and to retrieve
239// the MachineCodeForFunction object for the given function.
240// construct() -- Allocates and initializes for a given function and target
241// get()       -- Returns a handle to the object.
242//                This should not be called before "construct()"
243//                for a given Function.
244//
245MachineFunction&
246MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
247{
248  assert(Fn->getAnnotation(MF_AID) == 0 &&
249         "Object already exists for this function!");
250  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
251  Fn->addAnnotation(mcInfo);
252  return *mcInfo;
253}
254
255void MachineFunction::destruct(const Function *Fn) {
256  bool Deleted = Fn->deleteAnnotation(MF_AID);
257  assert(Deleted && "Machine code did not exist for function!");
258}
259
260MachineFunction& MachineFunction::get(const Function *F)
261{
262  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
263  assert(mc && "Call construct() method first to allocate the object");
264  return *mc;
265}
266
267void MachineFunction::clearSSARegMap() {
268  delete SSARegMapping;
269  SSARegMapping = 0;
270}
271
272//===----------------------------------------------------------------------===//
273//  MachineFrameInfo implementation
274//===----------------------------------------------------------------------===//
275
276void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
277  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
278
279  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
280    const StackObject &SO = Objects[i];
281    OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
282    if (SO.Size == 0)
283      OS << "variable sized";
284    else
285      OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
286    OS << " alignment is " << SO.Alignment << " byte"
287       << (SO.Alignment != 1 ? "s," : ",");
288
289    if (i < NumFixedObjects)
290      OS << " fixed";
291    if (i < NumFixedObjects || SO.SPOffset != -1) {
292      int Off = SO.SPOffset - ValOffset;
293      OS << " at location [SP";
294      if (Off > 0)
295        OS << "+" << Off;
296      else if (Off < 0)
297        OS << Off;
298      OS << "]";
299    }
300    OS << "\n";
301  }
302
303  if (HasVarSizedObjects)
304    OS << "  Stack frame contains variable sized objects\n";
305}
306
307void MachineFrameInfo::dump(const MachineFunction &MF) const {
308  print(MF, std::cerr);
309}
310
311
312//===----------------------------------------------------------------------===//
313//  MachineJumpTableInfo implementation
314//===----------------------------------------------------------------------===//
315
316/// getJumpTableIndex - Create a new jump table entry in the jump table info
317/// or return an existing one.
318///
319unsigned MachineJumpTableInfo::getJumpTableIndex(
320                                     std::vector<MachineBasicBlock*> &DestBBs) {
321  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
322    if (JumpTables[i].MBBs == DestBBs)
323      return i;
324
325  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
326  return JumpTables.size()-1;
327}
328
329
330void MachineJumpTableInfo::print(std::ostream &OS) const {
331  // FIXME: this is lame, maybe we could print out the MBB numbers or something
332  // like {1, 2, 4, 5, 3, 0}
333  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
334    OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size()
335       << " entries\n";
336  }
337}
338
339unsigned MachineJumpTableInfo::getEntrySize() const {
340  return TD->getPointerSize();
341}
342
343unsigned MachineJumpTableInfo::getAlignment() const {
344  return TD->getPointerAlignment();
345}
346
347void MachineJumpTableInfo::dump() const { print(std::cerr); }
348
349
350//===----------------------------------------------------------------------===//
351//  MachineConstantPool implementation
352//===----------------------------------------------------------------------===//
353
354const Type *MachineConstantPoolEntry::getType() const {
355  if (isMachineConstantPoolEntry())
356      return Val.MachineCPVal->getType();
357  return Val.ConstVal->getType();
358}
359
360MachineConstantPool::~MachineConstantPool() {
361  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
362    if (Constants[i].isMachineConstantPoolEntry())
363      delete Constants[i].Val.MachineCPVal;
364}
365
366/// getConstantPoolIndex - Create a new entry in the constant pool or return
367/// an existing one.  User must specify an alignment in bytes for the object.
368///
369unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
370                                                   unsigned Alignment) {
371  assert(Alignment && "Alignment must be specified!");
372  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
373
374  // Check to see if we already have this constant.
375  //
376  // FIXME, this could be made much more efficient for large constant pools.
377  unsigned AlignMask = (1 << Alignment)-1;
378  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
379    if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
380      return i;
381
382  unsigned Offset = 0;
383  if (!Constants.empty()) {
384    Offset = Constants.back().Offset;
385    Offset += TD->getTypeSize(Constants.back().getType());
386    Offset = (Offset+AlignMask)&~AlignMask;
387  }
388
389  Constants.push_back(MachineConstantPoolEntry(C, Offset));
390  return Constants.size()-1;
391}
392
393unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
394                                                   unsigned Alignment) {
395  assert(Alignment && "Alignment must be specified!");
396  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
397
398  // Check to see if we already have this constant.
399  //
400  // FIXME, this could be made much more efficient for large constant pools.
401  unsigned AlignMask = (1 << Alignment)-1;
402  int Idx = V->getExistingMachineCPValue(this, Alignment);
403  if (Idx != -1)
404    return (unsigned)Idx;
405
406  unsigned Offset = 0;
407  if (!Constants.empty()) {
408    Offset = Constants.back().Offset;
409    Offset += TD->getTypeSize(Constants.back().getType());
410    Offset = (Offset+AlignMask)&~AlignMask;
411  }
412
413  Constants.push_back(MachineConstantPoolEntry(V, Offset));
414  return Constants.size()-1;
415}
416
417
418void MachineConstantPool::print(std::ostream &OS) const {
419  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
420    OS << "  <cp #" << i << "> is";
421    if (Constants[i].isMachineConstantPoolEntry())
422      Constants[i].Val.MachineCPVal->print(OS);
423    else
424      OS << *(Value*)Constants[i].Val.ConstVal;
425    OS << " , offset=" << Constants[i].Offset;
426    OS << "\n";
427  }
428}
429
430void MachineConstantPool::dump() const { print(std::cerr); }
431