qasm3_utils.cpp 12.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/*******************************************************************************
 * Copyright (c) 2018-, UT-Battelle, LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the BSD 3-Clause License 
 * which accompanies this distribution. 
 *
 * Contributors:
 *   Alexander J. McCaskey - initial API and implementation
 *   Thien Nguyen - implementation
 *******************************************************************************/
11
#include "qasm3_utils.hpp"
12
13

#include "Quantum/QuantumOps.h"
14
15
16
17
18
19
20
21
22
23
24
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/BuiltinOps.h"
#include "symbol_table.hpp"

namespace qcor {

void printErrorMessage(const std::string msg, bool do_exit) {
  std::cout << "\n[OPENQASM3 MLIRGen] Error\n" << msg << "\n\n";
  if (do_exit) exit(1);
}

25
26
27
28
29
30
31
32
33
void printErrorMessage(const std::string msg,
                       antlr4::ParserRuleContext* context, bool do_exit) {
  auto line = context->getStart()->getLine();
  auto col = context->getStart()->getCharPositionInLine();
  std::cout << "\n[OPENQASM3 MLIRGen] Error at " << line << ":" << col << "\n"
            << "   AntlrText: " << context->getText() << "\n"
            << "   " << msg << "\n\n";
  if (do_exit) exit(1);
}
34
35
36
void printErrorMessage(const std::string msg,
                       antlr4::ParserRuleContext* context,
                       std::vector<mlir::Value>&& v, bool do_exit) {
37
38
39
40
41
42
43
  auto line = context->getStart()->getLine();
  auto col = context->getStart()->getCharPositionInLine();
  std::cout << "\n[OPENQASM3 MLIRGen] Error at " << line << ":" << col << "\n"
            << "   AntlrText: " << context->getText() << "\n"
            << "   " << msg << "\n\n";
  std::cout << "MLIR Values:\n";
  for (auto vv : v) vv.dump();
44

45
46
  if (do_exit) exit(1);
}
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
void printErrorMessage(const std::string msg, mlir::Value v) {
  printErrorMessage(msg, false);
  v.dump();
  exit(1);
}

void printErrorMessage(const std::string msg, std::vector<mlir::Value>&& v) {
  printErrorMessage(msg, false);
  for (auto vv : v) vv.dump();
  exit(1);
}

mlir::Location get_location(mlir::OpBuilder builder,
                            const std::string& file_name,
                            antlr4::ParserRuleContext* context) {
  auto line = context->getStart()->getLine();
  auto col = context->getStart()->getCharPositionInLine();
  return builder.getFileLineColLoc(builder.getIdentifier(file_name), line, col);
}

std::vector<std::string> split(const std::string& s, char delim) {
  std::vector<std::string> elems;
  split(s, delim, std::back_inserter(elems));
  return elems;
}

mlir::Type get_custom_opaque_type(const std::string& type,
                                  mlir::MLIRContext* context) {
  llvm::StringRef type_name(type);
  mlir::Identifier dialect = mlir::Identifier::get("quantum", context);
  return mlir::OpaqueType::get(context, dialect, type_name);
}

81
82
83
84
// Get or extract qubit to handle qubit SSA dominance properties:
// e.g., if the last-known qubit SSA was produced by QVS inside a sub region,
// such as if statements, the SSA var will not be used.
// Rather, a new extract from qreg will be issue to start the new use-def chain.
85
mlir::Value get_or_extract_qubit(const std::string &qreg_name,
86
                                 const std::size_t idx, mlir::Location location,
87
88
                                 ScopedSymbolTable &symbol_table,
                                 mlir::OpBuilder &builder) {
89
  auto key = symbol_table.array_qubit_symbol_name(qreg_name, idx);
90
  if (symbol_table.has_symbol(key)) {
91
92
93
94
95
96
97
98
99
100
101
102
    // Check if the cached qubit SSA var dominance properties in the current
    // scope:
    mlir::Value qubit_value = symbol_table.get_symbol(key);
    if (!symbol_table.verify_qubit_ssa_dominance_property(
            qubit_value, builder.getInsertionBlock())) {
      // The cache SSA value is not valid:
      symbol_table.erase_symbol(key);
      return get_or_extract_qubit(qreg_name, idx, location, symbol_table,
                                  builder);
    } else {
      return qubit_value;
    }
103
104
105
106
107
108
109
110
111
112
113
114
115
116
  } else {
    auto qubits = symbol_table.get_symbol(qreg_name);
    mlir::Value pos = get_or_create_constant_integer_value(
        idx, location, builder.getI64Type(), symbol_table, builder);
    auto value = builder.create<mlir::quantum::ExtractQubitOp>(
        location, get_custom_opaque_type("Qubit", builder.getContext()), qubits,
        pos);
    symbol_table.add_symbol(key, value);
    return value;
  }
}

mlir::Value get_or_create_constant_integer_value(
    const std::size_t idx, mlir::Location location, mlir::Type type,
117
    ScopedSymbolTable &symbol_table, mlir::OpBuilder &builder) {
118
119
120
121
  auto width = type.getIntOrFloatBitWidth();
  if (symbol_table.has_constant_integer(idx, width)) {
    return symbol_table.get_constant_integer(idx, width);
  } else {
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    // Handle unsigned int constant:
    // ConstantOp (std dialect) doesn't support Signed type (uint)
    if (!type.cast<mlir::IntegerType>().isSignless()) {
      auto signless_int_type =
          builder.getIntegerType(type.getIntOrFloatBitWidth());
      auto integer_attr = mlir::IntegerAttr::get(signless_int_type, idx);

      auto ret =
          builder
              .create<mlir::quantum::IntegerCastOp>(
                  location, type,
                  builder.create<mlir::ConstantOp>(location, integer_attr))
              .output();
      symbol_table.add_constant_integer(idx, ret, width);
      return ret;
    } else {
      auto integer_attr = mlir::IntegerAttr::get(type, idx);
      assert(integer_attr.getType().cast<mlir::IntegerType>().isSignless());
      auto ret = builder.create<mlir::ConstantOp>(location, integer_attr);
      symbol_table.add_constant_integer(idx, ret, width);
      return ret;
    }
144
145
146
147
148
149
  }
}

mlir::Value get_or_create_constant_index_value(const std::size_t idx,
                                               mlir::Location location,
                                               int width,
150
151
152
153
154
155
156
157
158
159
160
161
                                               ScopedSymbolTable &symbol_table,
                                               mlir::OpBuilder &builder) {
  if (symbol_table.has_constant_integer(idx, width)) {
    // If there is a cached constant integer value, cast and return it:
    auto constant_int = symbol_table.get_constant_integer(idx, width);
    return builder.create<mlir::IndexCastOp>(location, constant_int,
                                             builder.getIndexType());
  } else {
    // Otherwise, create a new constant index value
    auto integer_attr = mlir::IntegerAttr::get(builder.getIndexType(), idx);
    return builder.create<mlir::ConstantOp>(location, integer_attr);
  }
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
mlir::Type convertQasm3Type(qasm3::qasm3Parser::ClassicalTypeContext* ctx,
                            ScopedSymbolTable& symbol_table,
                            mlir::OpBuilder& builder, bool value_type) {
  auto type = ctx->getText();
  auto context = builder.getContext();
  llvm::StringRef qubit_type_name("Qubit"), array_type_name("Array"),
      result_type_name("Result");
  mlir::Identifier dialect = mlir::Identifier::get("quantum", context);
  auto qubit_type = mlir::OpaqueType::get(context, dialect, qubit_type_name);
  auto array_type = mlir::OpaqueType::get(context, dialect, array_type_name);
  auto result_type = mlir::IntegerType::get(context, 1);
  if (type == "bit") {
    // result type
    return result_type;
  } else if (type.find("bit") != std::string::npos &&
             type.find("[") != std::string::npos) {
    // array type
    auto start = type.find_first_of("[");
    auto finish = type.find_first_of("]");
    auto idx_str = type.substr(start + 1, finish - start - 1);
    auto bit_size = symbol_table.evaluate_constant_integer_expression(idx_str);

    mlir::Type mlir_type;
187
    llvm::ArrayRef<int64_t> shaperef(bit_size);
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    mlir_type = mlir::MemRefType::get(shaperef, result_type);
    return mlir_type;
  } else if (type == "bool") {
    mlir::Type mlir_type;
    llvm::ArrayRef<int64_t> shaperef{};
    mlir_type = mlir::MemRefType::get(shaperef, builder.getIntegerType(1));
    return mlir_type;
  } else if (type.find("uint") != std::string::npos) {
    auto start = type.find_first_of("[");
    auto finish = type.find_first_of("]");
    auto idx_str = type.substr(start + 1, finish - start - 1);
    auto bit_size = symbol_table.evaluate_constant_integer_expression(idx_str);

    mlir::Type mlir_type;
    llvm::ArrayRef<int64_t> shaperef{};
    mlir_type = mlir::MemRefType::get(shaperef,
                                      builder.getIntegerType(bit_size, false));
    return mlir_type;
  } else if (type.find("int") != std::string::npos) {
    auto start = type.find_first_of("[");
    int64_t bit_size;
    if (start == std::string::npos) {
210
      bit_size = type.find("64_t") == std::string::npos ? 32 : 64;
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
    } else {
      auto finish = type.find_first_of("]");
      auto idx_str = type.substr(start + 1, finish - start - 1);
      bit_size = symbol_table.evaluate_constant_integer_expression(idx_str);
    }

    mlir::Type mlir_type;
    if (value_type) {
      return builder.getIntegerType(bit_size);
    }
    llvm::ArrayRef<int64_t> shaperef{};
    mlir_type =
        mlir::MemRefType::get(shaperef, builder.getIntegerType(bit_size));
    return mlir_type;
  } else if (type.find("float") != std::string::npos) {
    auto start = type.find_first_of("[");
    int64_t bit_size;
    if (start == std::string::npos) {
      bit_size = 32;
    } else {
      auto finish = type.find_first_of("]");
      auto idx_str = type.substr(start + 1, finish - start - 1);
      bit_size = symbol_table.evaluate_constant_integer_expression(idx_str);
    }

    mlir::Type mlir_type;
    if (bit_size == 16) {
      mlir_type = builder.getF16Type();
    } else if (bit_size == 32) {
      mlir_type = builder.getF32Type();
    } else if (bit_size == 64) {
      mlir_type = builder.getF64Type();
    } else {
      printErrorMessage("We only accept float types of bit width 16, 32, 64.");
    }

    if (value_type) {
      return mlir_type;
    }
    llvm::ArrayRef<int64_t> shaperef{};
    mlir_type = mlir::MemRefType::get(shaperef, mlir_type);
    return mlir_type;
  } else if (type.find("double") != std::string::npos) {
    int64_t bit_size = 64;
    mlir::Type mlir_type;
    if (bit_size == 16) {
      mlir_type = builder.getF16Type();
    } else if (bit_size == 32) {
      mlir_type = builder.getF32Type();
    } else if (bit_size == 64) {
      mlir_type = builder.getF64Type();
    } else {
      printErrorMessage("We only accept float types of bit width 16, 32, 64.");
    }

    if (value_type) {
      return mlir_type;
    }
    llvm::ArrayRef<int64_t> shaperef{};
    mlir_type = mlir::MemRefType::get(shaperef, mlir_type);
    return mlir_type;
  } else if (type.find("angle") != std::string::npos) {
  }

  // arg_names.push_back(arg->association()->Identifier()->getText());
  // arg_attributes.push_back({});
  printErrorMessage("Could not convert qasm3 type to mlir type.", ctx);
  return mlir::Type();
}

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
mlir::Value cast_array_index_value_if_required(mlir::Type array_type, mlir::Value raw_index, mlir::Location location, mlir::OpBuilder &builder) {
  // Memref must use index type
  if (array_type.isa<mlir::MemRefType>() &&
      !raw_index.getType().isa<mlir::IndexType>()) {
    return builder.create<mlir::IndexCastOp>(location, builder.getIndexType(),
                                             raw_index);
  }
  // QIR arrays: must use I64
  if (array_type.isa<mlir::OpaqueType>() &&
      array_type.cast<mlir::OpaqueType>().getTypeData().str() == "Array" &&
      raw_index.getType().isa<mlir::IndexType>()) {
    return builder.create<mlir::IndexCastOp>(location, builder.getI64Type(),
                                             raw_index);
  }

  // No need to do anything
  return raw_index;
}


301
302
303
304
305
std::map<std::string, mlir::CmpIPredicate> antlr_to_mlir_predicate{
    {"==", mlir::CmpIPredicate::eq},  {"!=", mlir::CmpIPredicate::ne},
    {"<=", mlir::CmpIPredicate::sle}, {">=", mlir::CmpIPredicate::sge},
    {"<", mlir::CmpIPredicate::slt},  {">", mlir::CmpIPredicate::sgt}};

306
std::map<std::string, mlir::CmpFPredicate> antlr_to_mlir_fpredicate{
307
    {"==", mlir::CmpFPredicate::OEQ}, {"!=", mlir::CmpFPredicate::ONE},
308
309
    {"<=", mlir::CmpFPredicate::OLE}, {">=", mlir::CmpFPredicate::OGE},
    {"<", mlir::CmpFPredicate::OLT},  {">", mlir::CmpFPredicate::OGT}};
310
}  // namespace qcor