MIRPrinter.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
  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. // This file implements the class that prints out the LLVM IR and machine
  10. // functions using the MIR serialization format.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MIRPrinter.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallBitVector.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
  23. #include "llvm/CodeGen/MIRYamlMapping.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineConstantPool.h"
  26. #include "llvm/CodeGen/MachineFrameInfo.h"
  27. #include "llvm/CodeGen/MachineFunction.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  30. #include "llvm/CodeGen/MachineMemOperand.h"
  31. #include "llvm/CodeGen/MachineOperand.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/PseudoSourceValue.h"
  34. #include "llvm/CodeGen/TargetInstrInfo.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/CodeGen/TargetFrameLowering.h"
  38. #include "llvm/IR/BasicBlock.h"
  39. #include "llvm/IR/Constants.h"
  40. #include "llvm/IR/DebugInfo.h"
  41. #include "llvm/IR/DebugLoc.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/GlobalValue.h"
  44. #include "llvm/IR/IRPrintingPasses.h"
  45. #include "llvm/IR/InstrTypes.h"
  46. #include "llvm/IR/Instructions.h"
  47. #include "llvm/IR/Intrinsics.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/IR/ModuleSlotTracker.h"
  50. #include "llvm/IR/Value.h"
  51. #include "llvm/MC/LaneBitmask.h"
  52. #include "llvm/MC/MCContext.h"
  53. #include "llvm/MC/MCDwarf.h"
  54. #include "llvm/MC/MCSymbol.h"
  55. #include "llvm/Support/AtomicOrdering.h"
  56. #include "llvm/Support/BranchProbability.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/ErrorHandling.h"
  60. #include "llvm/Support/Format.h"
  61. #include "llvm/Support/LowLevelTypeImpl.h"
  62. #include "llvm/Support/YAMLTraits.h"
  63. #include "llvm/Support/raw_ostream.h"
  64. #include "llvm/Target/TargetIntrinsicInfo.h"
  65. #include "llvm/Target/TargetMachine.h"
  66. #include <algorithm>
  67. #include <cassert>
  68. #include <cinttypes>
  69. #include <cstdint>
  70. #include <iterator>
  71. #include <string>
  72. #include <utility>
  73. #include <vector>
  74. using namespace llvm;
  75. static cl::opt<bool> SimplifyMIR(
  76. "simplify-mir", cl::Hidden,
  77. cl::desc("Leave out unnecessary information when printing MIR"));
  78. namespace {
  79. /// This structure describes how to print out stack object references.
  80. struct FrameIndexOperand {
  81. std::string Name;
  82. unsigned ID;
  83. bool IsFixed;
  84. FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
  85. : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
  86. /// Return an ordinary stack object reference.
  87. static FrameIndexOperand create(StringRef Name, unsigned ID) {
  88. return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
  89. }
  90. /// Return a fixed stack object reference.
  91. static FrameIndexOperand createFixed(unsigned ID) {
  92. return FrameIndexOperand("", ID, /*IsFixed=*/true);
  93. }
  94. };
  95. } // end anonymous namespace
  96. namespace llvm {
  97. /// This class prints out the machine functions using the MIR serialization
  98. /// format.
  99. class MIRPrinter {
  100. raw_ostream &OS;
  101. DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
  102. /// Maps from stack object indices to operand indices which will be used when
  103. /// printing frame index machine operands.
  104. DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
  105. public:
  106. MIRPrinter(raw_ostream &OS) : OS(OS) {}
  107. void print(const MachineFunction &MF);
  108. void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
  109. const TargetRegisterInfo *TRI);
  110. void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
  111. const MachineFrameInfo &MFI);
  112. void convert(yaml::MachineFunction &MF,
  113. const MachineConstantPool &ConstantPool);
  114. void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
  115. const MachineJumpTableInfo &JTI);
  116. void convertStackObjects(yaml::MachineFunction &YMF,
  117. const MachineFunction &MF, ModuleSlotTracker &MST);
  118. void convertCallSiteObjects(yaml::MachineFunction &YMF,
  119. const MachineFunction &MF,
  120. ModuleSlotTracker &MST);
  121. private:
  122. void initRegisterMaskIds(const MachineFunction &MF);
  123. };
  124. /// This class prints out the machine instructions using the MIR serialization
  125. /// format.
  126. class MIPrinter {
  127. raw_ostream &OS;
  128. ModuleSlotTracker &MST;
  129. const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
  130. const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
  131. /// Synchronization scope names registered with LLVMContext.
  132. SmallVector<StringRef, 8> SSNs;
  133. bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
  134. bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
  135. public:
  136. MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
  137. const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
  138. const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
  139. : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
  140. StackObjectOperandMapping(StackObjectOperandMapping) {}
  141. void print(const MachineBasicBlock &MBB);
  142. void print(const MachineInstr &MI);
  143. void printStackObjectReference(int FrameIndex);
  144. void print(const MachineInstr &MI, unsigned OpIdx,
  145. const TargetRegisterInfo *TRI, bool ShouldPrintRegisterTies,
  146. LLT TypeToPrint, bool PrintDef = true);
  147. };
  148. } // end namespace llvm
  149. namespace llvm {
  150. namespace yaml {
  151. /// This struct serializes the LLVM IR module.
  152. template <> struct BlockScalarTraits<Module> {
  153. static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
  154. Mod.print(OS, nullptr);
  155. }
  156. static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
  157. llvm_unreachable("LLVM Module is supposed to be parsed separately");
  158. return "";
  159. }
  160. };
  161. } // end namespace yaml
  162. } // end namespace llvm
  163. static void printRegMIR(unsigned Reg, yaml::StringValue &Dest,
  164. const TargetRegisterInfo *TRI) {
  165. raw_string_ostream OS(Dest.Value);
  166. OS << printReg(Reg, TRI);
  167. }
  168. void MIRPrinter::print(const MachineFunction &MF) {
  169. initRegisterMaskIds(MF);
  170. yaml::MachineFunction YamlMF;
  171. YamlMF.Name = MF.getName();
  172. YamlMF.Alignment = 1UL << MF.getLogAlignment();
  173. YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
  174. YamlMF.HasWinCFI = MF.hasWinCFI();
  175. YamlMF.Legalized = MF.getProperties().hasProperty(
  176. MachineFunctionProperties::Property::Legalized);
  177. YamlMF.RegBankSelected = MF.getProperties().hasProperty(
  178. MachineFunctionProperties::Property::RegBankSelected);
  179. YamlMF.Selected = MF.getProperties().hasProperty(
  180. MachineFunctionProperties::Property::Selected);
  181. YamlMF.FailedISel = MF.getProperties().hasProperty(
  182. MachineFunctionProperties::Property::FailedISel);
  183. convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
  184. ModuleSlotTracker MST(MF.getFunction().getParent());
  185. MST.incorporateFunction(MF.getFunction());
  186. convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
  187. convertStackObjects(YamlMF, MF, MST);
  188. convertCallSiteObjects(YamlMF, MF, MST);
  189. if (const auto *ConstantPool = MF.getConstantPool())
  190. convert(YamlMF, *ConstantPool);
  191. if (const auto *JumpTableInfo = MF.getJumpTableInfo())
  192. convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
  193. const TargetMachine &TM = MF.getTarget();
  194. YamlMF.MachineFuncInfo =
  195. std::unique_ptr<yaml::MachineFunctionInfo>(TM.convertFuncInfoToYAML(MF));
  196. raw_string_ostream StrOS(YamlMF.Body.Value.Value);
  197. bool IsNewlineNeeded = false;
  198. for (const auto &MBB : MF) {
  199. if (IsNewlineNeeded)
  200. StrOS << "\n";
  201. MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
  202. .print(MBB);
  203. IsNewlineNeeded = true;
  204. }
  205. StrOS.flush();
  206. yaml::Output Out(OS);
  207. if (!SimplifyMIR)
  208. Out.setWriteDefaultValues(true);
  209. Out << YamlMF;
  210. }
  211. static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
  212. const TargetRegisterInfo *TRI) {
  213. assert(RegMask && "Can't print an empty register mask");
  214. OS << StringRef("CustomRegMask(");
  215. bool IsRegInRegMaskFound = false;
  216. for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
  217. // Check whether the register is asserted in regmask.
  218. if (RegMask[I / 32] & (1u << (I % 32))) {
  219. if (IsRegInRegMaskFound)
  220. OS << ',';
  221. OS << printReg(I, TRI);
  222. IsRegInRegMaskFound = true;
  223. }
  224. }
  225. OS << ')';
  226. }
  227. static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest,
  228. const MachineRegisterInfo &RegInfo,
  229. const TargetRegisterInfo *TRI) {
  230. raw_string_ostream OS(Dest.Value);
  231. OS << printRegClassOrBank(Reg, RegInfo, TRI);
  232. }
  233. template <typename T>
  234. static void
  235. printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo &DebugVar,
  236. T &Object, ModuleSlotTracker &MST) {
  237. std::array<std::string *, 3> Outputs{{&Object.DebugVar.Value,
  238. &Object.DebugExpr.Value,
  239. &Object.DebugLoc.Value}};
  240. std::array<const Metadata *, 3> Metas{{DebugVar.Var,
  241. DebugVar.Expr,
  242. DebugVar.Loc}};
  243. for (unsigned i = 0; i < 3; ++i) {
  244. raw_string_ostream StrOS(*Outputs[i]);
  245. Metas[i]->printAsOperand(StrOS, MST);
  246. }
  247. }
  248. void MIRPrinter::convert(yaml::MachineFunction &MF,
  249. const MachineRegisterInfo &RegInfo,
  250. const TargetRegisterInfo *TRI) {
  251. MF.TracksRegLiveness = RegInfo.tracksLiveness();
  252. // Print the virtual register definitions.
  253. for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
  254. unsigned Reg = Register::index2VirtReg(I);
  255. yaml::VirtualRegisterDefinition VReg;
  256. VReg.ID = I;
  257. if (RegInfo.getVRegName(Reg) != "")
  258. continue;
  259. ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI);
  260. unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
  261. if (PreferredReg)
  262. printRegMIR(PreferredReg, VReg.PreferredRegister, TRI);
  263. MF.VirtualRegisters.push_back(VReg);
  264. }
  265. // Print the live ins.
  266. for (std::pair<unsigned, unsigned> LI : RegInfo.liveins()) {
  267. yaml::MachineFunctionLiveIn LiveIn;
  268. printRegMIR(LI.first, LiveIn.Register, TRI);
  269. if (LI.second)
  270. printRegMIR(LI.second, LiveIn.VirtualRegister, TRI);
  271. MF.LiveIns.push_back(LiveIn);
  272. }
  273. // Prints the callee saved registers.
  274. if (RegInfo.isUpdatedCSRsInitialized()) {
  275. const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
  276. std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
  277. for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
  278. yaml::FlowStringValue Reg;
  279. printRegMIR(*I, Reg, TRI);
  280. CalleeSavedRegisters.push_back(Reg);
  281. }
  282. MF.CalleeSavedRegisters = CalleeSavedRegisters;
  283. }
  284. }
  285. void MIRPrinter::convert(ModuleSlotTracker &MST,
  286. yaml::MachineFrameInfo &YamlMFI,
  287. const MachineFrameInfo &MFI) {
  288. YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
  289. YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
  290. YamlMFI.HasStackMap = MFI.hasStackMap();
  291. YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
  292. YamlMFI.StackSize = MFI.getStackSize();
  293. YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
  294. YamlMFI.MaxAlignment = MFI.getMaxAlignment();
  295. YamlMFI.AdjustsStack = MFI.adjustsStack();
  296. YamlMFI.HasCalls = MFI.hasCalls();
  297. YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
  298. ? MFI.getMaxCallFrameSize() : ~0u;
  299. YamlMFI.CVBytesOfCalleeSavedRegisters =
  300. MFI.getCVBytesOfCalleeSavedRegisters();
  301. YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
  302. YamlMFI.HasVAStart = MFI.hasVAStart();
  303. YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
  304. YamlMFI.LocalFrameSize = MFI.getLocalFrameSize();
  305. if (MFI.getSavePoint()) {
  306. raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
  307. StrOS << printMBBReference(*MFI.getSavePoint());
  308. }
  309. if (MFI.getRestorePoint()) {
  310. raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
  311. StrOS << printMBBReference(*MFI.getRestorePoint());
  312. }
  313. }
  314. void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
  315. const MachineFunction &MF,
  316. ModuleSlotTracker &MST) {
  317. const MachineFrameInfo &MFI = MF.getFrameInfo();
  318. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  319. // Process fixed stack objects.
  320. unsigned ID = 0;
  321. for (int I = MFI.getObjectIndexBegin(); I < 0; ++I, ++ID) {
  322. if (MFI.isDeadObjectIndex(I))
  323. continue;
  324. yaml::FixedMachineStackObject YamlObject;
  325. YamlObject.ID = ID;
  326. YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
  327. ? yaml::FixedMachineStackObject::SpillSlot
  328. : yaml::FixedMachineStackObject::DefaultType;
  329. YamlObject.Offset = MFI.getObjectOffset(I);
  330. YamlObject.Size = MFI.getObjectSize(I);
  331. YamlObject.Alignment = MFI.getObjectAlignment(I);
  332. YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
  333. YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
  334. YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
  335. YMF.FixedStackObjects.push_back(YamlObject);
  336. StackObjectOperandMapping.insert(
  337. std::make_pair(I, FrameIndexOperand::createFixed(ID)));
  338. }
  339. // Process ordinary stack objects.
  340. ID = 0;
  341. for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I, ++ID) {
  342. if (MFI.isDeadObjectIndex(I))
  343. continue;
  344. yaml::MachineStackObject YamlObject;
  345. YamlObject.ID = ID;
  346. if (const auto *Alloca = MFI.getObjectAllocation(I))
  347. YamlObject.Name.Value =
  348. Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
  349. YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
  350. ? yaml::MachineStackObject::SpillSlot
  351. : MFI.isVariableSizedObjectIndex(I)
  352. ? yaml::MachineStackObject::VariableSized
  353. : yaml::MachineStackObject::DefaultType;
  354. YamlObject.Offset = MFI.getObjectOffset(I);
  355. YamlObject.Size = MFI.getObjectSize(I);
  356. YamlObject.Alignment = MFI.getObjectAlignment(I);
  357. YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
  358. YMF.StackObjects.push_back(YamlObject);
  359. StackObjectOperandMapping.insert(std::make_pair(
  360. I, FrameIndexOperand::create(YamlObject.Name.Value, ID)));
  361. }
  362. for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
  363. if (!CSInfo.isSpilledToReg() && MFI.isDeadObjectIndex(CSInfo.getFrameIdx()))
  364. continue;
  365. yaml::StringValue Reg;
  366. printRegMIR(CSInfo.getReg(), Reg, TRI);
  367. if (!CSInfo.isSpilledToReg()) {
  368. auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
  369. assert(StackObjectInfo != StackObjectOperandMapping.end() &&
  370. "Invalid stack object index");
  371. const FrameIndexOperand &StackObject = StackObjectInfo->second;
  372. if (StackObject.IsFixed) {
  373. YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
  374. YMF.FixedStackObjects[StackObject.ID].CalleeSavedRestored =
  375. CSInfo.isRestored();
  376. } else {
  377. YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
  378. YMF.StackObjects[StackObject.ID].CalleeSavedRestored =
  379. CSInfo.isRestored();
  380. }
  381. }
  382. }
  383. for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
  384. auto LocalObject = MFI.getLocalFrameObjectMap(I);
  385. auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
  386. assert(StackObjectInfo != StackObjectOperandMapping.end() &&
  387. "Invalid stack object index");
  388. const FrameIndexOperand &StackObject = StackObjectInfo->second;
  389. assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
  390. YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
  391. }
  392. // Print the stack object references in the frame information class after
  393. // converting the stack objects.
  394. if (MFI.hasStackProtectorIndex()) {
  395. raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
  396. MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
  397. .printStackObjectReference(MFI.getStackProtectorIndex());
  398. }
  399. // Print the debug variable information.
  400. for (const MachineFunction::VariableDbgInfo &DebugVar :
  401. MF.getVariableDbgInfo()) {
  402. auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
  403. assert(StackObjectInfo != StackObjectOperandMapping.end() &&
  404. "Invalid stack object index");
  405. const FrameIndexOperand &StackObject = StackObjectInfo->second;
  406. if (StackObject.IsFixed) {
  407. auto &Object = YMF.FixedStackObjects[StackObject.ID];
  408. printStackObjectDbgInfo(DebugVar, Object, MST);
  409. } else {
  410. auto &Object = YMF.StackObjects[StackObject.ID];
  411. printStackObjectDbgInfo(DebugVar, Object, MST);
  412. }
  413. }
  414. }
  415. void MIRPrinter::convertCallSiteObjects(yaml::MachineFunction &YMF,
  416. const MachineFunction &MF,
  417. ModuleSlotTracker &MST) {
  418. const auto *TRI = MF.getSubtarget().getRegisterInfo();
  419. for (auto CSInfo : MF.getCallSitesInfo()) {
  420. yaml::CallSiteInfo YmlCS;
  421. yaml::CallSiteInfo::MachineInstrLoc CallLocation;
  422. // Prepare instruction position.
  423. MachineBasicBlock::const_instr_iterator CallI = CSInfo.first->getIterator();
  424. CallLocation.BlockNum = CallI->getParent()->getNumber();
  425. // Get call instruction offset from the beginning of block.
  426. CallLocation.Offset =
  427. std::distance(CallI->getParent()->instr_begin(), CallI);
  428. YmlCS.CallLocation = CallLocation;
  429. // Construct call arguments and theirs forwarding register info.
  430. for (auto ArgReg : CSInfo.second) {
  431. yaml::CallSiteInfo::ArgRegPair YmlArgReg;
  432. YmlArgReg.ArgNo = ArgReg.ArgNo;
  433. printRegMIR(ArgReg.Reg, YmlArgReg.Reg, TRI);
  434. YmlCS.ArgForwardingRegs.emplace_back(YmlArgReg);
  435. }
  436. YMF.CallSitesInfo.push_back(YmlCS);
  437. }
  438. // Sort call info by position of call instructions.
  439. llvm::sort(YMF.CallSitesInfo.begin(), YMF.CallSitesInfo.end(),
  440. [](yaml::CallSiteInfo A, yaml::CallSiteInfo B) {
  441. if (A.CallLocation.BlockNum == B.CallLocation.BlockNum)
  442. return A.CallLocation.Offset < B.CallLocation.Offset;
  443. return A.CallLocation.BlockNum < B.CallLocation.BlockNum;
  444. });
  445. }
  446. void MIRPrinter::convert(yaml::MachineFunction &MF,
  447. const MachineConstantPool &ConstantPool) {
  448. unsigned ID = 0;
  449. for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
  450. std::string Str;
  451. raw_string_ostream StrOS(Str);
  452. if (Constant.isMachineConstantPoolEntry()) {
  453. Constant.Val.MachineCPVal->print(StrOS);
  454. } else {
  455. Constant.Val.ConstVal->printAsOperand(StrOS);
  456. }
  457. yaml::MachineConstantPoolValue YamlConstant;
  458. YamlConstant.ID = ID++;
  459. YamlConstant.Value = StrOS.str();
  460. YamlConstant.Alignment = Constant.getAlignment();
  461. YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
  462. MF.Constants.push_back(YamlConstant);
  463. }
  464. }
  465. void MIRPrinter::convert(ModuleSlotTracker &MST,
  466. yaml::MachineJumpTable &YamlJTI,
  467. const MachineJumpTableInfo &JTI) {
  468. YamlJTI.Kind = JTI.getEntryKind();
  469. unsigned ID = 0;
  470. for (const auto &Table : JTI.getJumpTables()) {
  471. std::string Str;
  472. yaml::MachineJumpTable::Entry Entry;
  473. Entry.ID = ID++;
  474. for (const auto *MBB : Table.MBBs) {
  475. raw_string_ostream StrOS(Str);
  476. StrOS << printMBBReference(*MBB);
  477. Entry.Blocks.push_back(StrOS.str());
  478. Str.clear();
  479. }
  480. YamlJTI.Entries.push_back(Entry);
  481. }
  482. }
  483. void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
  484. const auto *TRI = MF.getSubtarget().getRegisterInfo();
  485. unsigned I = 0;
  486. for (const uint32_t *Mask : TRI->getRegMasks())
  487. RegisterMaskIds.insert(std::make_pair(Mask, I++));
  488. }
  489. void llvm::guessSuccessors(const MachineBasicBlock &MBB,
  490. SmallVectorImpl<MachineBasicBlock*> &Result,
  491. bool &IsFallthrough) {
  492. SmallPtrSet<MachineBasicBlock*,8> Seen;
  493. for (const MachineInstr &MI : MBB) {
  494. if (MI.isPHI())
  495. continue;
  496. for (const MachineOperand &MO : MI.operands()) {
  497. if (!MO.isMBB())
  498. continue;
  499. MachineBasicBlock *Succ = MO.getMBB();
  500. auto RP = Seen.insert(Succ);
  501. if (RP.second)
  502. Result.push_back(Succ);
  503. }
  504. }
  505. MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
  506. IsFallthrough = I == MBB.end() || !I->isBarrier();
  507. }
  508. bool
  509. MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
  510. if (MBB.succ_size() <= 1)
  511. return true;
  512. if (!MBB.hasSuccessorProbabilities())
  513. return true;
  514. SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
  515. MBB.Probs.end());
  516. BranchProbability::normalizeProbabilities(Normalized.begin(),
  517. Normalized.end());
  518. SmallVector<BranchProbability,8> Equal(Normalized.size());
  519. BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
  520. return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
  521. }
  522. bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
  523. SmallVector<MachineBasicBlock*,8> GuessedSuccs;
  524. bool GuessedFallthrough;
  525. guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
  526. if (GuessedFallthrough) {
  527. const MachineFunction &MF = *MBB.getParent();
  528. MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
  529. if (NextI != MF.end()) {
  530. MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
  531. if (!is_contained(GuessedSuccs, Next))
  532. GuessedSuccs.push_back(Next);
  533. }
  534. }
  535. if (GuessedSuccs.size() != MBB.succ_size())
  536. return false;
  537. return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
  538. }
  539. void MIPrinter::print(const MachineBasicBlock &MBB) {
  540. assert(MBB.getNumber() >= 0 && "Invalid MBB number");
  541. OS << "bb." << MBB.getNumber();
  542. bool HasAttributes = false;
  543. if (const auto *BB = MBB.getBasicBlock()) {
  544. if (BB->hasName()) {
  545. OS << "." << BB->getName();
  546. } else {
  547. HasAttributes = true;
  548. OS << " (";
  549. int Slot = MST.getLocalSlot(BB);
  550. if (Slot == -1)
  551. OS << "<ir-block badref>";
  552. else
  553. OS << (Twine("%ir-block.") + Twine(Slot)).str();
  554. }
  555. }
  556. if (MBB.hasAddressTaken()) {
  557. OS << (HasAttributes ? ", " : " (");
  558. OS << "address-taken";
  559. HasAttributes = true;
  560. }
  561. if (MBB.isEHPad()) {
  562. OS << (HasAttributes ? ", " : " (");
  563. OS << "landing-pad";
  564. HasAttributes = true;
  565. }
  566. if (MBB.getLogAlignment()) {
  567. OS << (HasAttributes ? ", " : " (");
  568. OS << "align "
  569. << (1UL << MBB.getLogAlignment());
  570. HasAttributes = true;
  571. }
  572. if (HasAttributes)
  573. OS << ")";
  574. OS << ":\n";
  575. bool HasLineAttributes = false;
  576. // Print the successors
  577. bool canPredictProbs = canPredictBranchProbabilities(MBB);
  578. // Even if the list of successors is empty, if we cannot guess it,
  579. // we need to print it to tell the parser that the list is empty.
  580. // This is needed, because MI model unreachable as empty blocks
  581. // with an empty successor list. If the parser would see that
  582. // without the successor list, it would guess the code would
  583. // fallthrough.
  584. if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
  585. !canPredictSuccessors(MBB)) {
  586. OS.indent(2) << "successors: ";
  587. for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
  588. if (I != MBB.succ_begin())
  589. OS << ", ";
  590. OS << printMBBReference(**I);
  591. if (!SimplifyMIR || !canPredictProbs)
  592. OS << '('
  593. << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
  594. << ')';
  595. }
  596. OS << "\n";
  597. HasLineAttributes = true;
  598. }
  599. // Print the live in registers.
  600. const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  601. if (MRI.tracksLiveness() && !MBB.livein_empty()) {
  602. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  603. OS.indent(2) << "liveins: ";
  604. bool First = true;
  605. for (const auto &LI : MBB.liveins()) {
  606. if (!First)
  607. OS << ", ";
  608. First = false;
  609. OS << printReg(LI.PhysReg, &TRI);
  610. if (!LI.LaneMask.all())
  611. OS << ":0x" << PrintLaneMask(LI.LaneMask);
  612. }
  613. OS << "\n";
  614. HasLineAttributes = true;
  615. }
  616. if (HasLineAttributes)
  617. OS << "\n";
  618. bool IsInBundle = false;
  619. for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
  620. const MachineInstr &MI = *I;
  621. if (IsInBundle && !MI.isInsideBundle()) {
  622. OS.indent(2) << "}\n";
  623. IsInBundle = false;
  624. }
  625. OS.indent(IsInBundle ? 4 : 2);
  626. print(MI);
  627. if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
  628. OS << " {";
  629. IsInBundle = true;
  630. }
  631. OS << "\n";
  632. }
  633. if (IsInBundle)
  634. OS.indent(2) << "}\n";
  635. }
  636. void MIPrinter::print(const MachineInstr &MI) {
  637. const auto *MF = MI.getMF();
  638. const auto &MRI = MF->getRegInfo();
  639. const auto &SubTarget = MF->getSubtarget();
  640. const auto *TRI = SubTarget.getRegisterInfo();
  641. assert(TRI && "Expected target register info");
  642. const auto *TII = SubTarget.getInstrInfo();
  643. assert(TII && "Expected target instruction info");
  644. if (MI.isCFIInstruction())
  645. assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  646. SmallBitVector PrintedTypes(8);
  647. bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
  648. unsigned I = 0, E = MI.getNumOperands();
  649. for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
  650. !MI.getOperand(I).isImplicit();
  651. ++I) {
  652. if (I)
  653. OS << ", ";
  654. print(MI, I, TRI, ShouldPrintRegisterTies,
  655. MI.getTypeToPrint(I, PrintedTypes, MRI),
  656. /*PrintDef=*/false);
  657. }
  658. if (I)
  659. OS << " = ";
  660. if (MI.getFlag(MachineInstr::FrameSetup))
  661. OS << "frame-setup ";
  662. if (MI.getFlag(MachineInstr::FrameDestroy))
  663. OS << "frame-destroy ";
  664. if (MI.getFlag(MachineInstr::FmNoNans))
  665. OS << "nnan ";
  666. if (MI.getFlag(MachineInstr::FmNoInfs))
  667. OS << "ninf ";
  668. if (MI.getFlag(MachineInstr::FmNsz))
  669. OS << "nsz ";
  670. if (MI.getFlag(MachineInstr::FmArcp))
  671. OS << "arcp ";
  672. if (MI.getFlag(MachineInstr::FmContract))
  673. OS << "contract ";
  674. if (MI.getFlag(MachineInstr::FmAfn))
  675. OS << "afn ";
  676. if (MI.getFlag(MachineInstr::FmReassoc))
  677. OS << "reassoc ";
  678. if (MI.getFlag(MachineInstr::NoUWrap))
  679. OS << "nuw ";
  680. if (MI.getFlag(MachineInstr::NoSWrap))
  681. OS << "nsw ";
  682. if (MI.getFlag(MachineInstr::IsExact))
  683. OS << "exact ";
  684. if (MI.getFlag(MachineInstr::FPExcept))
  685. OS << "fpexcept ";
  686. OS << TII->getName(MI.getOpcode());
  687. if (I < E)
  688. OS << ' ';
  689. bool NeedComma = false;
  690. for (; I < E; ++I) {
  691. if (NeedComma)
  692. OS << ", ";
  693. print(MI, I, TRI, ShouldPrintRegisterTies,
  694. MI.getTypeToPrint(I, PrintedTypes, MRI));
  695. NeedComma = true;
  696. }
  697. // Print any optional symbols attached to this instruction as-if they were
  698. // operands.
  699. if (MCSymbol *PreInstrSymbol = MI.getPreInstrSymbol()) {
  700. if (NeedComma)
  701. OS << ',';
  702. OS << " pre-instr-symbol ";
  703. MachineOperand::printSymbol(OS, *PreInstrSymbol);
  704. NeedComma = true;
  705. }
  706. if (MCSymbol *PostInstrSymbol = MI.getPostInstrSymbol()) {
  707. if (NeedComma)
  708. OS << ',';
  709. OS << " post-instr-symbol ";
  710. MachineOperand::printSymbol(OS, *PostInstrSymbol);
  711. NeedComma = true;
  712. }
  713. if (const DebugLoc &DL = MI.getDebugLoc()) {
  714. if (NeedComma)
  715. OS << ',';
  716. OS << " debug-location ";
  717. DL->printAsOperand(OS, MST);
  718. }
  719. if (!MI.memoperands_empty()) {
  720. OS << " :: ";
  721. const LLVMContext &Context = MF->getFunction().getContext();
  722. const MachineFrameInfo &MFI = MF->getFrameInfo();
  723. bool NeedComma = false;
  724. for (const auto *Op : MI.memoperands()) {
  725. if (NeedComma)
  726. OS << ", ";
  727. Op->print(OS, MST, SSNs, Context, &MFI, TII);
  728. NeedComma = true;
  729. }
  730. }
  731. }
  732. void MIPrinter::printStackObjectReference(int FrameIndex) {
  733. auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
  734. assert(ObjectInfo != StackObjectOperandMapping.end() &&
  735. "Invalid frame index");
  736. const FrameIndexOperand &Operand = ObjectInfo->second;
  737. MachineOperand::printStackObjectReference(OS, Operand.ID, Operand.IsFixed,
  738. Operand.Name);
  739. }
  740. void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx,
  741. const TargetRegisterInfo *TRI,
  742. bool ShouldPrintRegisterTies, LLT TypeToPrint,
  743. bool PrintDef) {
  744. const MachineOperand &Op = MI.getOperand(OpIdx);
  745. switch (Op.getType()) {
  746. case MachineOperand::MO_Immediate:
  747. if (MI.isOperandSubregIdx(OpIdx)) {
  748. MachineOperand::printTargetFlags(OS, Op);
  749. MachineOperand::printSubRegIdx(OS, Op.getImm(), TRI);
  750. break;
  751. }
  752. LLVM_FALLTHROUGH;
  753. case MachineOperand::MO_Register:
  754. case MachineOperand::MO_CImmediate:
  755. case MachineOperand::MO_FPImmediate:
  756. case MachineOperand::MO_MachineBasicBlock:
  757. case MachineOperand::MO_ConstantPoolIndex:
  758. case MachineOperand::MO_TargetIndex:
  759. case MachineOperand::MO_JumpTableIndex:
  760. case MachineOperand::MO_ExternalSymbol:
  761. case MachineOperand::MO_GlobalAddress:
  762. case MachineOperand::MO_RegisterLiveOut:
  763. case MachineOperand::MO_Metadata:
  764. case MachineOperand::MO_MCSymbol:
  765. case MachineOperand::MO_CFIIndex:
  766. case MachineOperand::MO_IntrinsicID:
  767. case MachineOperand::MO_Predicate:
  768. case MachineOperand::MO_BlockAddress:
  769. case MachineOperand::MO_ShuffleMask: {
  770. unsigned TiedOperandIdx = 0;
  771. if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
  772. TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
  773. const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo();
  774. Op.print(OS, MST, TypeToPrint, PrintDef, /*IsStandalone=*/false,
  775. ShouldPrintRegisterTies, TiedOperandIdx, TRI, TII);
  776. break;
  777. }
  778. case MachineOperand::MO_FrameIndex:
  779. printStackObjectReference(Op.getIndex());
  780. break;
  781. case MachineOperand::MO_RegisterMask: {
  782. auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
  783. if (RegMaskInfo != RegisterMaskIds.end())
  784. OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
  785. else
  786. printCustomRegMask(Op.getRegMask(), OS, TRI);
  787. break;
  788. }
  789. }
  790. }
  791. void llvm::printMIR(raw_ostream &OS, const Module &M) {
  792. yaml::Output Out(OS);
  793. Out << const_cast<Module &>(M);
  794. }
  795. void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
  796. MIRPrinter Printer(OS);
  797. Printer.print(MF);
  798. }