1 //===- MIRYamlMapping.h - Describe mapping between MIR and YAML--*- C++ -*-===//
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 mapping between various MIR data structures and
10 // their corresponding YAML representation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CODEGEN_MIRYAMLMAPPING_H
15 #define LLVM_CODEGEN_MIRYAMLMAPPING_H
16 
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/TargetFrameLowering.h"
21 #include "llvm/Support/SMLoc.h"
22 #include "llvm/Support/YAMLTraits.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <cstdint>
26 #include <string>
27 #include <vector>
28 
29 namespace llvm {
30 namespace yaml {
31 
32 /// A wrapper around std::string which contains a source range that's being
33 /// set during parsing.
34 struct StringValue {
35   std::string Value;
36   SMRange SourceRange;
37 
38   StringValue() = default;
39   StringValue(std::string Value) : Value(std::move(Value)) {}
40   StringValue(const char Val[]) : Value(Val) {}
41 
42   bool operator==(const StringValue &Other) const {
43     return Value == Other.Value;
44   }
45 };
46 
47 template <> struct ScalarTraits<StringValue> {
48   static void output(const StringValue &S, void *, raw_ostream &OS) {
49     OS << S.Value;
50   }
51 
52   static StringRef input(StringRef Scalar, void *Ctx, StringValue &S) {
53     S.Value = Scalar.str();
54     if (const auto *Node =
55             reinterpret_cast<yaml::Input *>(Ctx)->getCurrentNode())
56       S.SourceRange = Node->getSourceRange();
57     return "";
58   }
59 
60   static QuotingType mustQuote(StringRef S) { return needsQuotes(S); }
61 };
62 
63 struct FlowStringValue : StringValue {
64   FlowStringValue() = default;
65   FlowStringValue(std::string Value) : StringValue(std::move(Value)) {}
66 };
67 
68 template <> struct ScalarTraits<FlowStringValue> {
69   static void output(const FlowStringValue &S, void *, raw_ostream &OS) {
70     return ScalarTraits<StringValue>::output(S, nullptr, OS);
71   }
72 
73   static StringRef input(StringRef Scalar, void *Ctx, FlowStringValue &S) {
74     return ScalarTraits<StringValue>::input(Scalar, Ctx, S);
75   }
76 
77   static QuotingType mustQuote(StringRef S) { return needsQuotes(S); }
78 };
79 
80 struct BlockStringValue {
81   StringValue Value;
82 
83   bool operator==(const BlockStringValue &Other) const {
84     return Value == Other.Value;
85   }
86 };
87 
88 template <> struct BlockScalarTraits<BlockStringValue> {
89   static void output(const BlockStringValue &S, void *Ctx, raw_ostream &OS) {
90     return ScalarTraits<StringValue>::output(S.Value, Ctx, OS);
91   }
92 
93   static StringRef input(StringRef Scalar, void *Ctx, BlockStringValue &S) {
94     return ScalarTraits<StringValue>::input(Scalar, Ctx, S.Value);
95   }
96 };
97 
98 /// A wrapper around unsigned which contains a source range that's being set
99 /// during parsing.
100 struct UnsignedValue {
101   unsigned Value = 0;
102   SMRange SourceRange;
103 
104   UnsignedValue() = default;
105   UnsignedValue(unsigned Value) : Value(Value) {}
106 
107   bool operator==(const UnsignedValue &Other) const {
108     return Value == Other.Value;
109   }
110 };
111 
112 template <> struct ScalarTraits<UnsignedValue> {
113   static void output(const UnsignedValue &Value, void *Ctx, raw_ostream &OS) {
114     return ScalarTraits<unsigned>::output(Value.Value, Ctx, OS);
115   }
116 
117   static StringRef input(StringRef Scalar, void *Ctx, UnsignedValue &Value) {
118     if (const auto *Node =
119             reinterpret_cast<yaml::Input *>(Ctx)->getCurrentNode())
120       Value.SourceRange = Node->getSourceRange();
121     return ScalarTraits<unsigned>::input(Scalar, Ctx, Value.Value);
122   }
123 
124   static QuotingType mustQuote(StringRef Scalar) {
125     return ScalarTraits<unsigned>::mustQuote(Scalar);
126   }
127 };
128 
129 template <> struct ScalarEnumerationTraits<MachineJumpTableInfo::JTEntryKind> {
130   static void enumeration(yaml::IO &IO,
131                           MachineJumpTableInfo::JTEntryKind &EntryKind) {
132     IO.enumCase(EntryKind, "block-address",
133                 MachineJumpTableInfo::EK_BlockAddress);
134     IO.enumCase(EntryKind, "gp-rel64-block-address",
135                 MachineJumpTableInfo::EK_GPRel64BlockAddress);
136     IO.enumCase(EntryKind, "gp-rel32-block-address",
137                 MachineJumpTableInfo::EK_GPRel32BlockAddress);
138     IO.enumCase(EntryKind, "label-difference32",
139                 MachineJumpTableInfo::EK_LabelDifference32);
140     IO.enumCase(EntryKind, "inline", MachineJumpTableInfo::EK_Inline);
141     IO.enumCase(EntryKind, "custom32", MachineJumpTableInfo::EK_Custom32);
142   }
143 };
144 
145 template <> struct ScalarTraits<MaybeAlign> {
146   static void output(const MaybeAlign &Alignment, void *,
147                      llvm::raw_ostream &out) {
148     out << uint64_t(Alignment ? Alignment->value() : 0U);
149   }
150   static StringRef input(StringRef Scalar, void *, MaybeAlign &Alignment) {
151     unsigned long long n;
152     if (getAsUnsignedInteger(Scalar, 10, n))
153       return "invalid number";
154     if (n > 0 && !isPowerOf2_64(n))
155       return "must be 0 or a power of two";
156     Alignment = MaybeAlign(n);
157     return StringRef();
158   }
159   static QuotingType mustQuote(StringRef) { return QuotingType::None; }
160 };
161 
162 template <> struct ScalarTraits<Align> {
163   static void output(const Align &Alignment, void *, llvm::raw_ostream &OS) {
164     OS << Alignment.value();
165   }
166   static StringRef input(StringRef Scalar, void *, Align &Alignment) {
167     unsigned long long N;
168     if (getAsUnsignedInteger(Scalar, 10, N))
169       return "invalid number";
170     if (!isPowerOf2_64(N))
171       return "must be a power of two";
172     Alignment = Align(N);
173     return StringRef();
174   }
175   static QuotingType mustQuote(StringRef) { return QuotingType::None; }
176 };
177 
178 } // end namespace yaml
179 } // end namespace llvm
180 
181 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::StringValue)
182 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::FlowStringValue)
183 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::UnsignedValue)
184 
185 namespace llvm {
186 namespace yaml {
187 
188 struct VirtualRegisterDefinition {
189   UnsignedValue ID;
190   StringValue Class;
191   StringValue PreferredRegister;
192 
193   // TODO: Serialize the target specific register hints.
194 
195   bool operator==(const VirtualRegisterDefinition &Other) const {
196     return ID == Other.ID && Class == Other.Class &&
197            PreferredRegister == Other.PreferredRegister;
198   }
199 };
200 
201 template <> struct MappingTraits<VirtualRegisterDefinition> {
202   static void mapping(IO &YamlIO, VirtualRegisterDefinition &Reg) {
203     YamlIO.mapRequired("id", Reg.ID);
204     YamlIO.mapRequired("class", Reg.Class);
205     YamlIO.mapOptional("preferred-register", Reg.PreferredRegister,
206                        StringValue()); // Don't print out when it's empty.
207   }
208 
209   static const bool flow = true;
210 };
211 
212 struct MachineFunctionLiveIn {
213   StringValue Register;
214   StringValue VirtualRegister;
215 
216   bool operator==(const MachineFunctionLiveIn &Other) const {
217     return Register == Other.Register &&
218            VirtualRegister == Other.VirtualRegister;
219   }
220 };
221 
222 template <> struct MappingTraits<MachineFunctionLiveIn> {
223   static void mapping(IO &YamlIO, MachineFunctionLiveIn &LiveIn) {
224     YamlIO.mapRequired("reg", LiveIn.Register);
225     YamlIO.mapOptional(
226         "virtual-reg", LiveIn.VirtualRegister,
227         StringValue()); // Don't print the virtual register when it's empty.
228   }
229 
230   static const bool flow = true;
231 };
232 
233 /// Serializable representation of stack object from the MachineFrameInfo class.
234 ///
235 /// The flags 'isImmutable' and 'isAliased' aren't serialized, as they are
236 /// determined by the object's type and frame information flags.
237 /// Dead stack objects aren't serialized.
238 ///
239 /// The 'isPreallocated' flag is determined by the local offset.
240 struct MachineStackObject {
241   enum ObjectType { DefaultType, SpillSlot, VariableSized };
242   UnsignedValue ID;
243   StringValue Name;
244   // TODO: Serialize unnamed LLVM alloca reference.
245   ObjectType Type = DefaultType;
246   int64_t Offset = 0;
247   uint64_t Size = 0;
248   MaybeAlign Alignment = None;
249   TargetStackID::Value StackID;
250   StringValue CalleeSavedRegister;
251   bool CalleeSavedRestored = true;
252   Optional<int64_t> LocalOffset;
253   StringValue DebugVar;
254   StringValue DebugExpr;
255   StringValue DebugLoc;
256 
257   bool operator==(const MachineStackObject &Other) const {
258     return ID == Other.ID && Name == Other.Name && Type == Other.Type &&
259            Offset == Other.Offset && Size == Other.Size &&
260            Alignment == Other.Alignment &&
261            StackID == Other.StackID &&
262            CalleeSavedRegister == Other.CalleeSavedRegister &&
263            CalleeSavedRestored == Other.CalleeSavedRestored &&
264            LocalOffset == Other.LocalOffset && DebugVar == Other.DebugVar &&
265            DebugExpr == Other.DebugExpr && DebugLoc == Other.DebugLoc;
266   }
267 };
268 
269 template <> struct ScalarEnumerationTraits<MachineStackObject::ObjectType> {
270   static void enumeration(yaml::IO &IO, MachineStackObject::ObjectType &Type) {
271     IO.enumCase(Type, "default", MachineStackObject::DefaultType);
272     IO.enumCase(Type, "spill-slot", MachineStackObject::SpillSlot);
273     IO.enumCase(Type, "variable-sized", MachineStackObject::VariableSized);
274   }
275 };
276 
277 template <> struct MappingTraits<MachineStackObject> {
278   static void mapping(yaml::IO &YamlIO, MachineStackObject &Object) {
279     YamlIO.mapRequired("id", Object.ID);
280     YamlIO.mapOptional("name", Object.Name,
281                        StringValue()); // Don't print out an empty name.
282     YamlIO.mapOptional(
283         "type", Object.Type,
284         MachineStackObject::DefaultType); // Don't print the default type.
285     YamlIO.mapOptional("offset", Object.Offset, (int64_t)0);
286     if (Object.Type != MachineStackObject::VariableSized)
287       YamlIO.mapRequired("size", Object.Size);
288     YamlIO.mapOptional("alignment", Object.Alignment, None);
289     YamlIO.mapOptional("stack-id", Object.StackID, TargetStackID::Default);
290     YamlIO.mapOptional("callee-saved-register", Object.CalleeSavedRegister,
291                        StringValue()); // Don't print it out when it's empty.
292     YamlIO.mapOptional("callee-saved-restored", Object.CalleeSavedRestored,
293                        true);
294     YamlIO.mapOptional("local-offset", Object.LocalOffset, Optional<int64_t>());
295     YamlIO.mapOptional("debug-info-variable", Object.DebugVar,
296                        StringValue()); // Don't print it out when it's empty.
297     YamlIO.mapOptional("debug-info-expression", Object.DebugExpr,
298                        StringValue()); // Don't print it out when it's empty.
299     YamlIO.mapOptional("debug-info-location", Object.DebugLoc,
300                        StringValue()); // Don't print it out when it's empty.
301   }
302 
303   static const bool flow = true;
304 };
305 
306 /// Serializable representation of the fixed stack object from the
307 /// MachineFrameInfo class.
308 struct FixedMachineStackObject {
309   enum ObjectType { DefaultType, SpillSlot };
310   UnsignedValue ID;
311   ObjectType Type = DefaultType;
312   int64_t Offset = 0;
313   uint64_t Size = 0;
314   MaybeAlign Alignment = None;
315   TargetStackID::Value StackID;
316   bool IsImmutable = false;
317   bool IsAliased = false;
318   StringValue CalleeSavedRegister;
319   bool CalleeSavedRestored = true;
320   StringValue DebugVar;
321   StringValue DebugExpr;
322   StringValue DebugLoc;
323 
324   bool operator==(const FixedMachineStackObject &Other) const {
325     return ID == Other.ID && Type == Other.Type && Offset == Other.Offset &&
326            Size == Other.Size && Alignment == Other.Alignment &&
327            StackID == Other.StackID &&
328            IsImmutable == Other.IsImmutable && IsAliased == Other.IsAliased &&
329            CalleeSavedRegister == Other.CalleeSavedRegister &&
330            CalleeSavedRestored == Other.CalleeSavedRestored &&
331            DebugVar == Other.DebugVar && DebugExpr == Other.DebugExpr
332            && DebugLoc == Other.DebugLoc;
333   }
334 };
335 
336 template <>
337 struct ScalarEnumerationTraits<FixedMachineStackObject::ObjectType> {
338   static void enumeration(yaml::IO &IO,
339                           FixedMachineStackObject::ObjectType &Type) {
340     IO.enumCase(Type, "default", FixedMachineStackObject::DefaultType);
341     IO.enumCase(Type, "spill-slot", FixedMachineStackObject::SpillSlot);
342   }
343 };
344 
345 template <>
346 struct ScalarEnumerationTraits<TargetStackID::Value> {
347   static void enumeration(yaml::IO &IO, TargetStackID::Value &ID) {
348     IO.enumCase(ID, "default", TargetStackID::Default);
349     IO.enumCase(ID, "sgpr-spill", TargetStackID::SGPRSpill);
350     IO.enumCase(ID, "scalable-vector", TargetStackID::ScalableVector);
351     IO.enumCase(ID, "wasm-local", TargetStackID::WasmLocal);
352     IO.enumCase(ID, "noalloc", TargetStackID::NoAlloc);
353   }
354 };
355 
356 template <> struct MappingTraits<FixedMachineStackObject> {
357   static void mapping(yaml::IO &YamlIO, FixedMachineStackObject &Object) {
358     YamlIO.mapRequired("id", Object.ID);
359     YamlIO.mapOptional(
360         "type", Object.Type,
361         FixedMachineStackObject::DefaultType); // Don't print the default type.
362     YamlIO.mapOptional("offset", Object.Offset, (int64_t)0);
363     YamlIO.mapOptional("size", Object.Size, (uint64_t)0);
364     YamlIO.mapOptional("alignment", Object.Alignment, None);
365     YamlIO.mapOptional("stack-id", Object.StackID, TargetStackID::Default);
366     if (Object.Type != FixedMachineStackObject::SpillSlot) {
367       YamlIO.mapOptional("isImmutable", Object.IsImmutable, false);
368       YamlIO.mapOptional("isAliased", Object.IsAliased, false);
369     }
370     YamlIO.mapOptional("callee-saved-register", Object.CalleeSavedRegister,
371                        StringValue()); // Don't print it out when it's empty.
372     YamlIO.mapOptional("callee-saved-restored", Object.CalleeSavedRestored,
373                      true);
374     YamlIO.mapOptional("debug-info-variable", Object.DebugVar,
375                        StringValue()); // Don't print it out when it's empty.
376     YamlIO.mapOptional("debug-info-expression", Object.DebugExpr,
377                        StringValue()); // Don't print it out when it's empty.
378     YamlIO.mapOptional("debug-info-location", Object.DebugLoc,
379                        StringValue()); // Don't print it out when it's empty.
380   }
381 
382   static const bool flow = true;
383 };
384 
385 /// A serializaable representation of a reference to a stack object or fixed
386 /// stack object.
387 struct FrameIndex {
388   // The frame index as printed. This is always a positive number, even for
389   // fixed objects. To obtain the real index,
390   // MachineFrameInfo::getObjectIndexBegin has to be added.
391   int FI;
392   bool IsFixed;
393   SMRange SourceRange;
394 
395   FrameIndex() = default;
396   FrameIndex(int FI, const llvm::MachineFrameInfo &MFI);
397 
398   Expected<int> getFI(const llvm::MachineFrameInfo &MFI) const;
399 };
400 
401 template <> struct ScalarTraits<FrameIndex> {
402   static void output(const FrameIndex &FI, void *, raw_ostream &OS) {
403     MachineOperand::printStackObjectReference(OS, FI.FI, FI.IsFixed, "");
404   }
405 
406   static StringRef input(StringRef Scalar, void *Ctx, FrameIndex &FI) {
407     FI.IsFixed = false;
408     StringRef Num;
409     if (Scalar.startswith("%stack.")) {
410       Num = Scalar.substr(7);
411     } else if (Scalar.startswith("%fixed-stack.")) {
412       Num = Scalar.substr(13);
413       FI.IsFixed = true;
414     } else {
415       return "Invalid frame index, needs to start with %stack. or "
416              "%fixed-stack.";
417     }
418     if (Num.consumeInteger(10, FI.FI))
419       return "Invalid frame index, not a valid number";
420 
421     if (const auto *Node =
422             reinterpret_cast<yaml::Input *>(Ctx)->getCurrentNode())
423       FI.SourceRange = Node->getSourceRange();
424     return StringRef();
425   }
426 
427   static QuotingType mustQuote(StringRef S) { return needsQuotes(S); }
428 };
429 
430 /// Serializable representation of CallSiteInfo.
431 struct CallSiteInfo {
432   // Representation of call argument and register which is used to
433   // transfer it.
434   struct ArgRegPair {
435     StringValue Reg;
436     uint16_t ArgNo;
437 
438     bool operator==(const ArgRegPair &Other) const {
439       return Reg == Other.Reg && ArgNo == Other.ArgNo;
440     }
441   };
442 
443   /// Identifies call instruction location in machine function.
444   struct MachineInstrLoc {
445     unsigned BlockNum;
446     unsigned Offset;
447 
448     bool operator==(const MachineInstrLoc &Other) const {
449       return BlockNum == Other.BlockNum && Offset == Other.Offset;
450     }
451   };
452 
453   MachineInstrLoc CallLocation;
454   std::vector<ArgRegPair> ArgForwardingRegs;
455 
456   bool operator==(const CallSiteInfo &Other) const {
457     return CallLocation.BlockNum == Other.CallLocation.BlockNum &&
458            CallLocation.Offset == Other.CallLocation.Offset;
459   }
460 };
461 
462 template <> struct MappingTraits<CallSiteInfo::ArgRegPair> {
463   static void mapping(IO &YamlIO, CallSiteInfo::ArgRegPair &ArgReg) {
464     YamlIO.mapRequired("arg", ArgReg.ArgNo);
465     YamlIO.mapRequired("reg", ArgReg.Reg);
466   }
467 
468   static const bool flow = true;
469 };
470 }
471 }
472 
473 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::CallSiteInfo::ArgRegPair)
474 
475 namespace llvm {
476 namespace yaml {
477 
478 template <> struct MappingTraits<CallSiteInfo> {
479   static void mapping(IO &YamlIO, CallSiteInfo &CSInfo) {
480     YamlIO.mapRequired("bb", CSInfo.CallLocation.BlockNum);
481     YamlIO.mapRequired("offset", CSInfo.CallLocation.Offset);
482     YamlIO.mapOptional("fwdArgRegs", CSInfo.ArgForwardingRegs,
483                        std::vector<CallSiteInfo::ArgRegPair>());
484   }
485 
486   static const bool flow = true;
487 };
488 
489 /// Serializable representation of debug value substitutions.
490 struct DebugValueSubstitution {
491   unsigned SrcInst;
492   unsigned SrcOp;
493   unsigned DstInst;
494   unsigned DstOp;
495   unsigned Subreg;
496 
497   bool operator==(const DebugValueSubstitution &Other) const {
498     return std::tie(SrcInst, SrcOp, DstInst, DstOp) ==
499            std::tie(Other.SrcInst, Other.SrcOp, Other.DstInst, Other.DstOp);
500   }
501 };
502 
503 template <> struct MappingTraits<DebugValueSubstitution> {
504   static void mapping(IO &YamlIO, DebugValueSubstitution &Sub) {
505     YamlIO.mapRequired("srcinst", Sub.SrcInst);
506     YamlIO.mapRequired("srcop", Sub.SrcOp);
507     YamlIO.mapRequired("dstinst", Sub.DstInst);
508     YamlIO.mapRequired("dstop", Sub.DstOp);
509     YamlIO.mapRequired("subreg", Sub.Subreg);
510   }
511 
512   static const bool flow = true;
513 };
514 } // namespace yaml
515 } // namespace llvm
516 
517 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::DebugValueSubstitution)
518 
519 namespace llvm {
520 namespace yaml {
521 struct MachineConstantPoolValue {
522   UnsignedValue ID;
523   StringValue Value;
524   MaybeAlign Alignment = None;
525   bool IsTargetSpecific = false;
526 
527   bool operator==(const MachineConstantPoolValue &Other) const {
528     return ID == Other.ID && Value == Other.Value &&
529            Alignment == Other.Alignment &&
530            IsTargetSpecific == Other.IsTargetSpecific;
531   }
532 };
533 
534 template <> struct MappingTraits<MachineConstantPoolValue> {
535   static void mapping(IO &YamlIO, MachineConstantPoolValue &Constant) {
536     YamlIO.mapRequired("id", Constant.ID);
537     YamlIO.mapOptional("value", Constant.Value, StringValue());
538     YamlIO.mapOptional("alignment", Constant.Alignment, None);
539     YamlIO.mapOptional("isTargetSpecific", Constant.IsTargetSpecific, false);
540   }
541 };
542 
543 struct MachineJumpTable {
544   struct Entry {
545     UnsignedValue ID;
546     std::vector<FlowStringValue> Blocks;
547 
548     bool operator==(const Entry &Other) const {
549       return ID == Other.ID && Blocks == Other.Blocks;
550     }
551   };
552 
553   MachineJumpTableInfo::JTEntryKind Kind = MachineJumpTableInfo::EK_Custom32;
554   std::vector<Entry> Entries;
555 
556   bool operator==(const MachineJumpTable &Other) const {
557     return Kind == Other.Kind && Entries == Other.Entries;
558   }
559 };
560 
561 template <> struct MappingTraits<MachineJumpTable::Entry> {
562   static void mapping(IO &YamlIO, MachineJumpTable::Entry &Entry) {
563     YamlIO.mapRequired("id", Entry.ID);
564     YamlIO.mapOptional("blocks", Entry.Blocks, std::vector<FlowStringValue>());
565   }
566 };
567 
568 } // end namespace yaml
569 } // end namespace llvm
570 
571 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineFunctionLiveIn)
572 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::VirtualRegisterDefinition)
573 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineStackObject)
574 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::FixedMachineStackObject)
575 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::CallSiteInfo)
576 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineConstantPoolValue)
577 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineJumpTable::Entry)
578 
579 namespace llvm {
580 namespace yaml {
581 
582 template <> struct MappingTraits<MachineJumpTable> {
583   static void mapping(IO &YamlIO, MachineJumpTable &JT) {
584     YamlIO.mapRequired("kind", JT.Kind);
585     YamlIO.mapOptional("entries", JT.Entries,
586                        std::vector<MachineJumpTable::Entry>());
587   }
588 };
589 
590 /// Serializable representation of MachineFrameInfo.
591 ///
592 /// Doesn't serialize attributes like 'StackAlignment', 'IsStackRealignable' and
593 /// 'RealignOption' as they are determined by the target and LLVM function
594 /// attributes.
595 /// It also doesn't serialize attributes like 'NumFixedObject' and
596 /// 'HasVarSizedObjects' as they are determined by the frame objects themselves.
597 struct MachineFrameInfo {
598   bool IsFrameAddressTaken = false;
599   bool IsReturnAddressTaken = false;
600   bool HasStackMap = false;
601   bool HasPatchPoint = false;
602   uint64_t StackSize = 0;
603   int OffsetAdjustment = 0;
604   unsigned MaxAlignment = 0;
605   bool AdjustsStack = false;
606   bool HasCalls = false;
607   StringValue StackProtector;
608   StringValue FunctionContext;
609   unsigned MaxCallFrameSize = ~0u; ///< ~0u means: not computed yet.
610   unsigned CVBytesOfCalleeSavedRegisters = 0;
611   bool HasOpaqueSPAdjustment = false;
612   bool HasVAStart = false;
613   bool HasMustTailInVarArgFunc = false;
614   bool HasTailCall = false;
615   unsigned LocalFrameSize = 0;
616   StringValue SavePoint;
617   StringValue RestorePoint;
618 
619   bool operator==(const MachineFrameInfo &Other) const {
620     return IsFrameAddressTaken == Other.IsFrameAddressTaken &&
621            IsReturnAddressTaken == Other.IsReturnAddressTaken &&
622            HasStackMap == Other.HasStackMap &&
623            HasPatchPoint == Other.HasPatchPoint &&
624            StackSize == Other.StackSize &&
625            OffsetAdjustment == Other.OffsetAdjustment &&
626            MaxAlignment == Other.MaxAlignment &&
627            AdjustsStack == Other.AdjustsStack && HasCalls == Other.HasCalls &&
628            StackProtector == Other.StackProtector &&
629            FunctionContext == Other.FunctionContext &&
630            MaxCallFrameSize == Other.MaxCallFrameSize &&
631            CVBytesOfCalleeSavedRegisters ==
632                Other.CVBytesOfCalleeSavedRegisters &&
633            HasOpaqueSPAdjustment == Other.HasOpaqueSPAdjustment &&
634            HasVAStart == Other.HasVAStart &&
635            HasMustTailInVarArgFunc == Other.HasMustTailInVarArgFunc &&
636            HasTailCall == Other.HasTailCall &&
637            LocalFrameSize == Other.LocalFrameSize &&
638            SavePoint == Other.SavePoint && RestorePoint == Other.RestorePoint;
639   }
640 };
641 
642 template <> struct MappingTraits<MachineFrameInfo> {
643   static void mapping(IO &YamlIO, MachineFrameInfo &MFI) {
644     YamlIO.mapOptional("isFrameAddressTaken", MFI.IsFrameAddressTaken, false);
645     YamlIO.mapOptional("isReturnAddressTaken", MFI.IsReturnAddressTaken, false);
646     YamlIO.mapOptional("hasStackMap", MFI.HasStackMap, false);
647     YamlIO.mapOptional("hasPatchPoint", MFI.HasPatchPoint, false);
648     YamlIO.mapOptional("stackSize", MFI.StackSize, (uint64_t)0);
649     YamlIO.mapOptional("offsetAdjustment", MFI.OffsetAdjustment, (int)0);
650     YamlIO.mapOptional("maxAlignment", MFI.MaxAlignment, (unsigned)0);
651     YamlIO.mapOptional("adjustsStack", MFI.AdjustsStack, false);
652     YamlIO.mapOptional("hasCalls", MFI.HasCalls, false);
653     YamlIO.mapOptional("stackProtector", MFI.StackProtector,
654                        StringValue()); // Don't print it out when it's empty.
655     YamlIO.mapOptional("functionContext", MFI.FunctionContext,
656                        StringValue()); // Don't print it out when it's empty.
657     YamlIO.mapOptional("maxCallFrameSize", MFI.MaxCallFrameSize, (unsigned)~0);
658     YamlIO.mapOptional("cvBytesOfCalleeSavedRegisters",
659                        MFI.CVBytesOfCalleeSavedRegisters, 0U);
660     YamlIO.mapOptional("hasOpaqueSPAdjustment", MFI.HasOpaqueSPAdjustment,
661                        false);
662     YamlIO.mapOptional("hasVAStart", MFI.HasVAStart, false);
663     YamlIO.mapOptional("hasMustTailInVarArgFunc", MFI.HasMustTailInVarArgFunc,
664                        false);
665     YamlIO.mapOptional("hasTailCall", MFI.HasTailCall, false);
666     YamlIO.mapOptional("localFrameSize", MFI.LocalFrameSize, (unsigned)0);
667     YamlIO.mapOptional("savePoint", MFI.SavePoint,
668                        StringValue()); // Don't print it out when it's empty.
669     YamlIO.mapOptional("restorePoint", MFI.RestorePoint,
670                        StringValue()); // Don't print it out when it's empty.
671   }
672 };
673 
674 /// Targets should override this in a way that mirrors the implementation of
675 /// llvm::MachineFunctionInfo.
676 struct MachineFunctionInfo {
677   virtual ~MachineFunctionInfo() = default;
678   virtual void mappingImpl(IO &YamlIO) {}
679 };
680 
681 template <> struct MappingTraits<std::unique_ptr<MachineFunctionInfo>> {
682   static void mapping(IO &YamlIO, std::unique_ptr<MachineFunctionInfo> &MFI) {
683     if (MFI)
684       MFI->mappingImpl(YamlIO);
685   }
686 };
687 
688 struct MachineFunction {
689   StringRef Name;
690   MaybeAlign Alignment = None;
691   bool ExposesReturnsTwice = false;
692   // GISel MachineFunctionProperties.
693   bool Legalized = false;
694   bool RegBankSelected = false;
695   bool Selected = false;
696   bool FailedISel = false;
697   // Register information
698   bool TracksRegLiveness = false;
699   bool HasWinCFI = false;
700 
701   bool CallsEHReturn = false;
702   bool CallsUnwindInit = false;
703   bool HasEHCatchret = false;
704   bool HasEHScopes = false;
705   bool HasEHFunclets = false;
706 
707   bool FailsVerification = false;
708   bool TracksDebugUserValues = false;
709   std::vector<VirtualRegisterDefinition> VirtualRegisters;
710   std::vector<MachineFunctionLiveIn> LiveIns;
711   Optional<std::vector<FlowStringValue>> CalleeSavedRegisters;
712   // TODO: Serialize the various register masks.
713   // Frame information
714   MachineFrameInfo FrameInfo;
715   std::vector<FixedMachineStackObject> FixedStackObjects;
716   std::vector<MachineStackObject> StackObjects;
717   std::vector<MachineConstantPoolValue> Constants; /// Constant pool.
718   std::unique_ptr<MachineFunctionInfo> MachineFuncInfo;
719   std::vector<CallSiteInfo> CallSitesInfo;
720   std::vector<DebugValueSubstitution> DebugValueSubstitutions;
721   MachineJumpTable JumpTableInfo;
722   std::vector<StringValue> MachineMetadataNodes;
723   BlockStringValue Body;
724 };
725 
726 template <> struct MappingTraits<MachineFunction> {
727   static void mapping(IO &YamlIO, MachineFunction &MF) {
728     YamlIO.mapRequired("name", MF.Name);
729     YamlIO.mapOptional("alignment", MF.Alignment, None);
730     YamlIO.mapOptional("exposesReturnsTwice", MF.ExposesReturnsTwice, false);
731     YamlIO.mapOptional("legalized", MF.Legalized, false);
732     YamlIO.mapOptional("regBankSelected", MF.RegBankSelected, false);
733     YamlIO.mapOptional("selected", MF.Selected, false);
734     YamlIO.mapOptional("failedISel", MF.FailedISel, false);
735     YamlIO.mapOptional("tracksRegLiveness", MF.TracksRegLiveness, false);
736     YamlIO.mapOptional("hasWinCFI", MF.HasWinCFI, false);
737 
738     YamlIO.mapOptional("callsEHReturn", MF.CallsEHReturn, false);
739     YamlIO.mapOptional("callsUnwindInit", MF.CallsUnwindInit, false);
740     YamlIO.mapOptional("hasEHCatchret", MF.HasEHCatchret, false);
741     YamlIO.mapOptional("hasEHScopes", MF.HasEHScopes, false);
742     YamlIO.mapOptional("hasEHFunclets", MF.HasEHFunclets, false);
743 
744     YamlIO.mapOptional("failsVerification", MF.FailsVerification, false);
745     YamlIO.mapOptional("tracksDebugUserValues", MF.TracksDebugUserValues,
746                        false);
747     YamlIO.mapOptional("registers", MF.VirtualRegisters,
748                        std::vector<VirtualRegisterDefinition>());
749     YamlIO.mapOptional("liveins", MF.LiveIns,
750                        std::vector<MachineFunctionLiveIn>());
751     YamlIO.mapOptional("calleeSavedRegisters", MF.CalleeSavedRegisters,
752                        Optional<std::vector<FlowStringValue>>());
753     YamlIO.mapOptional("frameInfo", MF.FrameInfo, MachineFrameInfo());
754     YamlIO.mapOptional("fixedStack", MF.FixedStackObjects,
755                        std::vector<FixedMachineStackObject>());
756     YamlIO.mapOptional("stack", MF.StackObjects,
757                        std::vector<MachineStackObject>());
758     YamlIO.mapOptional("callSites", MF.CallSitesInfo,
759                        std::vector<CallSiteInfo>());
760     YamlIO.mapOptional("debugValueSubstitutions", MF.DebugValueSubstitutions,
761                        std::vector<DebugValueSubstitution>());
762     YamlIO.mapOptional("constants", MF.Constants,
763                        std::vector<MachineConstantPoolValue>());
764     YamlIO.mapOptional("machineFunctionInfo", MF.MachineFuncInfo);
765     if (!YamlIO.outputting() || !MF.JumpTableInfo.Entries.empty())
766       YamlIO.mapOptional("jumpTable", MF.JumpTableInfo, MachineJumpTable());
767     if (!YamlIO.outputting() || !MF.MachineMetadataNodes.empty())
768       YamlIO.mapOptional("machineMetadataNodes", MF.MachineMetadataNodes,
769                          std::vector<StringValue>());
770     YamlIO.mapOptional("body", MF.Body, BlockStringValue());
771   }
772 };
773 
774 } // end namespace yaml
775 } // end namespace llvm
776 
777 #endif // LLVM_CODEGEN_MIRYAMLMAPPING_H
778