aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/MIR/MIRMetadataParser.cpp
blob: 6ce717bc26a1e0467ddbfc3b5dc1faf9df7fcf52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// SPDX-License-Identifier: GPL-3.0-or-later

#include "MIRDocumentParser.h"
#include "MIRDocumentReferenceValidation.h"
#include "MIRMetadataTextParser.h"
#include "MIRParserUtilities.h"
#include "rcc/CodeGen/MachineBasicBlock.h"
#include "rcc/CodeGen/MachineConstantPool.h"
#include "rcc/CodeGen/MachineFrameInfo.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineFunctionAttributes.h"
#include "rcc/CodeGen/MachineFunctionProperties.h"
#include "rcc/CodeGen/MachineFunctionRecords.h"
#include "rcc/CodeGen/MachineInstr.h"
#include "rcc/CodeGen/MachineJumpTableInfo.h"
#include "rcc/CodeGen/MachineMetadata.h"
#include "rcc/CodeGen/MachineRegisterInfo.h"
#include "rcc/CodeGen/MachineVerifier.h"
#include "rcc/CodeGen/TargetDescription.h"
#include "rcc/CodeGen/TargetMIRTextInfo.h"
#include "rcc/CodeGen/TargetRegisterInfo.h"
#include "rcc/MIR/LLVMConstantSyntax.h"

#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <limits>
#include <optional>
#include <ranges>
#include <span>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

