MachineFunction.cpp 36 KB

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