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