MachineFunction.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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);
  53. else
  54. RegInfo = 0;
  55. MFInfo = 0;
  56. FrameInfo =
  57. new (Allocator) MachineFrameInfo(TM,!F->hasFnAttribute("no-realign-stack"));
  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);
  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. const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
  373. (void)VRegRC;
  374. // A physical register can be added several times.
  375. // Between two calls, the register class of the related virtual register
  376. // may have been constrained to match some operation constraints.
  377. // In that case, check that the current register class includes the
  378. // physical register and is a sub class of the specified RC.
  379. assert((VRegRC == RC || (VRegRC->contains(PReg) &&
  380. RC->hasSubClassEq(VRegRC))) &&
  381. "Register class mismatch!");
  382. return VReg;
  383. }
  384. VReg = MRI.createVirtualRegister(RC);
  385. MRI.addLiveIn(PReg, VReg);
  386. return VReg;
  387. }
  388. /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
  389. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  390. /// normal 'L' label is returned.
  391. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
  392. bool isLinkerPrivate) const {
  393. const DataLayout *DL = getTarget().getDataLayout();
  394. assert(JumpTableInfo && "No jump tables");
  395. assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
  396. const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
  397. DL->getPrivateGlobalPrefix();
  398. SmallString<60> Name;
  399. raw_svector_ostream(Name)
  400. << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
  401. return Ctx.GetOrCreateSymbol(Name.str());
  402. }
  403. /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
  404. /// base.
  405. MCSymbol *MachineFunction::getPICBaseSymbol() const {
  406. const DataLayout *DL = getTarget().getDataLayout();
  407. return Ctx.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
  408. Twine(getFunctionNumber())+"$pb");
  409. }
  410. //===----------------------------------------------------------------------===//
  411. // MachineFrameInfo implementation
  412. //===----------------------------------------------------------------------===//
  413. const TargetFrameLowering *MachineFrameInfo::getFrameLowering() const {
  414. return TM.getFrameLowering();
  415. }
  416. /// ensureMaxAlignment - Make sure the function is at least Align bytes
  417. /// aligned.
  418. void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
  419. if (!getFrameLowering()->isStackRealignable() || !RealignOption)
  420. assert(Align <= getFrameLowering()->getStackAlignment() &&
  421. "For targets without stack realignment, Align is out of limit!");
  422. if (MaxAlignment < Align) MaxAlignment = Align;
  423. }
  424. /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
  425. static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
  426. unsigned StackAlign) {
  427. if (!ShouldClamp || Align <= StackAlign)
  428. return Align;
  429. DEBUG(dbgs() << "Warning: requested alignment " << Align
  430. << " exceeds the stack alignment " << StackAlign
  431. << " when stack realignment is off" << '\n');
  432. return StackAlign;
  433. }
  434. /// CreateStackObject - Create a new statically sized stack object, returning
  435. /// a nonnegative identifier to represent it.
  436. ///
  437. int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
  438. bool isSS, const AllocaInst *Alloca) {
  439. assert(Size != 0 && "Cannot allocate zero size stack objects!");
  440. Alignment =
  441. clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
  442. !RealignOption,
  443. Alignment, getFrameLowering()->getStackAlignment());
  444. Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca));
  445. int Index = (int)Objects.size() - NumFixedObjects - 1;
  446. assert(Index >= 0 && "Bad frame index!");
  447. ensureMaxAlignment(Alignment);
  448. return Index;
  449. }
  450. /// CreateSpillStackObject - Create a new statically sized stack object that
  451. /// represents a spill slot, returning a nonnegative identifier to represent
  452. /// it.
  453. ///
  454. int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
  455. unsigned Alignment) {
  456. Alignment =
  457. clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
  458. !RealignOption,
  459. Alignment, getFrameLowering()->getStackAlignment());
  460. CreateStackObject(Size, Alignment, true);
  461. int Index = (int)Objects.size() - NumFixedObjects - 1;
  462. ensureMaxAlignment(Alignment);
  463. return Index;
  464. }
  465. /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
  466. /// variable sized object has been created. This must be created whenever a
  467. /// variable sized object is created, whether or not the index returned is
  468. /// actually used.
  469. ///
  470. int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
  471. const AllocaInst *Alloca) {
  472. HasVarSizedObjects = true;
  473. Alignment =
  474. clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
  475. !RealignOption,
  476. Alignment, getFrameLowering()->getStackAlignment());
  477. Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca));
  478. ensureMaxAlignment(Alignment);
  479. return (int)Objects.size()-NumFixedObjects-1;
  480. }
  481. /// CreateFixedObject - Create a new object at a fixed location on the stack.
  482. /// All fixed objects should be created before other objects are created for
  483. /// efficiency. By default, fixed objects are immutable. This returns an
  484. /// index with a negative value.
  485. ///
  486. int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
  487. bool Immutable) {
  488. assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
  489. // The alignment of the frame index can be determined from its offset from
  490. // the incoming frame position. If the frame object is at offset 32 and
  491. // the stack is guaranteed to be 16-byte aligned, then we know that the
  492. // object is 16-byte aligned.
  493. unsigned StackAlign = getFrameLowering()->getStackAlignment();
  494. unsigned Align = MinAlign(SPOffset, StackAlign);
  495. Align =
  496. clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
  497. !RealignOption,
  498. Align, getFrameLowering()->getStackAlignment());
  499. Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
  500. /*isSS*/ false,
  501. /*Alloca*/ 0));
  502. return -++NumFixedObjects;
  503. }
  504. BitVector
  505. MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
  506. assert(MBB && "MBB must be valid");
  507. const MachineFunction *MF = MBB->getParent();
  508. assert(MF && "MBB must be part of a MachineFunction");
  509. const TargetMachine &TM = MF->getTarget();
  510. const TargetRegisterInfo *TRI = TM.getRegisterInfo();
  511. BitVector BV(TRI->getNumRegs());
  512. // Before CSI is calculated, no registers are considered pristine. They can be
  513. // freely used and PEI will make sure they are saved.
  514. if (!isCalleeSavedInfoValid())
  515. return BV;
  516. for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
  517. BV.set(*CSR);
  518. // The entry MBB always has all CSRs pristine.
  519. if (MBB == &MF->front())
  520. return BV;
  521. // On other MBBs the saved CSRs are not pristine.
  522. const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
  523. for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
  524. E = CSI.end(); I != E; ++I)
  525. BV.reset(I->getReg());
  526. return BV;
  527. }
  528. unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
  529. const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
  530. const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
  531. unsigned MaxAlign = getMaxAlignment();
  532. int Offset = 0;
  533. // This code is very, very similar to PEI::calculateFrameObjectOffsets().
  534. // It really should be refactored to share code. Until then, changes
  535. // should keep in mind that there's tight coupling between the two.
  536. for (int i = getObjectIndexBegin(); i != 0; ++i) {
  537. int FixedOff = -getObjectOffset(i);
  538. if (FixedOff > Offset) Offset = FixedOff;
  539. }
  540. for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
  541. if (isDeadObjectIndex(i))
  542. continue;
  543. Offset += getObjectSize(i);
  544. unsigned Align = getObjectAlignment(i);
  545. // Adjust to alignment boundary
  546. Offset = (Offset+Align-1)/Align*Align;
  547. MaxAlign = std::max(Align, MaxAlign);
  548. }
  549. if (adjustsStack() && TFI->hasReservedCallFrame(MF))
  550. Offset += getMaxCallFrameSize();
  551. // Round up the size to a multiple of the alignment. If the function has
  552. // any calls or alloca's, align to the target's StackAlignment value to
  553. // ensure that the callee's frame or the alloca data is suitably aligned;
  554. // otherwise, for leaf functions, align to the TransientStackAlignment
  555. // value.
  556. unsigned StackAlign;
  557. if (adjustsStack() || hasVarSizedObjects() ||
  558. (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
  559. StackAlign = TFI->getStackAlignment();
  560. else
  561. StackAlign = TFI->getTransientStackAlignment();
  562. // If the frame pointer is eliminated, all frame offsets will be relative to
  563. // SP not FP. Align to MaxAlign so this works.
  564. StackAlign = std::max(StackAlign, MaxAlign);
  565. unsigned AlignMask = StackAlign - 1;
  566. Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
  567. return (unsigned)Offset;
  568. }
  569. void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
  570. if (Objects.empty()) return;
  571. const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
  572. int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
  573. OS << "Frame Objects:\n";
  574. for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
  575. const StackObject &SO = Objects[i];
  576. OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
  577. if (SO.Size == ~0ULL) {
  578. OS << "dead\n";
  579. continue;
  580. }
  581. if (SO.Size == 0)
  582. OS << "variable sized";
  583. else
  584. OS << "size=" << SO.Size;
  585. OS << ", align=" << SO.Alignment;
  586. if (i < NumFixedObjects)
  587. OS << ", fixed";
  588. if (i < NumFixedObjects || SO.SPOffset != -1) {
  589. int64_t Off = SO.SPOffset - ValOffset;
  590. OS << ", at location [SP";
  591. if (Off > 0)
  592. OS << "+" << Off;
  593. else if (Off < 0)
  594. OS << Off;
  595. OS << "]";
  596. }
  597. OS << "\n";
  598. }
  599. }
  600. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  601. void MachineFrameInfo::dump(const MachineFunction &MF) const {
  602. print(MF, dbgs());
  603. }
  604. #endif
  605. //===----------------------------------------------------------------------===//
  606. // MachineJumpTableInfo implementation
  607. //===----------------------------------------------------------------------===//
  608. /// getEntrySize - Return the size of each entry in the jump table.
  609. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
  610. // The size of a jump table entry is 4 bytes unless the entry is just the
  611. // address of a block, in which case it is the pointer size.
  612. switch (getEntryKind()) {
  613. case MachineJumpTableInfo::EK_BlockAddress:
  614. return TD.getPointerSize();
  615. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  616. return 8;
  617. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  618. case MachineJumpTableInfo::EK_LabelDifference32:
  619. case MachineJumpTableInfo::EK_Custom32:
  620. return 4;
  621. case MachineJumpTableInfo::EK_Inline:
  622. return 0;
  623. }
  624. llvm_unreachable("Unknown jump table encoding!");
  625. }
  626. /// getEntryAlignment - Return the alignment of each entry in the jump table.
  627. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
  628. // The alignment of a jump table entry is the alignment of int32 unless the
  629. // entry is just the address of a block, in which case it is the pointer
  630. // alignment.
  631. switch (getEntryKind()) {
  632. case MachineJumpTableInfo::EK_BlockAddress:
  633. return TD.getPointerABIAlignment();
  634. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  635. return TD.getABIIntegerTypeAlignment(64);
  636. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  637. case MachineJumpTableInfo::EK_LabelDifference32:
  638. case MachineJumpTableInfo::EK_Custom32:
  639. return TD.getABIIntegerTypeAlignment(32);
  640. case MachineJumpTableInfo::EK_Inline:
  641. return 1;
  642. }
  643. llvm_unreachable("Unknown jump table encoding!");
  644. }
  645. /// createJumpTableIndex - Create a new jump table entry in the jump table info.
  646. ///
  647. unsigned MachineJumpTableInfo::createJumpTableIndex(
  648. const std::vector<MachineBasicBlock*> &DestBBs) {
  649. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  650. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  651. return JumpTables.size()-1;
  652. }
  653. /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
  654. /// the jump tables to branch to New instead.
  655. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  656. MachineBasicBlock *New) {
  657. assert(Old != New && "Not making a change?");
  658. bool MadeChange = false;
  659. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  660. ReplaceMBBInJumpTable(i, Old, New);
  661. return MadeChange;
  662. }
  663. /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
  664. /// the jump table to branch to New instead.
  665. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  666. MachineBasicBlock *Old,
  667. MachineBasicBlock *New) {
  668. assert(Old != New && "Not making a change?");
  669. bool MadeChange = false;
  670. MachineJumpTableEntry &JTE = JumpTables[Idx];
  671. for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
  672. if (JTE.MBBs[j] == Old) {
  673. JTE.MBBs[j] = New;
  674. MadeChange = true;
  675. }
  676. return MadeChange;
  677. }
  678. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  679. if (JumpTables.empty()) return;
  680. OS << "Jump Tables:\n";
  681. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  682. OS << " jt#" << i << ": ";
  683. for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
  684. OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
  685. }
  686. OS << '\n';
  687. }
  688. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  689. void MachineJumpTableInfo::dump() const { print(dbgs()); }
  690. #endif
  691. //===----------------------------------------------------------------------===//
  692. // MachineConstantPool implementation
  693. //===----------------------------------------------------------------------===//
  694. void MachineConstantPoolValue::anchor() { }
  695. const DataLayout *MachineConstantPool::getDataLayout() const {
  696. return TM.getDataLayout();
  697. }
  698. Type *MachineConstantPoolEntry::getType() const {
  699. if (isMachineConstantPoolEntry())
  700. return Val.MachineCPVal->getType();
  701. return Val.ConstVal->getType();
  702. }
  703. unsigned MachineConstantPoolEntry::getRelocationInfo() const {
  704. if (isMachineConstantPoolEntry())
  705. return Val.MachineCPVal->getRelocationInfo();
  706. return Val.ConstVal->getRelocationInfo();
  707. }
  708. MachineConstantPool::~MachineConstantPool() {
  709. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  710. if (Constants[i].isMachineConstantPoolEntry())
  711. delete Constants[i].Val.MachineCPVal;
  712. for (DenseSet<MachineConstantPoolValue*>::iterator I =
  713. MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
  714. I != E; ++I)
  715. delete *I;
  716. }
  717. /// CanShareConstantPoolEntry - Test whether the given two constants
  718. /// can be allocated the same constant pool entry.
  719. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  720. const DataLayout *TD) {
  721. // Handle the trivial case quickly.
  722. if (A == B) return true;
  723. // If they have the same type but weren't the same constant, quickly
  724. // reject them.
  725. if (A->getType() == B->getType()) return false;
  726. // We can't handle structs or arrays.
  727. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
  728. isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
  729. return false;
  730. // For now, only support constants with the same size.
  731. uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
  732. if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
  733. StoreSize > 128)
  734. return false;
  735. Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
  736. // Try constant folding a bitcast of both instructions to an integer. If we
  737. // get two identical ConstantInt's, then we are good to share them. We use
  738. // the constant folding APIs to do this so that we get the benefit of
  739. // DataLayout.
  740. if (isa<PointerType>(A->getType()))
  741. A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
  742. const_cast<Constant*>(A), TD);
  743. else if (A->getType() != IntTy)
  744. A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
  745. const_cast<Constant*>(A), TD);
  746. if (isa<PointerType>(B->getType()))
  747. B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
  748. const_cast<Constant*>(B), TD);
  749. else if (B->getType() != IntTy)
  750. B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
  751. const_cast<Constant*>(B), TD);
  752. return A == B;
  753. }
  754. /// getConstantPoolIndex - Create a new entry in the constant pool or return
  755. /// an existing one. User must specify the log2 of the minimum required
  756. /// alignment for the object.
  757. ///
  758. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  759. unsigned Alignment) {
  760. assert(Alignment && "Alignment must be specified!");
  761. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  762. // Check to see if we already have this constant.
  763. //
  764. // FIXME, this could be made much more efficient for large constant pools.
  765. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  766. if (!Constants[i].isMachineConstantPoolEntry() &&
  767. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
  768. getDataLayout())) {
  769. if ((unsigned)Constants[i].getAlignment() < Alignment)
  770. Constants[i].Alignment = Alignment;
  771. return i;
  772. }
  773. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  774. return Constants.size()-1;
  775. }
  776. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  777. unsigned Alignment) {
  778. assert(Alignment && "Alignment must be specified!");
  779. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  780. // Check to see if we already have this constant.
  781. //
  782. // FIXME, this could be made much more efficient for large constant pools.
  783. int Idx = V->getExistingMachineCPValue(this, Alignment);
  784. if (Idx != -1) {
  785. MachineCPVsSharingEntries.insert(V);
  786. return (unsigned)Idx;
  787. }
  788. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  789. return Constants.size()-1;
  790. }
  791. void MachineConstantPool::print(raw_ostream &OS) const {
  792. if (Constants.empty()) return;
  793. OS << "Constant Pool:\n";
  794. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  795. OS << " cp#" << i << ": ";
  796. if (Constants[i].isMachineConstantPoolEntry())
  797. Constants[i].Val.MachineCPVal->print(OS);
  798. else
  799. Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
  800. OS << ", align=" << Constants[i].getAlignment();
  801. OS << "\n";
  802. }
  803. }
  804. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  805. void MachineConstantPool::dump() const { print(dbgs()); }
  806. #endif