MachineFunction.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. //===- MachineFunction.cpp ------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Collect native machine code information for a function. This allows
  10. // target-specific information about the generated code to be stored with each
  11. // function.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/MachineFunction.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/DenseSet.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/Analysis/ConstantFolding.h"
  24. #include "llvm/Analysis/EHPersonalities.h"
  25. #include "llvm/CodeGen/MachineBasicBlock.h"
  26. #include "llvm/CodeGen/MachineConstantPool.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  30. #include "llvm/CodeGen/MachineMemOperand.h"
  31. #include "llvm/CodeGen/MachineModuleInfo.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/PseudoSourceValue.h"
  34. #include "llvm/CodeGen/TargetFrameLowering.h"
  35. #include "llvm/CodeGen/TargetLowering.h"
  36. #include "llvm/CodeGen/TargetRegisterInfo.h"
  37. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  38. #include "llvm/CodeGen/WasmEHFuncInfo.h"
  39. #include "llvm/CodeGen/WinEHFuncInfo.h"
  40. #include "llvm/Config/llvm-config.h"
  41. #include "llvm/IR/Attributes.h"
  42. #include "llvm/IR/BasicBlock.h"
  43. #include "llvm/IR/Constant.h"
  44. #include "llvm/IR/DataLayout.h"
  45. #include "llvm/IR/DebugInfoMetadata.h"
  46. #include "llvm/IR/DerivedTypes.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/GlobalValue.h"
  49. #include "llvm/IR/Instruction.h"
  50. #include "llvm/IR/Instructions.h"
  51. #include "llvm/IR/Metadata.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/IR/ModuleSlotTracker.h"
  54. #include "llvm/IR/Value.h"
  55. #include "llvm/MC/MCContext.h"
  56. #include "llvm/MC/MCSymbol.h"
  57. #include "llvm/MC/SectionKind.h"
  58. #include "llvm/Support/Casting.h"
  59. #include "llvm/Support/CommandLine.h"
  60. #include "llvm/Support/Compiler.h"
  61. #include "llvm/Support/DOTGraphTraits.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/GraphWriter.h"
  65. #include "llvm/Support/raw_ostream.h"
  66. #include "llvm/Target/TargetMachine.h"
  67. #include <algorithm>
  68. #include <cassert>
  69. #include <cstddef>
  70. #include <cstdint>
  71. #include <iterator>
  72. #include <string>
  73. #include <utility>
  74. #include <vector>
  75. using namespace llvm;
  76. #define DEBUG_TYPE "codegen"
  77. static cl::opt<unsigned> AlignAllFunctions(
  78. "align-all-functions",
  79. cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
  80. "means align on 16B boundaries)."),
  81. cl::init(0), cl::Hidden);
  82. static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
  83. using P = MachineFunctionProperties::Property;
  84. switch(Prop) {
  85. case P::FailedISel: return "FailedISel";
  86. case P::IsSSA: return "IsSSA";
  87. case P::Legalized: return "Legalized";
  88. case P::NoPHIs: return "NoPHIs";
  89. case P::NoVRegs: return "NoVRegs";
  90. case P::RegBankSelected: return "RegBankSelected";
  91. case P::Selected: return "Selected";
  92. case P::TracksLiveness: return "TracksLiveness";
  93. }
  94. llvm_unreachable("Invalid machine function property");
  95. }
  96. // Pin the vtable to this file.
  97. void MachineFunction::Delegate::anchor() {}
  98. void MachineFunctionProperties::print(raw_ostream &OS) const {
  99. const char *Separator = "";
  100. for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
  101. if (!Properties[I])
  102. continue;
  103. OS << Separator << getPropertyName(static_cast<Property>(I));
  104. Separator = ", ";
  105. }
  106. }
  107. //===----------------------------------------------------------------------===//
  108. // MachineFunction implementation
  109. //===----------------------------------------------------------------------===//
  110. // Out-of-line virtual method.
  111. MachineFunctionInfo::~MachineFunctionInfo() = default;
  112. void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
  113. MBB->getParent()->DeleteMachineBasicBlock(MBB);
  114. }
  115. static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
  116. const Function &F) {
  117. if (F.hasFnAttribute(Attribute::StackAlignment))
  118. return F.getFnStackAlignment();
  119. return STI->getFrameLowering()->getStackAlignment();
  120. }
  121. MachineFunction::MachineFunction(const Function &F,
  122. const LLVMTargetMachine &Target,
  123. const TargetSubtargetInfo &STI,
  124. unsigned FunctionNum, MachineModuleInfo &mmi)
  125. : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
  126. FunctionNumber = FunctionNum;
  127. init();
  128. }
  129. void MachineFunction::handleInsertion(MachineInstr &MI) {
  130. if (TheDelegate)
  131. TheDelegate->MF_HandleInsertion(MI);
  132. }
  133. void MachineFunction::handleRemoval(MachineInstr &MI) {
  134. if (TheDelegate)
  135. TheDelegate->MF_HandleRemoval(MI);
  136. }
  137. void MachineFunction::init() {
  138. // Assume the function starts in SSA form with correct liveness.
  139. Properties.set(MachineFunctionProperties::Property::IsSSA);
  140. Properties.set(MachineFunctionProperties::Property::TracksLiveness);
  141. if (STI->getRegisterInfo())
  142. RegInfo = new (Allocator) MachineRegisterInfo(this);
  143. else
  144. RegInfo = nullptr;
  145. MFInfo = nullptr;
  146. // We can realign the stack if the target supports it and the user hasn't
  147. // explicitly asked us not to.
  148. bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
  149. !F.hasFnAttribute("no-realign-stack");
  150. FrameInfo = new (Allocator) MachineFrameInfo(
  151. getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
  152. /*ForcedRealign=*/CanRealignSP &&
  153. F.hasFnAttribute(Attribute::StackAlignment));
  154. if (F.hasFnAttribute(Attribute::StackAlignment))
  155. FrameInfo->ensureMaxAlignment(F.getFnStackAlignment());
  156. ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
  157. LogAlignment = STI->getTargetLowering()->getMinFunctionLogAlignment();
  158. // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
  159. // FIXME: Use Function::hasOptSize().
  160. if (!F.hasFnAttribute(Attribute::OptimizeForSize))
  161. LogAlignment = std::max(
  162. LogAlignment, STI->getTargetLowering()->getPrefFunctionLogAlignment());
  163. if (AlignAllFunctions)
  164. LogAlignment = AlignAllFunctions;
  165. JumpTableInfo = nullptr;
  166. if (isFuncletEHPersonality(classifyEHPersonality(
  167. F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
  168. WinEHInfo = new (Allocator) WinEHFuncInfo();
  169. }
  170. if (isScopedEHPersonality(classifyEHPersonality(
  171. F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
  172. WasmEHInfo = new (Allocator) WasmEHFuncInfo();
  173. }
  174. assert(Target.isCompatibleDataLayout(getDataLayout()) &&
  175. "Can't create a MachineFunction using a Module with a "
  176. "Target-incompatible DataLayout attached\n");
  177. PSVManager =
  178. std::make_unique<PseudoSourceValueManager>(*(getSubtarget().
  179. getInstrInfo()));
  180. }
  181. MachineFunction::~MachineFunction() {
  182. clear();
  183. }
  184. void MachineFunction::clear() {
  185. Properties.reset();
  186. // Don't call destructors on MachineInstr and MachineOperand. All of their
  187. // memory comes from the BumpPtrAllocator which is about to be purged.
  188. //
  189. // Do call MachineBasicBlock destructors, it contains std::vectors.
  190. for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
  191. I->Insts.clearAndLeakNodesUnsafely();
  192. MBBNumbering.clear();
  193. InstructionRecycler.clear(Allocator);
  194. OperandRecycler.clear(Allocator);
  195. BasicBlockRecycler.clear(Allocator);
  196. CodeViewAnnotations.clear();
  197. VariableDbgInfos.clear();
  198. if (RegInfo) {
  199. RegInfo->~MachineRegisterInfo();
  200. Allocator.Deallocate(RegInfo);
  201. }
  202. if (MFInfo) {
  203. MFInfo->~MachineFunctionInfo();
  204. Allocator.Deallocate(MFInfo);
  205. }
  206. FrameInfo->~MachineFrameInfo();
  207. Allocator.Deallocate(FrameInfo);
  208. ConstantPool->~MachineConstantPool();
  209. Allocator.Deallocate(ConstantPool);
  210. if (JumpTableInfo) {
  211. JumpTableInfo->~MachineJumpTableInfo();
  212. Allocator.Deallocate(JumpTableInfo);
  213. }
  214. if (WinEHInfo) {
  215. WinEHInfo->~WinEHFuncInfo();
  216. Allocator.Deallocate(WinEHInfo);
  217. }
  218. if (WasmEHInfo) {
  219. WasmEHInfo->~WasmEHFuncInfo();
  220. Allocator.Deallocate(WasmEHInfo);
  221. }
  222. }
  223. const DataLayout &MachineFunction::getDataLayout() const {
  224. return F.getParent()->getDataLayout();
  225. }
  226. /// Get the JumpTableInfo for this function.
  227. /// If it does not already exist, allocate one.
  228. MachineJumpTableInfo *MachineFunction::
  229. getOrCreateJumpTableInfo(unsigned EntryKind) {
  230. if (JumpTableInfo) return JumpTableInfo;
  231. JumpTableInfo = new (Allocator)
  232. MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
  233. return JumpTableInfo;
  234. }
  235. /// Should we be emitting segmented stack stuff for the function
  236. bool MachineFunction::shouldSplitStack() const {
  237. return getFunction().hasFnAttribute("split-stack");
  238. }
  239. LLVM_NODISCARD unsigned
  240. MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
  241. FrameInstructions.push_back(Inst);
  242. return FrameInstructions.size() - 1;
  243. }
  244. /// This discards all of the MachineBasicBlock numbers and recomputes them.
  245. /// This guarantees that the MBB numbers are sequential, dense, and match the
  246. /// ordering of the blocks within the function. If a specific MachineBasicBlock
  247. /// is specified, only that block and those after it are renumbered.
  248. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
  249. if (empty()) { MBBNumbering.clear(); return; }
  250. MachineFunction::iterator MBBI, E = end();
  251. if (MBB == nullptr)
  252. MBBI = begin();
  253. else
  254. MBBI = MBB->getIterator();
  255. // Figure out the block number this should have.
  256. unsigned BlockNo = 0;
  257. if (MBBI != begin())
  258. BlockNo = std::prev(MBBI)->getNumber() + 1;
  259. for (; MBBI != E; ++MBBI, ++BlockNo) {
  260. if (MBBI->getNumber() != (int)BlockNo) {
  261. // Remove use of the old number.
  262. if (MBBI->getNumber() != -1) {
  263. assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
  264. "MBB number mismatch!");
  265. MBBNumbering[MBBI->getNumber()] = nullptr;
  266. }
  267. // If BlockNo is already taken, set that block's number to -1.
  268. if (MBBNumbering[BlockNo])
  269. MBBNumbering[BlockNo]->setNumber(-1);
  270. MBBNumbering[BlockNo] = &*MBBI;
  271. MBBI->setNumber(BlockNo);
  272. }
  273. }
  274. // Okay, all the blocks are renumbered. If we have compactified the block
  275. // numbering, shrink MBBNumbering now.
  276. assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
  277. MBBNumbering.resize(BlockNo);
  278. }
  279. /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
  280. MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
  281. const DebugLoc &DL,
  282. bool NoImp) {
  283. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  284. MachineInstr(*this, MCID, DL, NoImp);
  285. }
  286. /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
  287. /// identical in all ways except the instruction has no parent, prev, or next.
  288. MachineInstr *
  289. MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
  290. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  291. MachineInstr(*this, *Orig);
  292. }
  293. MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
  294. MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
  295. MachineInstr *FirstClone = nullptr;
  296. MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
  297. while (true) {
  298. MachineInstr *Cloned = CloneMachineInstr(&*I);
  299. MBB.insert(InsertBefore, Cloned);
  300. if (FirstClone == nullptr) {
  301. FirstClone = Cloned;
  302. } else {
  303. Cloned->bundleWithPred();
  304. }
  305. if (!I->isBundledWithSucc())
  306. break;
  307. ++I;
  308. }
  309. return *FirstClone;
  310. }
  311. /// Delete the given MachineInstr.
  312. ///
  313. /// This function also serves as the MachineInstr destructor - the real
  314. /// ~MachineInstr() destructor must be empty.
  315. void
  316. MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
  317. // Verify that a call site info is at valid state. This assertion should
  318. // be triggered during the implementation of support for the
  319. // call site info of a new architecture. If the assertion is triggered,
  320. // back trace will tell where to insert a call to updateCallSiteInfo().
  321. assert((!MI->isCall(MachineInstr::IgnoreBundle) ||
  322. CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
  323. "Call site info was not updated!");
  324. // Strip it for parts. The operand array and the MI object itself are
  325. // independently recyclable.
  326. if (MI->Operands)
  327. deallocateOperandArray(MI->CapOperands, MI->Operands);
  328. // Don't call ~MachineInstr() which must be trivial anyway because
  329. // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
  330. // destructors.
  331. InstructionRecycler.Deallocate(Allocator, MI);
  332. }
  333. /// Allocate a new MachineBasicBlock. Use this instead of
  334. /// `new MachineBasicBlock'.
  335. MachineBasicBlock *
  336. MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
  337. return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
  338. MachineBasicBlock(*this, bb);
  339. }
  340. /// Delete the given MachineBasicBlock.
  341. void
  342. MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
  343. assert(MBB->getParent() == this && "MBB parent mismatch!");
  344. MBB->~MachineBasicBlock();
  345. BasicBlockRecycler.Deallocate(Allocator, MBB);
  346. }
  347. MachineMemOperand *MachineFunction::getMachineMemOperand(
  348. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
  349. unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
  350. SyncScope::ID SSID, AtomicOrdering Ordering,
  351. AtomicOrdering FailureOrdering) {
  352. return new (Allocator)
  353. MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
  354. SSID, Ordering, FailureOrdering);
  355. }
  356. MachineMemOperand *
  357. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  358. int64_t Offset, uint64_t Size) {
  359. const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
  360. // If there is no pointer value, the offset isn't tracked so we need to adjust
  361. // the base alignment.
  362. unsigned Align = PtrInfo.V.isNull()
  363. ? MinAlign(MMO->getBaseAlignment(), Offset)
  364. : MMO->getBaseAlignment();
  365. return new (Allocator)
  366. MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size,
  367. Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(),
  368. MMO->getOrdering(), MMO->getFailureOrdering());
  369. }
  370. MachineMemOperand *
  371. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  372. const AAMDNodes &AAInfo) {
  373. MachinePointerInfo MPI = MMO->getValue() ?
  374. MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
  375. MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
  376. return new (Allocator)
  377. MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
  378. MMO->getBaseAlignment(), AAInfo,
  379. MMO->getRanges(), MMO->getSyncScopeID(),
  380. MMO->getOrdering(), MMO->getFailureOrdering());
  381. }
  382. MachineMemOperand *
  383. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  384. MachineMemOperand::Flags Flags) {
  385. return new (Allocator) MachineMemOperand(
  386. MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlignment(),
  387. MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
  388. MMO->getOrdering(), MMO->getFailureOrdering());
  389. }
  390. MachineInstr::ExtraInfo *
  391. MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
  392. MCSymbol *PreInstrSymbol,
  393. MCSymbol *PostInstrSymbol) {
  394. return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
  395. PostInstrSymbol);
  396. }
  397. const char *MachineFunction::createExternalSymbolName(StringRef Name) {
  398. char *Dest = Allocator.Allocate<char>(Name.size() + 1);
  399. llvm::copy(Name, Dest);
  400. Dest[Name.size()] = 0;
  401. return Dest;
  402. }
  403. uint32_t *MachineFunction::allocateRegMask() {
  404. unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
  405. unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
  406. uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
  407. memset(Mask, 0, Size * sizeof(Mask[0]));
  408. return Mask;
  409. }
  410. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  411. LLVM_DUMP_METHOD void MachineFunction::dump() const {
  412. print(dbgs());
  413. }
  414. #endif
  415. StringRef MachineFunction::getName() const {
  416. return getFunction().getName();
  417. }
  418. void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
  419. OS << "# Machine code for function " << getName() << ": ";
  420. getProperties().print(OS);
  421. OS << '\n';
  422. // Print Frame Information
  423. FrameInfo->print(*this, OS);
  424. // Print JumpTable Information
  425. if (JumpTableInfo)
  426. JumpTableInfo->print(OS);
  427. // Print Constant Pool
  428. ConstantPool->print(OS);
  429. const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
  430. if (RegInfo && !RegInfo->livein_empty()) {
  431. OS << "Function Live Ins: ";
  432. for (MachineRegisterInfo::livein_iterator
  433. I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
  434. OS << printReg(I->first, TRI);
  435. if (I->second)
  436. OS << " in " << printReg(I->second, TRI);
  437. if (std::next(I) != E)
  438. OS << ", ";
  439. }
  440. OS << '\n';
  441. }
  442. ModuleSlotTracker MST(getFunction().getParent());
  443. MST.incorporateFunction(getFunction());
  444. for (const auto &BB : *this) {
  445. OS << '\n';
  446. // If we print the whole function, print it at its most verbose level.
  447. BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
  448. }
  449. OS << "\n# End machine code for function " << getName() << ".\n\n";
  450. }
  451. namespace llvm {
  452. template<>
  453. struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
  454. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  455. static std::string getGraphName(const MachineFunction *F) {
  456. return ("CFG for '" + F->getName() + "' function").str();
  457. }
  458. std::string getNodeLabel(const MachineBasicBlock *Node,
  459. const MachineFunction *Graph) {
  460. std::string OutStr;
  461. {
  462. raw_string_ostream OSS(OutStr);
  463. if (isSimple()) {
  464. OSS << printMBBReference(*Node);
  465. if (const BasicBlock *BB = Node->getBasicBlock())
  466. OSS << ": " << BB->getName();
  467. } else
  468. Node->print(OSS);
  469. }
  470. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  471. // Process string output to make it nicer...
  472. for (unsigned i = 0; i != OutStr.length(); ++i)
  473. if (OutStr[i] == '\n') { // Left justify
  474. OutStr[i] = '\\';
  475. OutStr.insert(OutStr.begin()+i+1, 'l');
  476. }
  477. return OutStr;
  478. }
  479. };
  480. } // end namespace llvm
  481. void MachineFunction::viewCFG() const
  482. {
  483. #ifndef NDEBUG
  484. ViewGraph(this, "mf" + getName());
  485. #else
  486. errs() << "MachineFunction::viewCFG is only available in debug builds on "
  487. << "systems with Graphviz or gv!\n";
  488. #endif // NDEBUG
  489. }
  490. void MachineFunction::viewCFGOnly() const
  491. {
  492. #ifndef NDEBUG
  493. ViewGraph(this, "mf" + getName(), true);
  494. #else
  495. errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
  496. << "systems with Graphviz or gv!\n";
  497. #endif // NDEBUG
  498. }
  499. /// Add the specified physical register as a live-in value and
  500. /// create a corresponding virtual register for it.
  501. unsigned MachineFunction::addLiveIn(unsigned PReg,
  502. const TargetRegisterClass *RC) {
  503. MachineRegisterInfo &MRI = getRegInfo();
  504. unsigned VReg = MRI.getLiveInVirtReg(PReg);
  505. if (VReg) {
  506. const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
  507. (void)VRegRC;
  508. // A physical register can be added several times.
  509. // Between two calls, the register class of the related virtual register
  510. // may have been constrained to match some operation constraints.
  511. // In that case, check that the current register class includes the
  512. // physical register and is a sub class of the specified RC.
  513. assert((VRegRC == RC || (VRegRC->contains(PReg) &&
  514. RC->hasSubClassEq(VRegRC))) &&
  515. "Register class mismatch!");
  516. return VReg;
  517. }
  518. VReg = MRI.createVirtualRegister(RC);
  519. MRI.addLiveIn(PReg, VReg);
  520. return VReg;
  521. }
  522. /// Return the MCSymbol for the specified non-empty jump table.
  523. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  524. /// normal 'L' label is returned.
  525. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
  526. bool isLinkerPrivate) const {
  527. const DataLayout &DL = getDataLayout();
  528. assert(JumpTableInfo && "No jump tables");
  529. assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
  530. StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
  531. : DL.getPrivateGlobalPrefix();
  532. SmallString<60> Name;
  533. raw_svector_ostream(Name)
  534. << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
  535. return Ctx.getOrCreateSymbol(Name);
  536. }
  537. /// Return a function-local symbol to represent the PIC base.
  538. MCSymbol *MachineFunction::getPICBaseSymbol() const {
  539. const DataLayout &DL = getDataLayout();
  540. return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  541. Twine(getFunctionNumber()) + "$pb");
  542. }
  543. /// \name Exception Handling
  544. /// \{
  545. LandingPadInfo &
  546. MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
  547. unsigned N = LandingPads.size();
  548. for (unsigned i = 0; i < N; ++i) {
  549. LandingPadInfo &LP = LandingPads[i];
  550. if (LP.LandingPadBlock == LandingPad)
  551. return LP;
  552. }
  553. LandingPads.push_back(LandingPadInfo(LandingPad));
  554. return LandingPads[N];
  555. }
  556. void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
  557. MCSymbol *BeginLabel, MCSymbol *EndLabel) {
  558. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  559. LP.BeginLabels.push_back(BeginLabel);
  560. LP.EndLabels.push_back(EndLabel);
  561. }
  562. MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
  563. MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
  564. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  565. LP.LandingPadLabel = LandingPadLabel;
  566. const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
  567. if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
  568. if (const auto *PF =
  569. dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
  570. getMMI().addPersonality(PF);
  571. if (LPI->isCleanup())
  572. addCleanup(LandingPad);
  573. // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
  574. // correct, but we need to do it this way because of how the DWARF EH
  575. // emitter processes the clauses.
  576. for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
  577. Value *Val = LPI->getClause(I - 1);
  578. if (LPI->isCatch(I - 1)) {
  579. addCatchTypeInfo(LandingPad,
  580. dyn_cast<GlobalValue>(Val->stripPointerCasts()));
  581. } else {
  582. // Add filters in a list.
  583. auto *CVal = cast<Constant>(Val);
  584. SmallVector<const GlobalValue *, 4> FilterList;
  585. for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
  586. II != IE; ++II)
  587. FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
  588. addFilterTypeInfo(LandingPad, FilterList);
  589. }
  590. }
  591. } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
  592. for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
  593. Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
  594. addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
  595. }
  596. } else {
  597. assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
  598. }
  599. return LandingPadLabel;
  600. }
  601. void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
  602. ArrayRef<const GlobalValue *> TyInfo) {
  603. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  604. for (unsigned N = TyInfo.size(); N; --N)
  605. LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
  606. }
  607. void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
  608. ArrayRef<const GlobalValue *> TyInfo) {
  609. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  610. std::vector<unsigned> IdsInFilter(TyInfo.size());
  611. for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
  612. IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
  613. LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
  614. }
  615. void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
  616. bool TidyIfNoBeginLabels) {
  617. for (unsigned i = 0; i != LandingPads.size(); ) {
  618. LandingPadInfo &LandingPad = LandingPads[i];
  619. if (LandingPad.LandingPadLabel &&
  620. !LandingPad.LandingPadLabel->isDefined() &&
  621. (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
  622. LandingPad.LandingPadLabel = nullptr;
  623. // Special case: we *should* emit LPs with null LP MBB. This indicates
  624. // "nounwind" case.
  625. if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
  626. LandingPads.erase(LandingPads.begin() + i);
  627. continue;
  628. }
  629. if (TidyIfNoBeginLabels) {
  630. for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
  631. MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
  632. MCSymbol *EndLabel = LandingPad.EndLabels[j];
  633. if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
  634. (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
  635. continue;
  636. LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
  637. LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
  638. --j;
  639. --e;
  640. }
  641. // Remove landing pads with no try-ranges.
  642. if (LandingPads[i].BeginLabels.empty()) {
  643. LandingPads.erase(LandingPads.begin() + i);
  644. continue;
  645. }
  646. }
  647. // If there is no landing pad, ensure that the list of typeids is empty.
  648. // If the only typeid is a cleanup, this is the same as having no typeids.
  649. if (!LandingPad.LandingPadBlock ||
  650. (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
  651. LandingPad.TypeIds.clear();
  652. ++i;
  653. }
  654. }
  655. void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
  656. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  657. LP.TypeIds.push_back(0);
  658. }
  659. void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
  660. const Function *Filter,
  661. const BlockAddress *RecoverBA) {
  662. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  663. SEHHandler Handler;
  664. Handler.FilterOrFinally = Filter;
  665. Handler.RecoverBA = RecoverBA;
  666. LP.SEHHandlers.push_back(Handler);
  667. }
  668. void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
  669. const Function *Cleanup) {
  670. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  671. SEHHandler Handler;
  672. Handler.FilterOrFinally = Cleanup;
  673. Handler.RecoverBA = nullptr;
  674. LP.SEHHandlers.push_back(Handler);
  675. }
  676. void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
  677. ArrayRef<unsigned> Sites) {
  678. LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
  679. }
  680. unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
  681. for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
  682. if (TypeInfos[i] == TI) return i + 1;
  683. TypeInfos.push_back(TI);
  684. return TypeInfos.size();
  685. }
  686. int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
  687. // If the new filter coincides with the tail of an existing filter, then
  688. // re-use the existing filter. Folding filters more than this requires
  689. // re-ordering filters and/or their elements - probably not worth it.
  690. for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
  691. E = FilterEnds.end(); I != E; ++I) {
  692. unsigned i = *I, j = TyIds.size();
  693. while (i && j)
  694. if (FilterIds[--i] != TyIds[--j])
  695. goto try_next;
  696. if (!j)
  697. // The new filter coincides with range [i, end) of the existing filter.
  698. return -(1 + i);
  699. try_next:;
  700. }
  701. // Add the new filter.
  702. int FilterID = -(1 + FilterIds.size());
  703. FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
  704. FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
  705. FilterEnds.push_back(FilterIds.size());
  706. FilterIds.push_back(0); // terminator
  707. return FilterID;
  708. }
  709. void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I,
  710. const MDNode *MD) {
  711. MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
  712. MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
  713. I->setPreInstrSymbol(*this, BeginLabel);
  714. I->setPostInstrSymbol(*this, EndLabel);
  715. const DIType *DI = dyn_cast<DIType>(MD);
  716. CodeViewHeapAllocSites.push_back(std::make_tuple(BeginLabel, EndLabel, DI));
  717. }
  718. void MachineFunction::updateCallSiteInfo(const MachineInstr *Old,
  719. const MachineInstr *New) {
  720. if (!Target.Options.EnableDebugEntryValues || Old == New)
  721. return;
  722. assert(Old->isCall() && (!New || New->isCall()) &&
  723. "Call site info referes only to call instructions!");
  724. CallSiteInfoMap::iterator CSIt = CallSitesInfo.find(Old);
  725. if (CSIt == CallSitesInfo.end())
  726. return;
  727. CallSiteInfo CSInfo = std::move(CSIt->second);
  728. CallSitesInfo.erase(CSIt);
  729. if (New)
  730. CallSitesInfo[New] = CSInfo;
  731. }
  732. /// \}
  733. //===----------------------------------------------------------------------===//
  734. // MachineJumpTableInfo implementation
  735. //===----------------------------------------------------------------------===//
  736. /// Return the size of each entry in the jump table.
  737. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
  738. // The size of a jump table entry is 4 bytes unless the entry is just the
  739. // address of a block, in which case it is the pointer size.
  740. switch (getEntryKind()) {
  741. case MachineJumpTableInfo::EK_BlockAddress:
  742. return TD.getPointerSize();
  743. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  744. return 8;
  745. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  746. case MachineJumpTableInfo::EK_LabelDifference32:
  747. case MachineJumpTableInfo::EK_Custom32:
  748. return 4;
  749. case MachineJumpTableInfo::EK_Inline:
  750. return 0;
  751. }
  752. llvm_unreachable("Unknown jump table encoding!");
  753. }
  754. /// Return the alignment of each entry in the jump table.
  755. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
  756. // The alignment of a jump table entry is the alignment of int32 unless the
  757. // entry is just the address of a block, in which case it is the pointer
  758. // alignment.
  759. switch (getEntryKind()) {
  760. case MachineJumpTableInfo::EK_BlockAddress:
  761. return TD.getPointerABIAlignment(0);
  762. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  763. return TD.getABIIntegerTypeAlignment(64);
  764. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  765. case MachineJumpTableInfo::EK_LabelDifference32:
  766. case MachineJumpTableInfo::EK_Custom32:
  767. return TD.getABIIntegerTypeAlignment(32);
  768. case MachineJumpTableInfo::EK_Inline:
  769. return 1;
  770. }
  771. llvm_unreachable("Unknown jump table encoding!");
  772. }
  773. /// Create a new jump table entry in the jump table info.
  774. unsigned MachineJumpTableInfo::createJumpTableIndex(
  775. const std::vector<MachineBasicBlock*> &DestBBs) {
  776. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  777. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  778. return JumpTables.size()-1;
  779. }
  780. /// If Old is the target of any jump tables, update the jump tables to branch
  781. /// to New instead.
  782. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  783. MachineBasicBlock *New) {
  784. assert(Old != New && "Not making a change?");
  785. bool MadeChange = false;
  786. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  787. ReplaceMBBInJumpTable(i, Old, New);
  788. return MadeChange;
  789. }
  790. /// If Old is a target of the jump tables, update the jump table to branch to
  791. /// New instead.
  792. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  793. MachineBasicBlock *Old,
  794. MachineBasicBlock *New) {
  795. assert(Old != New && "Not making a change?");
  796. bool MadeChange = false;
  797. MachineJumpTableEntry &JTE = JumpTables[Idx];
  798. for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
  799. if (JTE.MBBs[j] == Old) {
  800. JTE.MBBs[j] = New;
  801. MadeChange = true;
  802. }
  803. return MadeChange;
  804. }
  805. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  806. if (JumpTables.empty()) return;
  807. OS << "Jump Tables:\n";
  808. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  809. OS << printJumpTableEntryReference(i) << ':';
  810. for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
  811. OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
  812. if (i != e)
  813. OS << '\n';
  814. }
  815. OS << '\n';
  816. }
  817. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  818. LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
  819. #endif
  820. Printable llvm::printJumpTableEntryReference(unsigned Idx) {
  821. return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
  822. }
  823. //===----------------------------------------------------------------------===//
  824. // MachineConstantPool implementation
  825. //===----------------------------------------------------------------------===//
  826. void MachineConstantPoolValue::anchor() {}
  827. Type *MachineConstantPoolEntry::getType() const {
  828. if (isMachineConstantPoolEntry())
  829. return Val.MachineCPVal->getType();
  830. return Val.ConstVal->getType();
  831. }
  832. bool MachineConstantPoolEntry::needsRelocation() const {
  833. if (isMachineConstantPoolEntry())
  834. return true;
  835. return Val.ConstVal->needsRelocation();
  836. }
  837. SectionKind
  838. MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
  839. if (needsRelocation())
  840. return SectionKind::getReadOnlyWithRel();
  841. switch (DL->getTypeAllocSize(getType())) {
  842. case 4:
  843. return SectionKind::getMergeableConst4();
  844. case 8:
  845. return SectionKind::getMergeableConst8();
  846. case 16:
  847. return SectionKind::getMergeableConst16();
  848. case 32:
  849. return SectionKind::getMergeableConst32();
  850. default:
  851. return SectionKind::getReadOnly();
  852. }
  853. }
  854. MachineConstantPool::~MachineConstantPool() {
  855. // A constant may be a member of both Constants and MachineCPVsSharingEntries,
  856. // so keep track of which we've deleted to avoid double deletions.
  857. DenseSet<MachineConstantPoolValue*> Deleted;
  858. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  859. if (Constants[i].isMachineConstantPoolEntry()) {
  860. Deleted.insert(Constants[i].Val.MachineCPVal);
  861. delete Constants[i].Val.MachineCPVal;
  862. }
  863. for (DenseSet<MachineConstantPoolValue*>::iterator I =
  864. MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
  865. I != E; ++I) {
  866. if (Deleted.count(*I) == 0)
  867. delete *I;
  868. }
  869. }
  870. /// Test whether the given two constants can be allocated the same constant pool
  871. /// entry.
  872. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  873. const DataLayout &DL) {
  874. // Handle the trivial case quickly.
  875. if (A == B) return true;
  876. // If they have the same type but weren't the same constant, quickly
  877. // reject them.
  878. if (A->getType() == B->getType()) return false;
  879. // We can't handle structs or arrays.
  880. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
  881. isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
  882. return false;
  883. // For now, only support constants with the same size.
  884. uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
  885. if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
  886. return false;
  887. Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
  888. // Try constant folding a bitcast of both instructions to an integer. If we
  889. // get two identical ConstantInt's, then we are good to share them. We use
  890. // the constant folding APIs to do this so that we get the benefit of
  891. // DataLayout.
  892. if (isa<PointerType>(A->getType()))
  893. A = ConstantFoldCastOperand(Instruction::PtrToInt,
  894. const_cast<Constant *>(A), IntTy, DL);
  895. else if (A->getType() != IntTy)
  896. A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
  897. IntTy, DL);
  898. if (isa<PointerType>(B->getType()))
  899. B = ConstantFoldCastOperand(Instruction::PtrToInt,
  900. const_cast<Constant *>(B), IntTy, DL);
  901. else if (B->getType() != IntTy)
  902. B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
  903. IntTy, DL);
  904. return A == B;
  905. }
  906. /// Create a new entry in the constant pool or return an existing one.
  907. /// User must specify the log2 of the minimum required alignment for the object.
  908. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  909. unsigned Alignment) {
  910. assert(Alignment && "Alignment must be specified!");
  911. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  912. // Check to see if we already have this constant.
  913. //
  914. // FIXME, this could be made much more efficient for large constant pools.
  915. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  916. if (!Constants[i].isMachineConstantPoolEntry() &&
  917. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
  918. if ((unsigned)Constants[i].getAlignment() < Alignment)
  919. Constants[i].Alignment = Alignment;
  920. return i;
  921. }
  922. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  923. return Constants.size()-1;
  924. }
  925. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  926. unsigned Alignment) {
  927. assert(Alignment && "Alignment must be specified!");
  928. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  929. // Check to see if we already have this constant.
  930. //
  931. // FIXME, this could be made much more efficient for large constant pools.
  932. int Idx = V->getExistingMachineCPValue(this, Alignment);
  933. if (Idx != -1) {
  934. MachineCPVsSharingEntries.insert(V);
  935. return (unsigned)Idx;
  936. }
  937. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  938. return Constants.size()-1;
  939. }
  940. void MachineConstantPool::print(raw_ostream &OS) const {
  941. if (Constants.empty()) return;
  942. OS << "Constant Pool:\n";
  943. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  944. OS << " cp#" << i << ": ";
  945. if (Constants[i].isMachineConstantPoolEntry())
  946. Constants[i].Val.MachineCPVal->print(OS);
  947. else
  948. Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
  949. OS << ", align=" << Constants[i].getAlignment();
  950. OS << "\n";
  951. }
  952. }
  953. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  954. LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
  955. #endif