MachineFunction.cpp 37 KB

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