MachineFunction.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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/CodeGen/MachineFunction.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/Analysis/ConstantFolding.h"
  19. #include "llvm/CodeGen/MachineConstantPool.h"
  20. #include "llvm/CodeGen/MachineFrameInfo.h"
  21. #include "llvm/CodeGen/MachineFunctionPass.h"
  22. #include "llvm/CodeGen/MachineInstr.h"
  23. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  24. #include "llvm/CodeGen/MachineModuleInfo.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/CodeGen/Passes.h"
  27. #include "llvm/DebugInfo.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/MC/MCAsmInfo.h"
  31. #include "llvm/MC/MCContext.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/GraphWriter.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Target/TargetFrameLowering.h"
  36. #include "llvm/Target/TargetLowering.h"
  37. #include "llvm/Target/TargetMachine.h"
  38. using namespace llvm;
  39. //===----------------------------------------------------------------------===//
  40. // MachineFunction implementation
  41. //===----------------------------------------------------------------------===//
  42. // Out of line virtual method.
  43. MachineFunctionInfo::~MachineFunctionInfo() {}
  44. void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
  45. MBB->getParent()->DeleteMachineBasicBlock(MBB);
  46. }
  47. MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
  48. unsigned FunctionNum, MachineModuleInfo &mmi,
  49. GCModuleInfo* gmi)
  50. : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
  51. if (TM.getRegisterInfo())
  52. RegInfo = new (Allocator) MachineRegisterInfo(*TM.getRegisterInfo());
  53. else
  54. RegInfo = 0;
  55. MFInfo = 0;
  56. FrameInfo = new (Allocator) MachineFrameInfo(*TM.getFrameLowering(),
  57. TM.Options.RealignStack);
  58. if (Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  59. Attribute::StackAlignment))
  60. FrameInfo->ensureMaxAlignment(Fn->getAttributes().
  61. getStackAlignment(AttributeSet::FunctionIndex));
  62. ConstantPool = new (Allocator) MachineConstantPool(TM.getDataLayout());
  63. Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
  64. // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
  65. if (!Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  66. Attribute::OptimizeForSize))
  67. Alignment = std::max(Alignment,
  68. TM.getTargetLowering()->getPrefFunctionAlignment());
  69. FunctionNumber = FunctionNum;
  70. JumpTableInfo = 0;
  71. }
  72. MachineFunction::~MachineFunction() {
  73. // Don't call destructors on MachineInstr and MachineOperand. All of their
  74. // memory comes from the BumpPtrAllocator which is about to be purged.
  75. //
  76. // Do call MachineBasicBlock destructors, it contains std::vectors.
  77. for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
  78. I->Insts.clearAndLeakNodesUnsafely();
  79. InstructionRecycler.clear(Allocator);
  80. OperandRecycler.clear(Allocator);
  81. BasicBlockRecycler.clear(Allocator);
  82. if (RegInfo) {
  83. RegInfo->~MachineRegisterInfo();
  84. Allocator.Deallocate(RegInfo);
  85. }
  86. if (MFInfo) {
  87. MFInfo->~MachineFunctionInfo();
  88. Allocator.Deallocate(MFInfo);
  89. }
  90. FrameInfo->~MachineFrameInfo();
  91. Allocator.Deallocate(FrameInfo);
  92. ConstantPool->~MachineConstantPool();
  93. Allocator.Deallocate(ConstantPool);
  94. if (JumpTableInfo) {
  95. JumpTableInfo->~MachineJumpTableInfo();
  96. Allocator.Deallocate(JumpTableInfo);
  97. }
  98. }
  99. /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
  100. /// does already exist, allocate one.
  101. MachineJumpTableInfo *MachineFunction::
  102. getOrCreateJumpTableInfo(unsigned EntryKind) {
  103. if (JumpTableInfo) return JumpTableInfo;
  104. JumpTableInfo = new (Allocator)
  105. MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
  106. return JumpTableInfo;
  107. }
  108. /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
  109. /// recomputes them. This guarantees that the MBB numbers are sequential,
  110. /// dense, and match the ordering of the blocks within the function. If a
  111. /// specific MachineBasicBlock is specified, only that block and those after
  112. /// it are renumbered.
  113. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
  114. if (empty()) { MBBNumbering.clear(); return; }
  115. MachineFunction::iterator MBBI, E = end();
  116. if (MBB == 0)
  117. MBBI = begin();
  118. else
  119. MBBI = MBB;
  120. // Figure out the block number this should have.
  121. unsigned BlockNo = 0;
  122. if (MBBI != begin())
  123. BlockNo = prior(MBBI)->getNumber()+1;
  124. for (; MBBI != E; ++MBBI, ++BlockNo) {
  125. if (MBBI->getNumber() != (int)BlockNo) {
  126. // Remove use of the old number.
  127. if (MBBI->getNumber() != -1) {
  128. assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
  129. "MBB number mismatch!");
  130. MBBNumbering[MBBI->getNumber()] = 0;
  131. }
  132. // If BlockNo is already taken, set that block's number to -1.
  133. if (MBBNumbering[BlockNo])
  134. MBBNumbering[BlockNo]->setNumber(-1);
  135. MBBNumbering[BlockNo] = MBBI;
  136. MBBI->setNumber(BlockNo);
  137. }
  138. }
  139. // Okay, all the blocks are renumbered. If we have compactified the block
  140. // numbering, shrink MBBNumbering now.
  141. assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
  142. MBBNumbering.resize(BlockNo);
  143. }
  144. /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
  145. /// of `new MachineInstr'.
  146. ///
  147. MachineInstr *
  148. MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
  149. DebugLoc DL, bool NoImp) {
  150. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  151. MachineInstr(*this, MCID, DL, NoImp);
  152. }
  153. /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
  154. /// 'Orig' instruction, identical in all ways except the instruction
  155. /// has no parent, prev, or next.
  156. ///
  157. MachineInstr *
  158. MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
  159. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  160. MachineInstr(*this, *Orig);
  161. }
  162. /// DeleteMachineInstr - Delete the given MachineInstr.
  163. ///
  164. /// This function also serves as the MachineInstr destructor - the real
  165. /// ~MachineInstr() destructor must be empty.
  166. void
  167. MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
  168. // Strip it for parts. The operand array and the MI object itself are
  169. // independently recyclable.
  170. if (MI->Operands)
  171. deallocateOperandArray(MI->CapOperands, MI->Operands);
  172. // Don't call ~MachineInstr() which must be trivial anyway because
  173. // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
  174. // destructors.
  175. InstructionRecycler.Deallocate(Allocator, MI);
  176. }
  177. /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
  178. /// instead of `new MachineBasicBlock'.
  179. ///
  180. MachineBasicBlock *
  181. MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
  182. return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
  183. MachineBasicBlock(*this, bb);
  184. }
  185. /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
  186. ///
  187. void
  188. MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
  189. assert(MBB->getParent() == this && "MBB parent mismatch!");
  190. MBB->~MachineBasicBlock();
  191. BasicBlockRecycler.Deallocate(Allocator, MBB);
  192. }
  193. MachineMemOperand *
  194. MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
  195. uint64_t s, unsigned base_alignment,
  196. const MDNode *TBAAInfo,
  197. const MDNode *Ranges) {
  198. return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
  199. TBAAInfo, Ranges);
  200. }
  201. MachineMemOperand *
  202. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  203. int64_t Offset, uint64_t Size) {
  204. return new (Allocator)
  205. MachineMemOperand(MachinePointerInfo(MMO->getValue(),
  206. MMO->getOffset()+Offset),
  207. MMO->getFlags(), Size,
  208. MMO->getBaseAlignment(), 0);
  209. }
  210. MachineInstr::mmo_iterator
  211. MachineFunction::allocateMemRefsArray(unsigned long Num) {
  212. return Allocator.Allocate<MachineMemOperand *>(Num);
  213. }
  214. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  215. MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
  216. MachineInstr::mmo_iterator End) {
  217. // Count the number of load mem refs.
  218. unsigned Num = 0;
  219. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  220. if ((*I)->isLoad())
  221. ++Num;
  222. // Allocate a new array and populate it with the load information.
  223. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  224. unsigned Index = 0;
  225. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  226. if ((*I)->isLoad()) {
  227. if (!(*I)->isStore())
  228. // Reuse the MMO.
  229. Result[Index] = *I;
  230. else {
  231. // Clone the MMO and unset the store flag.
  232. MachineMemOperand *JustLoad =
  233. getMachineMemOperand((*I)->getPointerInfo(),
  234. (*I)->getFlags() & ~MachineMemOperand::MOStore,
  235. (*I)->getSize(), (*I)->getBaseAlignment(),
  236. (*I)->getTBAAInfo());
  237. Result[Index] = JustLoad;
  238. }
  239. ++Index;
  240. }
  241. }
  242. return std::make_pair(Result, Result + Num);
  243. }
  244. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  245. MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
  246. MachineInstr::mmo_iterator End) {
  247. // Count the number of load mem refs.
  248. unsigned Num = 0;
  249. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  250. if ((*I)->isStore())
  251. ++Num;
  252. // Allocate a new array and populate it with the store information.
  253. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  254. unsigned Index = 0;
  255. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  256. if ((*I)->isStore()) {
  257. if (!(*I)->isLoad())
  258. // Reuse the MMO.
  259. Result[Index] = *I;
  260. else {
  261. // Clone the MMO and unset the load flag.
  262. MachineMemOperand *JustStore =
  263. getMachineMemOperand((*I)->getPointerInfo(),
  264. (*I)->getFlags() & ~MachineMemOperand::MOLoad,
  265. (*I)->getSize(), (*I)->getBaseAlignment(),
  266. (*I)->getTBAAInfo());
  267. Result[Index] = JustStore;
  268. }
  269. ++Index;
  270. }
  271. }
  272. return std::make_pair(Result, Result + Num);
  273. }
  274. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  275. void MachineFunction::dump() const {
  276. print(dbgs());
  277. }
  278. #endif
  279. StringRef MachineFunction::getName() const {
  280. assert(getFunction() && "No function!");
  281. return getFunction()->getName();
  282. }
  283. void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  284. OS << "# Machine code for function " << getName() << ": ";
  285. if (RegInfo) {
  286. OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
  287. if (!RegInfo->tracksLiveness())
  288. OS << ", not tracking liveness";
  289. }
  290. OS << '\n';
  291. // Print Frame Information
  292. FrameInfo->print(*this, OS);
  293. // Print JumpTable Information
  294. if (JumpTableInfo)
  295. JumpTableInfo->print(OS);
  296. // Print Constant Pool
  297. ConstantPool->print(OS);
  298. const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
  299. if (RegInfo && !RegInfo->livein_empty()) {
  300. OS << "Function Live Ins: ";
  301. for (MachineRegisterInfo::livein_iterator
  302. I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
  303. OS << PrintReg(I->first, TRI);
  304. if (I->second)
  305. OS << " in " << PrintReg(I->second, TRI);
  306. if (llvm::next(I) != E)
  307. OS << ", ";
  308. }
  309. OS << '\n';
  310. }
  311. for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
  312. OS << '\n';
  313. BB->print(OS, Indexes);
  314. }
  315. OS << "\n# End machine code for function " << getName() << ".\n\n";
  316. }
  317. namespace llvm {
  318. template<>
  319. struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
  320. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  321. static std::string getGraphName(const MachineFunction *F) {
  322. return "CFG for '" + F->getName().str() + "' function";
  323. }
  324. std::string getNodeLabel(const MachineBasicBlock *Node,
  325. const MachineFunction *Graph) {
  326. std::string OutStr;
  327. {
  328. raw_string_ostream OSS(OutStr);
  329. if (isSimple()) {
  330. OSS << "BB#" << Node->getNumber();
  331. if (const BasicBlock *BB = Node->getBasicBlock())
  332. OSS << ": " << BB->getName();
  333. } else
  334. Node->print(OSS);
  335. }
  336. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  337. // Process string output to make it nicer...
  338. for (unsigned i = 0; i != OutStr.length(); ++i)
  339. if (OutStr[i] == '\n') { // Left justify
  340. OutStr[i] = '\\';
  341. OutStr.insert(OutStr.begin()+i+1, 'l');
  342. }
  343. return OutStr;
  344. }
  345. };
  346. }
  347. void MachineFunction::viewCFG() const
  348. {
  349. #ifndef NDEBUG
  350. ViewGraph(this, "mf" + getName());
  351. #else
  352. errs() << "MachineFunction::viewCFG is only available in debug builds on "
  353. << "systems with Graphviz or gv!\n";
  354. #endif // NDEBUG
  355. }
  356. void MachineFunction::viewCFGOnly() const
  357. {
  358. #ifndef NDEBUG
  359. ViewGraph(this, "mf" + getName(), true);
  360. #else
  361. errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
  362. << "systems with Graphviz or gv!\n";
  363. #endif // NDEBUG
  364. }
  365. /// addLiveIn - Add the specified physical register as a live-in value and
  366. /// create a corresponding virtual register for it.
  367. unsigned MachineFunction::addLiveIn(unsigned PReg,
  368. const TargetRegisterClass *RC) {
  369. MachineRegisterInfo &MRI = getRegInfo();
  370. unsigned VReg = MRI.getLiveInVirtReg(PReg);
  371. if (VReg) {
  372. assert(MRI.getRegClass(VReg) == RC && "Register class mismatch!");
  373. return VReg;
  374. }
  375. VReg = MRI.createVirtualRegister(RC);
  376. MRI.addLiveIn(PReg, VReg);
  377. return VReg;
  378. }
  379. /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
  380. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  381. /// normal 'L' label is returned.
  382. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
  383. bool isLinkerPrivate) const {
  384. assert(JumpTableInfo && "No jump tables");
  385. assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
  386. const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
  387. const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
  388. MAI.getPrivateGlobalPrefix();
  389. SmallString<60> Name;
  390. raw_svector_ostream(Name)
  391. << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
  392. return Ctx.GetOrCreateSymbol(Name.str());
  393. }
  394. /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
  395. /// base.
  396. MCSymbol *MachineFunction::getPICBaseSymbol() const {
  397. const MCAsmInfo &MAI = *Target.getMCAsmInfo();
  398. return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
  399. Twine(getFunctionNumber())+"$pb");
  400. }
  401. //===----------------------------------------------------------------------===//
  402. // MachineFrameInfo implementation
  403. //===----------------------------------------------------------------------===//
  404. /// ensureMaxAlignment - Make sure the function is at least Align bytes
  405. /// aligned.
  406. void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
  407. if (!TFI.isStackRealignable() || !RealignOption)
  408. assert(Align <= TFI.getStackAlignment() &&
  409. "For targets without stack realignment, Align is out of limit!");
  410. if (MaxAlignment < Align) MaxAlignment = Align;
  411. }
  412. /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
  413. static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
  414. unsigned StackAlign) {
  415. if (!ShouldClamp || Align <= StackAlign)
  416. return Align;
  417. DEBUG(dbgs() << "Warning: requested alignment " << Align
  418. << " exceeds the stack alignment " << StackAlign
  419. << " when stack realignment is off" << '\n');
  420. return StackAlign;
  421. }
  422. /// CreateStackObject - Create a new statically sized stack object, returning
  423. /// a nonnegative identifier to represent it.
  424. ///
  425. int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
  426. bool isSS, bool MayNeedSP, const AllocaInst *Alloca) {
  427. assert(Size != 0 && "Cannot allocate zero size stack objects!");
  428. Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
  429. Alignment, TFI.getStackAlignment());
  430. Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
  431. Alloca));
  432. int Index = (int)Objects.size() - NumFixedObjects - 1;
  433. assert(Index >= 0 && "Bad frame index!");
  434. ensureMaxAlignment(Alignment);
  435. return Index;
  436. }
  437. /// CreateSpillStackObject - Create a new statically sized stack object that
  438. /// represents a spill slot, returning a nonnegative identifier to represent
  439. /// it.
  440. ///
  441. int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
  442. unsigned Alignment) {
  443. Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
  444. Alignment, TFI.getStackAlignment());
  445. CreateStackObject(Size, Alignment, true, false);
  446. int Index = (int)Objects.size() - NumFixedObjects - 1;
  447. ensureMaxAlignment(Alignment);
  448. return Index;
  449. }
  450. /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
  451. /// variable sized object has been created. This must be created whenever a
  452. /// variable sized object is created, whether or not the index returned is
  453. /// actually used.
  454. ///
  455. int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment) {
  456. HasVarSizedObjects = true;
  457. Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
  458. Alignment, TFI.getStackAlignment());
  459. Objects.push_back(StackObject(0, Alignment, 0, false, false, true, 0));
  460. ensureMaxAlignment(Alignment);
  461. return (int)Objects.size()-NumFixedObjects-1;
  462. }
  463. /// CreateFixedObject - Create a new object at a fixed location on the stack.
  464. /// All fixed objects should be created before other objects are created for
  465. /// efficiency. By default, fixed objects are immutable. This returns an
  466. /// index with a negative value.
  467. ///
  468. int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
  469. bool Immutable) {
  470. assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
  471. // The alignment of the frame index can be determined from its offset from
  472. // the incoming frame position. If the frame object is at offset 32 and
  473. // the stack is guaranteed to be 16-byte aligned, then we know that the
  474. // object is 16-byte aligned.
  475. unsigned StackAlign = TFI.getStackAlignment();
  476. unsigned Align = MinAlign(SPOffset, StackAlign);
  477. Align = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
  478. Align, TFI.getStackAlignment());
  479. Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
  480. /*isSS*/ false,
  481. /*NeedSP*/ false,
  482. /*Alloca*/ 0));
  483. return -++NumFixedObjects;
  484. }
  485. BitVector
  486. MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
  487. assert(MBB && "MBB must be valid");
  488. const MachineFunction *MF = MBB->getParent();
  489. assert(MF && "MBB must be part of a MachineFunction");
  490. const TargetMachine &TM = MF->getTarget();
  491. const TargetRegisterInfo *TRI = TM.getRegisterInfo();
  492. BitVector BV(TRI->getNumRegs());
  493. // Before CSI is calculated, no registers are considered pristine. They can be
  494. // freely used and PEI will make sure they are saved.
  495. if (!isCalleeSavedInfoValid())
  496. return BV;
  497. for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
  498. BV.set(*CSR);
  499. // The entry MBB always has all CSRs pristine.
  500. if (MBB == &MF->front())
  501. return BV;
  502. // On other MBBs the saved CSRs are not pristine.
  503. const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
  504. for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
  505. E = CSI.end(); I != E; ++I)
  506. BV.reset(I->getReg());
  507. return BV;
  508. }
  509. unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
  510. const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
  511. const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
  512. unsigned MaxAlign = getMaxAlignment();
  513. int Offset = 0;
  514. // This code is very, very similar to PEI::calculateFrameObjectOffsets().
  515. // It really should be refactored to share code. Until then, changes
  516. // should keep in mind that there's tight coupling between the two.
  517. for (int i = getObjectIndexBegin(); i != 0; ++i) {
  518. int FixedOff = -getObjectOffset(i);
  519. if (FixedOff > Offset) Offset = FixedOff;
  520. }
  521. for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
  522. if (isDeadObjectIndex(i))
  523. continue;
  524. Offset += getObjectSize(i);
  525. unsigned Align = getObjectAlignment(i);
  526. // Adjust to alignment boundary
  527. Offset = (Offset+Align-1)/Align*Align;
  528. MaxAlign = std::max(Align, MaxAlign);
  529. }
  530. if (adjustsStack() && TFI->hasReservedCallFrame(MF))
  531. Offset += getMaxCallFrameSize();
  532. // Round up the size to a multiple of the alignment. If the function has
  533. // any calls or alloca's, align to the target's StackAlignment value to
  534. // ensure that the callee's frame or the alloca data is suitably aligned;
  535. // otherwise, for leaf functions, align to the TransientStackAlignment
  536. // value.
  537. unsigned StackAlign;
  538. if (adjustsStack() || hasVarSizedObjects() ||
  539. (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
  540. StackAlign = TFI->getStackAlignment();
  541. else
  542. StackAlign = TFI->getTransientStackAlignment();
  543. // If the frame pointer is eliminated, all frame offsets will be relative to
  544. // SP not FP. Align to MaxAlign so this works.
  545. StackAlign = std::max(StackAlign, MaxAlign);
  546. unsigned AlignMask = StackAlign - 1;
  547. Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
  548. return (unsigned)Offset;
  549. }
  550. void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
  551. if (Objects.empty()) return;
  552. const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
  553. int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
  554. OS << "Frame Objects:\n";
  555. for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
  556. const StackObject &SO = Objects[i];
  557. OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
  558. if (SO.Size == ~0ULL) {
  559. OS << "dead\n";
  560. continue;
  561. }
  562. if (SO.Size == 0)
  563. OS << "variable sized";
  564. else
  565. OS << "size=" << SO.Size;
  566. OS << ", align=" << SO.Alignment;
  567. if (i < NumFixedObjects)
  568. OS << ", fixed";
  569. if (i < NumFixedObjects || SO.SPOffset != -1) {
  570. int64_t Off = SO.SPOffset - ValOffset;
  571. OS << ", at location [SP";
  572. if (Off > 0)
  573. OS << "+" << Off;
  574. else if (Off < 0)
  575. OS << Off;
  576. OS << "]";
  577. }
  578. OS << "\n";
  579. }
  580. }
  581. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  582. void MachineFrameInfo::dump(const MachineFunction &MF) const {
  583. print(MF, dbgs());
  584. }
  585. #endif
  586. //===----------------------------------------------------------------------===//
  587. // MachineJumpTableInfo implementation
  588. //===----------------------------------------------------------------------===//
  589. /// getEntrySize - Return the size of each entry in the jump table.
  590. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
  591. // The size of a jump table entry is 4 bytes unless the entry is just the
  592. // address of a block, in which case it is the pointer size.
  593. switch (getEntryKind()) {
  594. case MachineJumpTableInfo::EK_BlockAddress:
  595. return TD.getPointerSize();
  596. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  597. return 8;
  598. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  599. case MachineJumpTableInfo::EK_LabelDifference32:
  600. case MachineJumpTableInfo::EK_Custom32:
  601. return 4;
  602. case MachineJumpTableInfo::EK_Inline:
  603. return 0;
  604. }
  605. llvm_unreachable("Unknown jump table encoding!");
  606. }
  607. /// getEntryAlignment - Return the alignment of each entry in the jump table.
  608. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
  609. // The alignment of a jump table entry is the alignment of int32 unless the
  610. // entry is just the address of a block, in which case it is the pointer
  611. // alignment.
  612. switch (getEntryKind()) {
  613. case MachineJumpTableInfo::EK_BlockAddress:
  614. return TD.getPointerABIAlignment();
  615. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  616. return TD.getABIIntegerTypeAlignment(64);
  617. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  618. case MachineJumpTableInfo::EK_LabelDifference32:
  619. case MachineJumpTableInfo::EK_Custom32:
  620. return TD.getABIIntegerTypeAlignment(32);
  621. case MachineJumpTableInfo::EK_Inline:
  622. return 1;
  623. }
  624. llvm_unreachable("Unknown jump table encoding!");
  625. }
  626. /// createJumpTableIndex - Create a new jump table entry in the jump table info.
  627. ///
  628. unsigned MachineJumpTableInfo::createJumpTableIndex(
  629. const std::vector<MachineBasicBlock*> &DestBBs) {
  630. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  631. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  632. return JumpTables.size()-1;
  633. }
  634. /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
  635. /// the jump tables to branch to New instead.
  636. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  637. MachineBasicBlock *New) {
  638. assert(Old != New && "Not making a change?");
  639. bool MadeChange = false;
  640. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  641. ReplaceMBBInJumpTable(i, Old, New);
  642. return MadeChange;
  643. }
  644. /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
  645. /// the jump table to branch to New instead.
  646. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  647. MachineBasicBlock *Old,
  648. MachineBasicBlock *New) {
  649. assert(Old != New && "Not making a change?");
  650. bool MadeChange = false;
  651. MachineJumpTableEntry &JTE = JumpTables[Idx];
  652. for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
  653. if (JTE.MBBs[j] == Old) {
  654. JTE.MBBs[j] = New;
  655. MadeChange = true;
  656. }
  657. return MadeChange;
  658. }
  659. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  660. if (JumpTables.empty()) return;
  661. OS << "Jump Tables:\n";
  662. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  663. OS << " jt#" << i << ": ";
  664. for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
  665. OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
  666. }
  667. OS << '\n';
  668. }
  669. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  670. void MachineJumpTableInfo::dump() const { print(dbgs()); }
  671. #endif
  672. //===----------------------------------------------------------------------===//
  673. // MachineConstantPool implementation
  674. //===----------------------------------------------------------------------===//
  675. void MachineConstantPoolValue::anchor() { }
  676. Type *MachineConstantPoolEntry::getType() const {
  677. if (isMachineConstantPoolEntry())
  678. return Val.MachineCPVal->getType();
  679. return Val.ConstVal->getType();
  680. }
  681. unsigned MachineConstantPoolEntry::getRelocationInfo() const {
  682. if (isMachineConstantPoolEntry())
  683. return Val.MachineCPVal->getRelocationInfo();
  684. return Val.ConstVal->getRelocationInfo();
  685. }
  686. MachineConstantPool::~MachineConstantPool() {
  687. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  688. if (Constants[i].isMachineConstantPoolEntry())
  689. delete Constants[i].Val.MachineCPVal;
  690. for (DenseSet<MachineConstantPoolValue*>::iterator I =
  691. MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
  692. I != E; ++I)
  693. delete *I;
  694. }
  695. /// CanShareConstantPoolEntry - Test whether the given two constants
  696. /// can be allocated the same constant pool entry.
  697. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  698. const DataLayout *TD) {
  699. // Handle the trivial case quickly.
  700. if (A == B) return true;
  701. // If they have the same type but weren't the same constant, quickly
  702. // reject them.
  703. if (A->getType() == B->getType()) return false;
  704. // We can't handle structs or arrays.
  705. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
  706. isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
  707. return false;
  708. // For now, only support constants with the same size.
  709. uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
  710. if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
  711. StoreSize > 128)
  712. return false;
  713. Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
  714. // Try constant folding a bitcast of both instructions to an integer. If we
  715. // get two identical ConstantInt's, then we are good to share them. We use
  716. // the constant folding APIs to do this so that we get the benefit of
  717. // DataLayout.
  718. if (isa<PointerType>(A->getType()))
  719. A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
  720. const_cast<Constant*>(A), TD);
  721. else if (A->getType() != IntTy)
  722. A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
  723. const_cast<Constant*>(A), TD);
  724. if (isa<PointerType>(B->getType()))
  725. B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
  726. const_cast<Constant*>(B), TD);
  727. else if (B->getType() != IntTy)
  728. B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
  729. const_cast<Constant*>(B), TD);
  730. return A == B;
  731. }
  732. /// getConstantPoolIndex - Create a new entry in the constant pool or return
  733. /// an existing one. User must specify the log2 of the minimum required
  734. /// alignment for the object.
  735. ///
  736. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  737. unsigned Alignment) {
  738. assert(Alignment && "Alignment must be specified!");
  739. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  740. // Check to see if we already have this constant.
  741. //
  742. // FIXME, this could be made much more efficient for large constant pools.
  743. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  744. if (!Constants[i].isMachineConstantPoolEntry() &&
  745. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
  746. if ((unsigned)Constants[i].getAlignment() < Alignment)
  747. Constants[i].Alignment = Alignment;
  748. return i;
  749. }
  750. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  751. return Constants.size()-1;
  752. }
  753. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  754. unsigned Alignment) {
  755. assert(Alignment && "Alignment must be specified!");
  756. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  757. // Check to see if we already have this constant.
  758. //
  759. // FIXME, this could be made much more efficient for large constant pools.
  760. int Idx = V->getExistingMachineCPValue(this, Alignment);
  761. if (Idx != -1) {
  762. MachineCPVsSharingEntries.insert(V);
  763. return (unsigned)Idx;
  764. }
  765. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  766. return Constants.size()-1;
  767. }
  768. void MachineConstantPool::print(raw_ostream &OS) const {
  769. if (Constants.empty()) return;
  770. OS << "Constant Pool:\n";
  771. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  772. OS << " cp#" << i << ": ";
  773. if (Constants[i].isMachineConstantPoolEntry())
  774. Constants[i].Val.MachineCPVal->print(OS);
  775. else
  776. OS << *(const Value*)Constants[i].Val.ConstVal;
  777. OS << ", align=" << Constants[i].getAlignment();
  778. OS << "\n";
  779. }
  780. }
  781. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  782. void MachineConstantPool::dump() const { print(dbgs()); }
  783. #endif