summaryrefslogtreecommitdiffhomepage
path: root/asm/intel64/encode.cpp
blob: c02349c1d53fc90430087e25bb5042ff073f298c (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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Intel specific conversion: Abstract Graph -> Machine specific segment
#include "encode.h"

#include "asm/assembler.h"
#include "asm/parse.h"
#include "byteorder.h"
#include "minicc.h"

#include <algorithm>
#include <exception>

namespace {

std::shared_ptr<Op> makeLoadValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::Constant)) {
  FlowGraph::Constant& value {dynamic_cast<FlowGraph::Constant&>(data_storage)};
  if (value.value().size() < sizeof(uint32_t))
   throw std::runtime_error("ICE: Int data from operand needs at least 4 bytes, got "s + std::to_string(value.value().size()));

  uint32_t immediate = endian::from_little32(value.value());

  return makeOp("mov", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Immediate32(immediate)}});
 } else if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  return makeOp("mov", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4)}});
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at load: "s + demangle(typeid(data_storage)));
}

std::shared_ptr<Op> makeStoreValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  return makeOp("mov", Asm::Args{{Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4), Asm::Args::Register32("eax")}});
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at store: "s  + demangle(typeid(data_storage)));
}

std::shared_ptr<Op> makeAddValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::Constant)) {
  FlowGraph::Constant& value {dynamic_cast<FlowGraph::Constant&>(data_storage)};
  if (value.value().size() < sizeof(uint32_t))
   throw std::runtime_error("ICE: Int data from operand needs at least 4 bytes, got "s + std::to_string(value.value().size()));

  uint32_t immediate = endian::from_little32(value.value());

  return makeOp("add", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Immediate32(immediate)}});
 } else if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  return makeOp("add", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4)}});
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at add: "s + demangle(typeid(data_storage)));
}

std::shared_ptr<Op> makeSubValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::Constant)) {
  FlowGraph::Constant& value {dynamic_cast<FlowGraph::Constant&>(data_storage)};
  if (value.value().size() < sizeof(uint32_t))
   throw std::runtime_error("ICE: Int data from operand needs at least 4 bytes, got "s + std::to_string(value.value().size()));

  uint32_t immediate = endian::from_little32(value.value());

  return makeOp("sub", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Immediate32(immediate)}});
 } else if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  return makeOp("sub", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4)}});
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at sub: "s + demangle(typeid(data_storage)));
}

std::vector<std::shared_ptr<Chunk>> makeMulValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::Constant)) {
  FlowGraph::Constant& value {dynamic_cast<FlowGraph::Constant&>(data_storage)};
  if (value.value().size() < sizeof(uint32_t))
   throw std::runtime_error("ICE: Int data from operand needs at least 4 bytes, got "s + std::to_string(value.value().size()));

  uint32_t immediate = endian::from_little32(value.value());

  return {{
   makeOp("mov", Asm::Args{{Asm::Args::Register32("ebx"), Asm::Args::Immediate32(immediate)}}),
   makeOp("mul", Asm::Args{{Asm::Args::Register32("ebx")}})
  }};
 } else if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  return {{makeOp("mul", Asm::Args{{Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4)}})}};
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at mul: "s + demangle(typeid(data_storage)));
}

std::vector<std::shared_ptr<Chunk>> makeDivValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::Constant)) {
  FlowGraph::Constant& value {dynamic_cast<FlowGraph::Constant&>(data_storage)};
  if (value.value().size() < sizeof(uint32_t))
   throw std::runtime_error("ICE: Int data from operand needs at least 4 bytes, got "s + std::to_string(value.value().size()));

  uint32_t immediate = endian::from_little32(value.value());

  return {{
   makeOp("mov", Asm::Args{{Asm::Args::Register32("ebx"), Asm::Args::Immediate32(immediate)}}),
   makeOp("div", Asm::Args{{Asm::Args::Register32("ebx")}})
  }};
 } else if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  return {{makeOp("div", Asm::Args{{Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4)}})}};
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at div: "s + demangle(typeid(data_storage)));
}

