1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
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"
39 static AnnotationID MF_AID(
40 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
42 // Out of line virtual function to home classes.
43 void MachineFunctionPass::virtfn() {}
46 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
50 const std::string Banner;
52 Printer (std::ostream *_OS, const std::string &_Banner)
53 : MachineFunctionPass((intptr_t)&ID), OS (_OS), Banner (_Banner) { }
55 const char *getPassName() const { return "MachineFunction Printer"; }
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 bool runOnMachineFunction(MachineFunction &MF) {
70 /// Returns a newly-created MachineFunction Printer pass. The default output
71 /// stream is std::cerr; the default banner is empty.
73 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
74 const std::string &Banner){
75 return new Printer(OS, Banner);
79 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
81 Deleter() : MachineFunctionPass((intptr_t)&ID) {}
83 const char *getPassName() const { return "Machine Code Deleter"; }
85 bool runOnMachineFunction(MachineFunction &MF) {
86 // Delete the annotation from the function now.
87 MachineFunction::destruct(MF.getFunction());
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.
97 FunctionPass *llvm::createMachineCodeDeleter() {
103 //===---------------------------------------------------------------------===//
104 // MachineFunction implementation
105 //===---------------------------------------------------------------------===//
107 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
108 MachineBasicBlock* dummy = new MachineBasicBlock();
109 LeakDetector::removeGarbageObject(dummy);
113 void 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;
122 MachineFunction::MachineFunction(const Function *F,
123 const TargetMachine &TM)
124 : Annotation(MF_AID), Fn(F), Target(TM) {
125 SSARegMapping = new SSARegMap();
127 FrameInfo = new MachineFrameInfo();
128 ConstantPool = new MachineConstantPool(TM.getTargetData());
129 UsedPhysRegs.resize(TM.getRegisterInfo()->getNumRegs());
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);
139 BasicBlocks.Parent = this;
142 MachineFunction::~MachineFunction() {
144 delete SSARegMapping;
148 delete JumpTableInfo;
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.
157 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
158 if (empty()) { MBBNumbering.clear(); return; }
159 MachineFunction::iterator MBBI, E = end();
165 // Figure out the block number this should have.
166 unsigned BlockNo = 0;
168 BlockNo = prior(MBBI)->getNumber()+1;
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;
179 // If BlockNo is already taken, set that block's number to -1.
180 if (MBBNumbering[BlockNo])
181 MBBNumbering[BlockNo]->setNumber(-1);
183 MBBNumbering[BlockNo] = MBBI;
184 MBBI->setNumber(BlockNo);
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);
195 void MachineFunction::dump() const { print(*cerr.stream()); }
197 void MachineFunction::print(std::ostream &OS) const {
198 OS << "# Machine code for " << Fn->getName () << "():\n";
200 // Print Frame Information
201 getFrameInfo()->print(*this, OS);
203 // Print JumpTable Information
204 getJumpTableInfo()->print(OS);
206 // Print Constant Pool
207 getConstantPool()->print(OS);
209 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
211 if (!livein_empty()) {
213 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
215 OS << " " << MRI->getName(I->first);
217 OS << " Reg #" << I->first;
220 OS << " in VR#" << I->second << " ";
224 if (!liveout_empty()) {
226 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
228 OS << " " << MRI->getName(*I);
230 OS << " Reg #" << *I;
234 for (const_iterator BB = begin(); BB != end(); ++BB)
237 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
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.
244 static bool CFGOnly = false;
248 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
249 static std::string getGraphName(const MachineFunction *F) {
250 return "CFG for '" + F->getFunction()->getName() + "' function";
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() + ":";
259 std::ostringstream Out;
261 Out << Node->getNumber() << ':';
267 std::string OutStr = Out.str();
268 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
270 // Process string output to make it nicer...
271 for (unsigned i = 0; i != OutStr.length(); ++i)
272 if (OutStr[i] == '\n') { // Left justify
274 OutStr.insert(OutStr.begin()+i+1, 'l');
281 void MachineFunction::viewCFG() const
284 ViewGraph(this, "mf" + getFunction()->getName());
286 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
287 << "systems with Graphviz or gv!\n";
291 void MachineFunction::viewCFGOnly() const
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.
306 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
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);
315 void MachineFunction::destruct(const Function *Fn) {
316 bool Deleted = Fn->deleteAnnotation(MF_AID);
317 assert(Deleted && "Machine code did not exist for function!");
320 MachineFunction& MachineFunction::get(const Function *F)
322 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
323 assert(mc && "Call construct() method first to allocate the object");
327 void MachineFunction::clearSSARegMap() {
328 delete SSARegMapping;
332 //===----------------------------------------------------------------------===//
333 // MachineFrameInfo implementation
334 //===----------------------------------------------------------------------===//
336 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
337 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
339 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
340 const StackObject &SO = Objects[i];
341 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
343 OS << "variable sized";
345 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
346 OS << " alignment is " << SO.Alignment << " byte"
347 << (SO.Alignment != 1 ? "s," : ",");
349 if (i < NumFixedObjects)
351 if (i < NumFixedObjects || SO.SPOffset != -1) {
352 int64_t Off = SO.SPOffset - ValOffset;
353 OS << " at location [SP";
363 if (HasVarSizedObjects)
364 OS << " Stack frame contains variable sized objects\n";
367 void MachineFrameInfo::dump(const MachineFunction &MF) const {
368 print(MF, *cerr.stream());
372 //===----------------------------------------------------------------------===//
373 // MachineJumpTableInfo implementation
374 //===----------------------------------------------------------------------===//
376 /// getJumpTableIndex - Create a new jump table entry in the jump table info
377 /// or return an existing one.
379 unsigned 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)
386 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
387 return JumpTables.size()-1;
391 void 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()
400 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
403 //===----------------------------------------------------------------------===//
404 // MachineConstantPool implementation
405 //===----------------------------------------------------------------------===//
407 const Type *MachineConstantPoolEntry::getType() const {
408 if (isMachineConstantPoolEntry())
409 return Val.MachineCPVal->getType();
410 return Val.ConstVal->getType();
413 MachineConstantPool::~MachineConstantPool() {
414 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
415 if (Constants[i].isMachineConstantPoolEntry())
416 delete Constants[i].Val.MachineCPVal;
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.
422 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
423 unsigned Alignment) {
424 assert(Alignment && "Alignment must be specified!");
425 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
427 // Check to see if we already have this constant.
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)
436 if (!Constants.empty()) {
437 Offset = Constants.back().getOffset();
438 Offset += TD->getTypeSize(Constants.back().getType());
439 Offset = (Offset+AlignMask)&~AlignMask;
442 Constants.push_back(MachineConstantPoolEntry(C, Offset));
443 return Constants.size()-1;
446 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
447 unsigned Alignment) {
448 assert(Alignment && "Alignment must be specified!");
449 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
451 // Check to see if we already have this constant.
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);
457 return (unsigned)Idx;
460 if (!Constants.empty()) {
461 Offset = Constants.back().getOffset();
462 Offset += TD->getTypeSize(Constants.back().getType());
463 Offset = (Offset+AlignMask)&~AlignMask;
466 Constants.push_back(MachineConstantPoolEntry(V, Offset));
467 return Constants.size()-1;
471 void 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);
477 OS << *(Value*)Constants[i].Val.ConstVal;
478 OS << " , offset=" << Constants[i].getOffset();
483 void MachineConstantPool::dump() const { print(*cerr.stream()); }