MachineFunction.cpp 27 KB

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