MachineFunction.cpp 30 KB

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