std::vector<std::shared_ptr<Chunk>> makeShiftLeftValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::Constant)) {
  FlowGraph::Constant& value {dynamic_cast<FlowGraph::Constant&>(data_storage)};
  if (value.value().size() < sizeof(uint32_t))
   throw std::runtime_error("ICE: Int data from operand needs at least 4 bytes, got "s + std::to_string(value.value().size()));

  uint32_t immediate = endian::from_little32(value.value());
  immediate = std::min(immediate, uint32_t(0xFF));

  return {makeOp("shl", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Immediate8(static_cast<uint8_t>(immediate))}})};
 } else if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  std::vector<std::shared_ptr<Chunk>> result;
  result.push_back(makeOp("mov", Asm::Args{{Asm::Args::Register32("ecx"), Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4)}}));
  
  // limit ecx to 0xff (for saving in cl)
  result.push_back(makeOp("mov", Asm::Args{{Asm::Args::Register32("edx"), Asm::Args::Immediate32(0xff)}}));
  result.push_back(makeOp("cmp", Asm::Args{{Asm::Args::Register32("ecx"), Asm::Args::Register32("edx")}}));
  result.push_back(makeOp("cmova", Asm::Args{{Asm::Args::Register32("ecx"), Asm::Args::Register32("edx")}}));
  
  result.push_back(makeOp("shl", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Register8("cl")}}));
  return result;
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at shift left: "s + demangle(typeid(data_storage)));
}

std::vector<std::shared_ptr<Chunk>> makeShiftRightValue(const FlowGraph::Data& data, const FlowGraph::Graph& graph)
{
 if (data.type() != FlowGraph::DataType::Int) {
  throw std::runtime_error("Bad type for operand: "s + std::to_string(int(data.type())));
 }

 if (!data.storage())
  throw std::runtime_error("ICE: Operand storage is 0");

 auto& data_storage{*data.storage()};
 if (typeid(data_storage) == typeid(FlowGraph::Constant)) {
  FlowGraph::Constant& value {dynamic_cast<FlowGraph::Constant&>(data_storage)};
  if (value.value().size() < sizeof(uint32_t))
   throw std::runtime_error("ICE: Int data from operand needs at least 4 bytes, got "s + std::to_string(value.value().size()));

  uint32_t immediate = endian::from_little32(value.value());
  immediate = std::min(immediate, uint32_t(0xFF));

  return {makeOp("shr", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Immediate8(static_cast<uint8_t>(immediate))}})};
 } else if (typeid(data_storage) == typeid(FlowGraph::TemporaryStorage)) {
  //FlowGraph::TemporaryStorage& storage {dynamic_cast<FlowGraph::TemporaryStorage&>(data_storage)};

  index_t index { graph.scope()->indexOfData(data)};
  std::vector<std::shared_ptr<Chunk>> result;
  result.push_back(makeOp("mov", Asm::Args{{Asm::Args::Register32("ecx"), Asm::Args::Mem32Ptr64("rbp", int32_t(index + 1) * -4)}}));
  
  // limit ecx to 0xff (for saving in cl)
  result.push_back(makeOp("mov", Asm::Args{{Asm::Args::Register32("edx"), Asm::Args::Immediate32(0xff)}}));
  result.push_back(makeOp("cmp", Asm::Args{{Asm::Args::Register32("ecx"), Asm::Args::Register32("edx")}}));
  result.push_back(makeOp("cmova", Asm::Args{{Asm::Args::Register32("ecx"), Asm::Args::Register32("edx")}}));
  
  result.push_back(makeOp("shr", Asm::Args{{Asm::Args::Register32("eax"), Asm::Args::Register8("cl")}}));
  return result;
 } else
  throw std::runtime_error("ICE: Unsupported type for operand data at shift right: "s + demangle(typeid(data_storage)));
}

} // namespace

