MachineFunction.cpp 18 KB

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