MachineFunction.cpp 26 KB

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