MIRPrinter.cpp 34 KB

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