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/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/TargetLowering.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/LeakDetector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Config/config.h"
38 static AnnotationID MF_AID(
39 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
41 // Out of line virtual function to home classes.
42 void MachineFunctionPass::virtfn() {}
45 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
47 const std::string Banner;
49 Printer (std::ostream *_OS, const std::string &_Banner) :
50 OS (_OS), Banner (_Banner) { }
52 const char *getPassName() const { return "MachineFunction Printer"; }
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 bool runOnMachineFunction(MachineFunction &MF) {
66 /// Returns a newly-created MachineFunction Printer pass. The default output
67 /// stream is std::cerr; the default banner is empty.
69 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
70 const std::string &Banner){
71 return new Printer(OS, Banner);
75 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
76 const char *getPassName() const { return "Machine Code Deleter"; }
78 bool runOnMachineFunction(MachineFunction &MF) {
79 // Delete the annotation from the function now.
80 MachineFunction::destruct(MF.getFunction());
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.
89 FunctionPass *llvm::createMachineCodeDeleter() {
95 //===---------------------------------------------------------------------===//
96 // MachineFunction implementation
97 //===---------------------------------------------------------------------===//
99 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
100 MachineBasicBlock* dummy = new MachineBasicBlock();
101 LeakDetector::removeGarbageObject(dummy);
105 void 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;
114 MachineFunction::MachineFunction(const Function *F,
115 const TargetMachine &TM)
116 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
117 SSARegMapping = new SSARegMap();
119 FrameInfo = new MachineFrameInfo();
120 ConstantPool = new MachineConstantPool(TM.getTargetData());
122 // Set up jump table.
123 const TargetData &TD = *TM.getTargetData();
124 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
125 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
126 unsigned Alignment = IsPic ? TD.getIntABIAlignment()
127 : TD.getPointerABIAlignment();
128 JumpTableInfo = new MachineJumpTableInfo(EntrySize, Alignment);
130 BasicBlocks.Parent = this;
133 MachineFunction::~MachineFunction() {
135 delete SSARegMapping;
139 delete JumpTableInfo;
140 delete[] UsedPhysRegs;
144 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
145 /// recomputes them. This guarantees that the MBB numbers are sequential,
146 /// dense, and match the ordering of the blocks within the function. If a
147 /// specific MachineBasicBlock is specified, only that block and those after
148 /// it are renumbered.
149 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
150 if (empty()) { MBBNumbering.clear(); return; }
151 MachineFunction::iterator MBBI, E = end();
157 // Figure out the block number this should have.
158 unsigned BlockNo = 0;
160 BlockNo = prior(MBBI)->getNumber()+1;
162 for (; MBBI != E; ++MBBI, ++BlockNo) {
163 if (MBBI->getNumber() != (int)BlockNo) {
164 // Remove use of the old number.
165 if (MBBI->getNumber() != -1) {
166 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
167 "MBB number mismatch!");
168 MBBNumbering[MBBI->getNumber()] = 0;
171 // If BlockNo is already taken, set that block's number to -1.
172 if (MBBNumbering[BlockNo])
173 MBBNumbering[BlockNo]->setNumber(-1);
175 MBBNumbering[BlockNo] = MBBI;
176 MBBI->setNumber(BlockNo);
180 // Okay, all the blocks are renumbered. If we have compactified the block
181 // numbering, shrink MBBNumbering now.
182 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
183 MBBNumbering.resize(BlockNo);
187 void MachineFunction::dump() const { print(*cerr.stream()); }
189 void MachineFunction::print(std::ostream &OS) const {
190 OS << "# Machine code for " << Fn->getName () << "():\n";
192 // Print Frame Information
193 getFrameInfo()->print(*this, OS);
195 // Print JumpTable Information
196 getJumpTableInfo()->print(OS);
198 // Print Constant Pool
199 getConstantPool()->print(OS);
201 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
203 if (livein_begin() != livein_end()) {
205 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
207 OS << " " << MRI->getName(I->first);
209 OS << " Reg #" << I->first;
212 OS << " in VR#" << I->second << " ";
216 if (liveout_begin() != liveout_end()) {
218 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
220 OS << " " << MRI->getName(*I);
222 OS << " Reg #" << *I;
226 for (const_iterator BB = begin(); BB != end(); ++BB)
229 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
232 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
233 /// prints out the contents of basic blocks or not. This is acceptable because
234 /// this code is only really used for debugging purposes.
236 static bool CFGOnly = false;
240 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
241 static std::string getGraphName(const MachineFunction *F) {
242 return "CFG for '" + F->getFunction()->getName() + "' function";
245 static std::string getNodeLabel(const MachineBasicBlock *Node,
246 const MachineFunction *Graph) {
247 if (CFGOnly && Node->getBasicBlock() &&
248 !Node->getBasicBlock()->getName().empty())
249 return Node->getBasicBlock()->getName() + ":";
251 std::ostringstream Out;
253 Out << Node->getNumber() << ':';
259 std::string OutStr = Out.str();
260 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
262 // Process string output to make it nicer...
263 for (unsigned i = 0; i != OutStr.length(); ++i)
264 if (OutStr[i] == '\n') { // Left justify
266 OutStr.insert(OutStr.begin()+i+1, 'l');
273 void MachineFunction::viewCFG() const
276 ViewGraph(this, "mf" + getFunction()->getName());
278 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
279 << "systems with Graphviz or gv!\n";
283 void MachineFunction::viewCFGOnly() const
290 // The next two methods are used to construct and to retrieve
291 // the MachineCodeForFunction object for the given function.
292 // construct() -- Allocates and initializes for a given function and target
293 // get() -- Returns a handle to the object.
294 // This should not be called before "construct()"
295 // for a given Function.
298 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
300 assert(Fn->getAnnotation(MF_AID) == 0 &&
301 "Object already exists for this function!");
302 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
303 Fn->addAnnotation(mcInfo);
307 void MachineFunction::destruct(const Function *Fn) {
308 bool Deleted = Fn->deleteAnnotation(MF_AID);
309 assert(Deleted && "Machine code did not exist for function!");
312 MachineFunction& MachineFunction::get(const Function *F)
314 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
315 assert(mc && "Call construct() method first to allocate the object");
319 void MachineFunction::clearSSARegMap() {
320 delete SSARegMapping;
324 //===----------------------------------------------------------------------===//
325 // MachineFrameInfo implementation
326 //===----------------------------------------------------------------------===//
328 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
329 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
331 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
332 const StackObject &SO = Objects[i];
333 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
335 OS << "variable sized";
337 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
338 OS << " alignment is " << SO.Alignment << " byte"
339 << (SO.Alignment != 1 ? "s," : ",");
341 if (i < NumFixedObjects)
343 if (i < NumFixedObjects || SO.SPOffset != -1) {
344 int Off = SO.SPOffset - ValOffset;
345 OS << " at location [SP";
355 if (HasVarSizedObjects)
356 OS << " Stack frame contains variable sized objects\n";
359 void MachineFrameInfo::dump(const MachineFunction &MF) const {
360 print(MF, *cerr.stream());
364 //===----------------------------------------------------------------------===//
365 // MachineJumpTableInfo implementation
366 //===----------------------------------------------------------------------===//
368 /// getJumpTableIndex - Create a new jump table entry in the jump table info
369 /// or return an existing one.
371 unsigned MachineJumpTableInfo::getJumpTableIndex(
372 const std::vector<MachineBasicBlock*> &DestBBs) {
373 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
374 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
375 if (JumpTables[i].MBBs == DestBBs)
378 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
379 return JumpTables.size()-1;
383 void MachineJumpTableInfo::print(std::ostream &OS) const {
384 // FIXME: this is lame, maybe we could print out the MBB numbers or something
385 // like {1, 2, 4, 5, 3, 0}
386 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
387 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
392 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
395 //===----------------------------------------------------------------------===//
396 // MachineConstantPool implementation
397 //===----------------------------------------------------------------------===//
399 const Type *MachineConstantPoolEntry::getType() const {
400 if (isMachineConstantPoolEntry())
401 return Val.MachineCPVal->getType();
402 return Val.ConstVal->getType();
405 MachineConstantPool::~MachineConstantPool() {
406 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
407 if (Constants[i].isMachineConstantPoolEntry())
408 delete Constants[i].Val.MachineCPVal;
411 /// getConstantPoolIndex - Create a new entry in the constant pool or return
412 /// an existing one. User must specify an alignment in bytes for the object.
414 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
415 unsigned Alignment) {
416 assert(Alignment && "Alignment must be specified!");
417 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
419 // Check to see if we already have this constant.
421 // FIXME, this could be made much more efficient for large constant pools.
422 unsigned AlignMask = (1 << Alignment)-1;
423 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
424 if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
428 if (!Constants.empty()) {
429 Offset = Constants.back().getOffset();
430 Offset += TD->getTypeSize(Constants.back().getType());
431 Offset = (Offset+AlignMask)&~AlignMask;
434 Constants.push_back(MachineConstantPoolEntry(C, Offset));
435 return Constants.size()-1;
438 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
439 unsigned Alignment) {
440 assert(Alignment && "Alignment must be specified!");
441 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
443 // Check to see if we already have this constant.
445 // FIXME, this could be made much more efficient for large constant pools.
446 unsigned AlignMask = (1 << Alignment)-1;
447 int Idx = V->getExistingMachineCPValue(this, Alignment);
449 return (unsigned)Idx;
452 if (!Constants.empty()) {
453 Offset = Constants.back().getOffset();
454 Offset += TD->getTypeSize(Constants.back().getType());
455 Offset = (Offset+AlignMask)&~AlignMask;
458 Constants.push_back(MachineConstantPoolEntry(V, Offset));
459 return Constants.size()-1;
463 void MachineConstantPool::print(std::ostream &OS) const {
464 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
465 OS << " <cp #" << i << "> is";
466 if (Constants[i].isMachineConstantPoolEntry())
467 Constants[i].Val.MachineCPVal->print(OS);
469 OS << *(Value*)Constants[i].Val.ConstVal;
470 OS << " , offset=" << Constants[i].getOffset();
475 void MachineConstantPool::dump() const { print(*cerr.stream()); }