aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/Target/RISCV/RISCVTargetObjectFile.cpp
blob: 9a8aebb82464570ab97d2c47af22b269e343d001 (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
// SPDX-License-Identifier: GPL-3.0-or-later

#include "RISCVTargetObjectFile.h"

#include "rcc/CodeGen/GlobalObject.h"
#include "rcc/CodeGen/MachineConstantPool.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineJumpTableInfo.h"
#include "rcc/CodeGen/MachineMCContext.h"
#include "rcc/CodeGen/TargetConstant.h"
#include "rcc/MC/MCContext.h"
#include "rcc/MC/MCSymbol.h"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <ranges>
#include <string>

namespace rcc::riscv {
namespace {

[[nodiscard]] bool initializerIsZero(const GlobalInitializer &Initializer, std::size_t Depth = 0) {
  if (Depth > 1024)
    return false;
  switch (Initializer.kind()) {
  case GlobalInitializer::Kind::Integer: {
    const auto *Value = Initializer.getIf<APInt>();
    return Value != nullptr &&
           std::ranges::all_of(Value->words(), [](std::uint64_t Word) { return Word == 0; });
  }
  case GlobalInitializer::Kind::Floating: {
    const auto *Value = Initializer.getIf<APFloat>();
    return Value != nullptr &&
           std::ranges::all_of(Value->words(), [](std::uint64_t Word) { return Word == 0; });
  }
  case GlobalInitializer::Kind::Bytes: {
    const auto *Value = Initializer.getIf<std::vector<std::byte>>();
    return Value != nullptr &&
           std::ranges::all_of(*Value, [](std::byte Byte) { return Byte == std::byte{0}; });
  }
  case GlobalInitializer::Kind::ZeroFill:
  case GlobalInitializer::Kind::UndefinedStorage:
    return true;
  case GlobalInitializer::Kind::Repeated: {
    const auto *Value = Initializer.getIf<GlobalRepeatedInitializer>();
    return Value != nullptr && Value->Value && initializerIsZero(*Value->Value, Depth + 1);
  }
  case GlobalInitializer::Kind::Aggregate: {
    const auto *Value = Initializer.getIf<GlobalAggregateInitializer>();
    return Value != nullptr && std::ranges::all_of(Value->Elements, [Depth](const auto &Element) {
             return Element && initializerIsZero(*Element, Depth + 1);
           });
  }
  case GlobalInitializer::Kind::AlignmentPadding: {
    const auto *Value = Initializer.getIf<GlobalAlignmentPadding>();
    return Value != nullptr && Value->Fill == 0;
  }
  case GlobalInitializer::Kind::Target: {
    const auto *Value = Initializer.getIf<TargetConstant>();
    if (Value == nullptr)
      return false;
    auto Emission = Value->emit();
    return Emission && Emission->Fixups.empty() &&
           std::ranges::all_of(Emission->Bytes,
                               [](std::byte Byte) { return Byte == std::byte{0}; });
  }
  case GlobalInitializer::Kind::Invalid:
  case GlobalInitializer::Kind::SymbolAddress:
  case GlobalInitializer::Kind::SymbolDifference:
    return false;
  }
  return false;
}

[[nodiscard]] bool initializerHasRelocation(const GlobalInitializer &Initializer,
                                            std::size_t Depth = 0) {
  if (Depth > 1024)
    return true;
  switch (Initializer.kind()) {
  case GlobalInitializer::Kind::SymbolAddress:
  case GlobalInitializer::Kind::SymbolDifference:
    return true;
  case GlobalInitializer::Kind::Repeated: {
    const auto *Value = Initializer.getIf<GlobalRepeatedInitializer>();
    return Value == nullptr || !Value->Value || initializerHasRelocation(*Value->Value, Depth + 1);
  }
  case GlobalInitializer::Kind::Aggregate: {
    const auto *Value = Initializer.getIf<GlobalAggregateInitializer>();
    return Value == nullptr || std::ranges::any_of(Value->Elements, [Depth](const auto &Element) {
             return !Element || initializerHasRelocation(*Element, Depth + 1);
           });
  }
  case GlobalInitializer::Kind::Target: {
    const auto *Value = Initializer.getIf<TargetConstant>();
    if (Value == nullptr)
      return true;
    auto Emission = Value->emit();
    return !Emission || !Emission->Fixups.empty();
  }
  case GlobalInitializer::Kind::Invalid:
    return true;
  case GlobalInitializer::Kind::Integer:
  case GlobalInitializer::Kind::Floating:
  case GlobalInitializer::Kind::Bytes:
  case GlobalInitializer::Kind::ZeroFill:
  case GlobalInitializer::Kind::AlignmentPadding:
  case GlobalInitializer::Kind::UndefinedStorage:
    return false;
  }
  return true;
}

[[nodiscard]] mc::MCSectionDesc textSectionDescription() {
  return mc::MCSectionDesc{
      .Name = ".text",
      .Kind = mc::MCSectionKind::Text,
      .Flags = {mc::MCSectionFlag::Alloc, mc::MCSectionFlag::Executable},
      .Alignment = 4,
      .EntrySize = 0,
      .Group = {},
      .UniqueID = std::nullopt,
  };
}

[[nodiscard]] mc::MCSectionDesc readOnlySectionDescription() {
  return mc::MCSectionDesc{
      .Name = ".rodata",
      .Kind = mc::MCSectionKind::ReadOnly,
      .Flags = {mc::MCSectionFlag::Alloc},
      .Alignment = 1,
      .EntrySize = 0,
      .Group = {},
      .UniqueID = std::nullopt,
  };
}

} // namespace

Expected<mc::MCSectionDesc> RISCVELFTargetObjectFile::textSection(const MachineFunction &) const {
  return textSectionDescription();
}

Expected<mc::MCSectionDesc>
RISCVELFTargetObjectFile::globalSection(const GlobalObjectDesc &Object,
                                        MachineMCContext &Context) const {
  if (Object.AddressSpace != 0) {
    return makeUnexpected(ErrorCode::Unsupported,
                          "RV64GC assembly does not support nonzero global address spaces");
  }
  if (Object.TargetFlags != 0 || !Object.TargetAttributes.empty()) {
    return makeUnexpected(ErrorCode::Unsupported,
                          "RV64GC assembly does not recognize this global target state");
  }
  const bool IsTLS = Object.TLSModel != GlobalTLSModel::None;
  const bool IsZero = Object.Initializer && initializerIsZero(*Object.Initializer);
  const bool HasRelocation = Object.Initializer && initializerHasRelocation(*Object.Initializer);

  mc::MCSectionDesc Result;
  Result.Alignment = Object.Align.bytes();
  if (IsTLS) {
    Result.Name = IsZero ? ".tbss" : ".tdata";
    Result.Kind = IsZero ? mc::MCSectionKind::TLSBSS : mc::MCSectionKind::TLSData;
    Result.Flags = {mc::MCSectionFlag::Alloc, mc::MCSectionFlag::Writable, mc::MCSectionFlag::TLS};
  } else if (Object.IsConstant && HasRelocation) {
    Result.Name = ".data.rel.ro";
    Result.Kind = mc::MCSectionKind::Data;
    Result.Flags = {mc::MCSectionFlag::Alloc, mc::MCSectionFlag::Writable};
  } else if (Object.IsConstant) {
    Result = readOnlySectionDescription();
    Result.Alignment = Object.Align.bytes();
  } else if (IsZero) {
    Result.Name = ".bss";
    Result.Kind = mc::MCSectionKind::BSS;
    Result.Flags = {mc::MCSectionFlag::Alloc, mc::MCSectionFlag::Writable};
  } else {
    Result.Name = ".data";
    Result.Kind = mc::MCSectionKind::Data;
    Result.Flags = {mc::MCSectionFlag::Alloc, mc::MCSectionFlag::Writable};
  }

  if (Object.Section)
    Result.Name = *Object.Section;
  if (Object.COMDAT) {
    auto Group = Context.symbol(*Object.COMDAT);
    if (!Group)
      return std::unexpected(Group.error());
    Result.Flags.set(mc::MCSectionFlag::Group);
    Result.Group = std::move(*Group);
    if (!Object.Section)
      Result.Name += "." + Object.Symbol;
  }
  return Result;
}

Expected<mc::MCSectionDesc>
RISCVELFTargetObjectFile::constantPoolSection(const MachineFunction &Function,
                                              const MachineConstantPoolEntry &Entry) const {
  const MachineConstantPoolEntryDesc *Description = Entry.description();
  if (Description == nullptr)
    return makeUnexpected(ErrorCode::InvalidArgument, "constant-pool entry is not live");
  if (Description->Placement.Section == ConstantPoolSectionKind::TextAdjacent)
    return textSectionDescription();

  mc::MCSectionDesc Result = readOnlySectionDescription();
  if (Description->Placement.Section == ConstantPoolSectionKind::Data) {
    Result.Name = ".data";
    Result.Kind = mc::MCSectionKind::Data;
    Result.Flags.set(mc::MCSectionFlag::Writable);
  } else if (Description->Placement.Section == ConstantPoolSectionKind::Target) {
    return makeUnexpected(ErrorCode::Unsupported,
                          "RV64GC constant pool has an unknown target section");
  } else if (Description->Placement.Section == ConstantPoolSectionKind::MergeableReadOnly) {
    Result.Name = ".rodata.cst" + std::to_string(Description->Size);
    Result.Flags.set(mc::MCSectionFlag::Merge);
    Result.EntrySize = Description->Size;
  }
  if (Description->Placement.UniqueSection) {
    Result.Name += "." + std::to_string(Function.stableID().value()) + "." +
                   std::to_string(Entry.index().value());
    Result.UniqueID = static_cast<std::uint64_t>(Entry.index().value()) + 1U;
  }
  Result.Alignment = Description->Align.bytes();
  return Result;
}

Expected<mc::MCSectionDesc>
RISCVELFTargetObjectFile::jumpTableSection(const MachineFunction &Function,
                                           const MachineJumpTableEntry &Entry) const {
  const MachineJumpTableDesc *Description = Entry.description();
  if (Description == nullptr)
    return makeUnexpected(ErrorCode::InvalidArgument, "jump-table entry is not live");
  mc::MCSectionDesc Result = Description->Placement.InTextSection ? textSectionDescription()
                                                                  : readOnlySectionDescription();
  if (Description->Placement.UniqueSection) {
    Result.Name += "." + std::to_string(Function.stableID().value()) + ".jt." +
                   std::to_string(Entry.index().value());
    Result.UniqueID = static_cast<std::uint64_t>(Entry.index().value()) + 1U;
  }
  Result.Alignment = Description->Align.bytes();
  return Result;
}

} // namespace rcc::riscv