void Asm::toMachineCode(const FlowGraph::Graph& graph, Segment& segment)
{
 segment.clear();

 for (const std::shared_ptr<FlowGraph::Node>& node: graph) {
  if (node.get()) {
   auto& node_deref = *node.get();
   if (typeid(node_deref) == typeid(FlowGraph::UnaryOperation)) {
    FlowGraph::UnaryOperation& op {dynamic_cast<FlowGraph::UnaryOperation&>(*node)};

    auto operands {op.operands()};

    if (operands.size() != 2)
     throw std::runtime_error("ICE: Bad number of operands for UnaryOperation: "s + std::to_string(operands.size()));

    if (op.type() == FlowGraph::UnaryOperationType::BitwiseNot) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(parseAsm("not eax"));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::UnaryOperationType::LogicalNot) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(parseAsm("cmp eax, 0"));
     segment.append(parseAsm("sete al"));
     segment.append(parseAsm("movsx eax, al"));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::UnaryOperationType::Minus) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(parseAsm("neg eax"));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::UnaryOperationType::Resize) {
     throw std::runtime_error("ICE: Asm: Unsupported unary operation type: Resize"s);
    } else
     throw std::runtime_error("ICE: Asm: Unsupported unary operation type: "s + std::to_string(static_cast<int>(op.type())));
    
   } else if (typeid(node_deref) == typeid(FlowGraph::BinaryOperation)) {
    FlowGraph::BinaryOperation& op {dynamic_cast<FlowGraph::BinaryOperation&>(*node)};

    auto operands {op.operands()};

    if (operands.size() != 3)
     throw std::runtime_error("ICE: Bad number of operands for BinaryOperation: "s + std::to_string(operands.size()));

    if (op.type() == FlowGraph::BinaryOperationType::Add) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.push_back(makeAddValue(operands[2], graph));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::BinaryOperationType::Subtract) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.push_back(makeSubValue(operands[2], graph));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::BinaryOperationType::Multiply) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(makeMulValue(operands[2], graph));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::BinaryOperationType::Divide) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(parseAsm("xor edx, edx"));
     segment.append(makeDivValue(operands[2], graph));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::BinaryOperationType::Modulo) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(parseAsm("xor edx, edx"));
     segment.append(makeDivValue(operands[2], graph));
     segment.append(parseAsm("mov eax, edx")); // remainder is in edx
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::BinaryOperationType::ShiftLeft) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(makeShiftLeftValue(operands[2], graph));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else if (op.type() == FlowGraph::BinaryOperationType::ShiftRight) {
     segment.push_back(makeLoadValue(operands[1], graph));
     segment.append(makeShiftRightValue(operands[2], graph));
     segment.push_back(makeStoreValue(operands[0], graph));
    } else
     throw std::runtime_error("ICE: Asm: Unsupported binary operation type: "s + std::to_string(static_cast<int>(op.type())));

   } else if (typeid(node_deref) == typeid(FlowGraph::CreateScopeOp)) {
    //FlowGraph::CreateScopeOp& op {dynamic_cast<FlowGraph::CreateScopeOp&>(*node)}; // TODO: Create stack frame
    segment.push_back(makeOp("push", Asm::Args{{Asm::Args::Register64("rbp")}}));
    segment.push_back(makeOp("mov", Asm::Args{{Asm::Args::Register64("rbp"), Asm::Args::Register64("rsp")}}));
    
   } else if (typeid(node_deref) == typeid(FlowGraph::DestroyScopeOp)) {

    segment.push_back(makeLoadValue(graph.lastOp()->destination(), graph)); // TODO: Just get last operation result to eax for now
    segment.push_back(makeOp("xor", Asm::Args{{Asm::Args::Register64("rdi"), Asm::Args::Register64("rdi")}}));
    segment.push_back(makeOp("mov", Asm::Args{{Asm::Args::Register32("edi"), Asm::Args::Register32("eax")}}));

    segment.push_back(makeOp("mov", Asm::Args{{Asm::Args::Register64("rax"), Asm::Args::Immediate32(60)}})); // syscall 60: exit()
    
    //FlowGraph::DestroyScopeOp& op {dynamic_cast<FlowGraph::DestroyScopeOp&>(*node)}; // TODO: Destroy stack frame
    segment.push_back(makeOp("pop", Asm::Args{{Asm::Args::Register64("rbp")}}));
    
    segment.push_back(makeOp("syscall")); // rax: #syscall, rdi: exit code value
   } else if (typeid(node_deref) == typeid(FlowGraph::DataNode)) {
    // ignore: Immediate data is used in subsequent nodes
   } else {
    throw std::runtime_error("ICE: Encoding: Unsupported node: "s + demangle(typeid(node_deref)));
   }
  } else {
   throw std::runtime_error("ICE: encode: flowgraph node is null");
  }
 }
}