namespace rcc::mir {

using parser_detail::parseBool;
using parser_detail::parsePrefixedID;
using parser_detail::parseSigned;
using parser_detail::parseUnsigned;
using parser_detail::parseUnsigned32;
using parser_detail::trim;

Expected<MachineMetadataReference>
MIRDocumentParser::resolveMetadataReference(const MachineFunction &Function,
                                            std::uint32_t Slot) const {
  if (ActiveDocument != nullptr && ActiveDocument->EmbeddedIR &&
      ActiveDocument->EmbeddedIR->metadata(std::to_string(Slot)) != nullptr) {
    return MachineMetadataReference::embeddedIR(Slot);
  }
  if (Function.metadata().node(Slot) != nullptr)
    return MachineMetadataReference::machineFunction(Slot);
  return makeUnexpected(ErrorCode::ParseError,
                        "metadata reference uses undefined slot '!" + std::to_string(Slot) + "'");
}

bool MIRDocumentParser::parseVariableDebugInfo(const yaml::Node &Entry, MachineFunction &Function,
                                               MachineVariableDebugInfo &DebugInfo) {
  const auto Resolve = [this, &Function](std::uint32_t Slot) {
    return resolveMetadataReference(Function, Slot);
  };
  if (const yaml::Node *VariableNode = mappingValue(Entry, "debug-info-variable")) {
    std::string_view Text;
    if (scalar(*VariableNode, Text, "debug variable"))
      return true;
    if (!Text.empty()) {
      MetadataTextParser Parser(std::string(Text), Resolve);
      auto Reference = Parser.parseReferenceOnly();
      if (!Reference)
        return importError(VariableNode->range(), Reference.error(), "mir-debug-metadata");
      if (Reference->scope() != MachineMetadataScope::EmbeddedIR) {
        return fail(VariableNode->range(),
                    "debug variable must reference embedded LLVM IR metadata",
                    "mir-debug-metadata");
      }
      DebugInfo.Variable = *Reference;
    }
  }
  if (const yaml::Node *ExpressionNode = mappingValue(Entry, "debug-info-expression")) {
    std::string_view Text;
    if (scalar(*ExpressionNode, Text, "debug expression"))
      return true;
    if (!Text.empty()) {
      MetadataTextParser Parser(std::string(Text), Resolve);
      auto Value = Parser.parseValue();
      if (!Value)
        return importError(ExpressionNode->range(), Value.error(), "mir-debug-metadata");
      if (Value->reference() != nullptr &&
          Value->reference()->scope() != MachineMetadataScope::EmbeddedIR) {
        return fail(ExpressionNode->range(),
                    "debug expression reference must use embedded LLVM IR metadata",
                    "mir-debug-metadata");
      }
      DebugInfo.Expression = std::move(*Value);
    }
  }
  if (const yaml::Node *LocationNode = mappingValue(Entry, "debug-info-location")) {
    std::string_view Text;
    if (scalar(*LocationNode, Text, "debug location"))
      return true;
    if (!Text.empty()) {
      MetadataTextParser Parser(std::string(Text), Resolve);
      auto Location = Parser.parseLocation();
      if (!Location)
        return importError(LocationNode->range(), Location.error(), "mir-debug-metadata");
      if (Location->reference() != nullptr &&
          Location->reference()->scope() != MachineMetadataScope::EmbeddedIR) {
        return fail(LocationNode->range(),
                    "variable debug location must reference embedded LLVM IR metadata",
                    "mir-debug-metadata");
      }
      DebugInfo.Location = std::move(*Location);
    }
  }
  if (!DebugInfo.Variable && !DebugInfo.Expression && !DebugInfo.Location)
    return false;
  auto Verification = DebugInfo.verifyStructure();
  if (!Verification)
    return importError(Entry.range(), Verification.error(), "mir-debug-metadata");
  return false;
}

bool MIRDocumentParser::parseMetadata(const yaml::Node &Root, MachineFunction &Function,
                                      MIParserContext &Context) {
  if (ActiveDocument->EmbeddedIR) {
    for (const EmbeddedIRMetadataDefinition &Reference :
         ActiveDocument->EmbeddedIR->metadataDefinitions()) {
      std::uint32_t ID = 0;
      if (!parseUnsigned32(Reference.Name, ID))
        continue;
      if (std::ranges::any_of(Context.Metadata,
                              [ID](const MIMetadataSlot &Slot) { return Slot.TextID == ID; })) {
        return fail(Root.range(), "embedded LLVM IR metadata slots are not unique");
      }
      Context.Metadata.push_back(
          {.TextID = ID, .Reference = MachineMetadataReference::embeddedIR(ID)});
    }
  }

  const yaml::Node *Metadata = mappingValue(Root, "machineMetadataNodes");
  if (Metadata == nullptr)
    return false;
  if (requireKind(*Metadata, yaml::NodeKind::Sequence, "machine metadata nodes"))
    return true;

  struct Definition final {
    const yaml::Node *Node = nullptr;
    std::uint32_t Slot = 0;
    bool IsDistinct = false;
    std::string_view Elements;
  };
  std::vector<Definition> Definitions;
  std::unordered_set<std::uint32_t> Slots;

  for (const yaml::NodeID DefinitionID : Metadata->sequence()) {
    const yaml::Node *DefinitionNode = node(DefinitionID);
    std::string_view Text;
    if (DefinitionNode == nullptr || scalar(*DefinitionNode, Text, "machine metadata definition")) {
      return true;
    }
    Text = trim(Text);
    if (!Text.starts_with('!'))
      return fail(DefinitionNode->range(), "machine metadata definition must start with '!N'");
    const std::size_t Equals = Text.find('=');
    if (Equals == std::string_view::npos)
      return fail(DefinitionNode->range(), "machine metadata definition requires '='");
    std::uint32_t Slot = 0;
    if (!parseUnsigned32(trim(Text.substr(1, Equals - 1)), Slot))
      return fail(DefinitionNode->range(), "machine metadata definition has an invalid slot");
    if (!Slots.insert(Slot).second)
      return fail(DefinitionNode->range(), "duplicate machine metadata slot");
    std::string_view Right = trim(Text.substr(Equals + 1));
    bool IsDistinct = false;
    if (Right.starts_with("distinct")) {
      Right = trim(Right.substr(std::string_view("distinct").size()));
      IsDistinct = true;
    }
    if (!Right.starts_with("!{") || !Right.ends_with('}'))
      return fail(DefinitionNode->range(), "machine metadata node must be a metadata tuple");
    Definitions.push_back({.Node = DefinitionNode,
                           .Slot = Slot,
                           .IsDistinct = IsDistinct,
                           .Elements = Right.substr(2, Right.size() - 3)});
    Context.Metadata.push_back(
        {.TextID = Slot, .Reference = MachineMetadataReference::machineFunction(Slot)});
  }

  auto ResolveReference = [this,
                           &Slots](std::uint32_t Slot,
                                   const TextRange &Range) -> Expected<MachineMetadataElement> {
    MachineMetadataReference Reference;
    if (ActiveDocument->EmbeddedIR != std::nullopt &&
        ActiveDocument->EmbeddedIR->metadata(std::to_string(Slot)) != nullptr) {
      Reference = MachineMetadataReference::embeddedIR(Slot);
    } else if (Slots.contains(Slot)) {
      Reference = MachineMetadataReference::machineFunction(Slot);
    } else {
      return makeUnexpected(ErrorCode::ParseError, "metadata tuple references undefined slot '!" +
                                                       std::to_string(Slot) + "' at line " +
                                                       std::to_string(Range.Begin.Line));
    }
    return MachineMetadataElement::reference(Reference);
  };

  for (const Definition &Definition : Definitions) {
    MachineMetadataNode NewNode{
        .Slot = Definition.Slot,
        .IsDistinct = Definition.IsDistinct,
        .Elements = {},
    };
    std::string_view Remaining = trim(Definition.Elements);
    while (!Remaining.empty()) {
      std::size_t End = 0;
      bool InString = false;
      bool Escaped = false;
      for (; End < Remaining.size(); ++End) {
        const char Character = Remaining[End];
        if (InString && Escaped) {
          Escaped = false;
          continue;
        }
        if (InString && Character == '\\') {
          Escaped = true;
          continue;
        }
        if (Character == '"') {
          InString = !InString;
          continue;
        }
        if (!InString && Character == ',')
          break;
      }
      if (InString)
        return fail(Definition.Node->range(), "unterminated machine metadata string");
      std::string_view Element = trim(Remaining.substr(0, End));
      if (Element.empty())
        return fail(Definition.Node->range(), "empty machine metadata tuple element");

      if (Element == "null") {
        NewNode.Elements.push_back(MachineMetadataElement::null());
      } else if (Element.starts_with('!') && Element.size() > 1 && Element[1] >= '0' &&
                 Element[1] <= '9') {
        std::uint32_t ReferenceSlot = 0;
        if (!parseUnsigned32(Element.substr(1), ReferenceSlot))
          return fail(Definition.Node->range(), "invalid metadata tuple reference");
        auto Reference = ResolveReference(ReferenceSlot, Definition.Node->range());
        if (!Reference)
          return importError(Definition.Node->range(), Reference.error());
        NewNode.Elements.push_back(std::move(*Reference));
      } else if (Element.starts_with("!\"") && Element.ends_with('"')) {
        std::string Value;
        std::string_view Encoded = Element.substr(2, Element.size() - 3);
        for (std::size_t Index = 0; Index < Encoded.size(); ++Index) {
          if (Encoded[Index] == '\\' && Index + 1 < Encoded.size()) {
            const char EscapedCharacter = Encoded[++Index];
            if (EscapedCharacter != '\\' && EscapedCharacter != '"')
              return fail(Definition.Node->range(), "unsupported machine metadata string escape");
            Value.push_back(EscapedCharacter);
          } else {
            Value.push_back(Encoded[Index]);
          }
        }
        NewNode.Elements.push_back(MachineMetadataElement::string(std::move(Value)));
      } else {
        return fail(Definition.Node->range(), "unsupported machine metadata tuple element");
      }

      if (End == Remaining.size())
        Remaining = {};
      else
        Remaining = trim(Remaining.substr(End + 1));
    }
    auto AddResult = Function.metadata().addNode(std::move(NewNode));
    if (!AddResult)
      return importError(Definition.Node->range(), AddResult.error());
  }
  return false;
}

} // namespace rcc::mir