MLIR  19.0.0git
TranslateToCpp.cpp
Go to the documentation of this file.
1 //===- TranslateToCpp.cpp - Translating to C++ calls ----------------------===//
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 
12 #include "mlir/IR/BuiltinOps.h"
13 #include "mlir/IR/BuiltinTypes.h"
14 #include "mlir/IR/Dialect.h"
15 #include "mlir/IR/Operation.h"
16 #include "mlir/IR/SymbolTable.h"
18 #include "mlir/Support/LLVM.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ScopedHashTable.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/TypeSwitch.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/FormatVariadic.h"
27 #include <stack>
28 #include <utility>
29 
30 #define DEBUG_TYPE "translate-to-cpp"
31 
32 using namespace mlir;
33 using namespace mlir::emitc;
34 using llvm::formatv;
35 
36 /// Convenience functions to produce interleaved output with functions returning
37 /// a LogicalResult. This is different than those in STLExtras as functions used
38 /// on each element doesn't return a string.
39 template <typename ForwardIterator, typename UnaryFunctor,
40  typename NullaryFunctor>
41 inline LogicalResult
43  UnaryFunctor eachFn, NullaryFunctor betweenFn) {
44  if (begin == end)
45  return success();
46  if (failed(eachFn(*begin)))
47  return failure();
48  ++begin;
49  for (; begin != end; ++begin) {
50  betweenFn();
51  if (failed(eachFn(*begin)))
52  return failure();
53  }
54  return success();
55 }
56 
57 template <typename Container, typename UnaryFunctor, typename NullaryFunctor>
58 inline LogicalResult interleaveWithError(const Container &c,
59  UnaryFunctor eachFn,
60  NullaryFunctor betweenFn) {
61  return interleaveWithError(c.begin(), c.end(), eachFn, betweenFn);
62 }
63 
64 template <typename Container, typename UnaryFunctor>
65 inline LogicalResult interleaveCommaWithError(const Container &c,
66  raw_ostream &os,
67  UnaryFunctor eachFn) {
68  return interleaveWithError(c.begin(), c.end(), eachFn, [&]() { os << ", "; });
69 }
70 
71 /// Return the precedence of a operator as an integer, higher values
72 /// imply higher precedence.
75  .Case<emitc::AddOp>([&](auto op) { return 12; })
76  .Case<emitc::ApplyOp>([&](auto op) { return 15; })
77  .Case<emitc::BitwiseAndOp>([&](auto op) { return 7; })
78  .Case<emitc::BitwiseLeftShiftOp>([&](auto op) { return 11; })
79  .Case<emitc::BitwiseNotOp>([&](auto op) { return 15; })
80  .Case<emitc::BitwiseOrOp>([&](auto op) { return 5; })
81  .Case<emitc::BitwiseRightShiftOp>([&](auto op) { return 11; })
82  .Case<emitc::BitwiseXorOp>([&](auto op) { return 6; })
83  .Case<emitc::CallOp>([&](auto op) { return 16; })
84  .Case<emitc::CallOpaqueOp>([&](auto op) { return 16; })
85  .Case<emitc::CastOp>([&](auto op) { return 15; })
86  .Case<emitc::CmpOp>([&](auto op) -> FailureOr<int> {
87  switch (op.getPredicate()) {
88  case emitc::CmpPredicate::eq:
89  case emitc::CmpPredicate::ne:
90  return 8;
91  case emitc::CmpPredicate::lt:
92  case emitc::CmpPredicate::le:
93  case emitc::CmpPredicate::gt:
94  case emitc::CmpPredicate::ge:
95  return 9;
96  case emitc::CmpPredicate::three_way:
97  return 10;
98  }
99  return op->emitError("unsupported cmp predicate");
100  })
101  .Case<emitc::ConditionalOp>([&](auto op) { return 2; })
102  .Case<emitc::DivOp>([&](auto op) { return 13; })
103  .Case<emitc::LogicalAndOp>([&](auto op) { return 4; })
104  .Case<emitc::LogicalNotOp>([&](auto op) { return 15; })
105  .Case<emitc::LogicalOrOp>([&](auto op) { return 3; })
106  .Case<emitc::MulOp>([&](auto op) { return 13; })
107  .Case<emitc::RemOp>([&](auto op) { return 13; })
108  .Case<emitc::SubOp>([&](auto op) { return 12; })
109  .Case<emitc::UnaryMinusOp>([&](auto op) { return 15; })
110  .Case<emitc::UnaryPlusOp>([&](auto op) { return 15; })
111  .Default([](auto op) { return op->emitError("unsupported operation"); });
112 }
113 
114 namespace {
115 /// Emitter that uses dialect specific emitters to emit C++ code.
116 struct CppEmitter {
117  explicit CppEmitter(raw_ostream &os, bool declareVariablesAtTop);
118 
119  /// Emits attribute or returns failure.
120  LogicalResult emitAttribute(Location loc, Attribute attr);
121 
122  /// Emits operation 'op' with/without training semicolon or returns failure.
123  LogicalResult emitOperation(Operation &op, bool trailingSemicolon);
124 
125  /// Emits type 'type' or returns failure.
126  LogicalResult emitType(Location loc, Type type);
127 
128  /// Emits array of types as a std::tuple of the emitted types.
129  /// - emits void for an empty array;
130  /// - emits the type of the only element for arrays of size one;
131  /// - emits a std::tuple otherwise;
132  LogicalResult emitTypes(Location loc, ArrayRef<Type> types);
133 
134  /// Emits array of types as a std::tuple of the emitted types independently of
135  /// the array size.
136  LogicalResult emitTupleType(Location loc, ArrayRef<Type> types);
137 
138  /// Emits an assignment for a variable which has been declared previously.
139  LogicalResult emitVariableAssignment(OpResult result);
140 
141  /// Emits a variable declaration for a result of an operation.
142  LogicalResult emitVariableDeclaration(OpResult result,
143  bool trailingSemicolon);
144 
145  /// Emits a declaration of a variable with the given type and name.
146  LogicalResult emitVariableDeclaration(Location loc, Type type,
147  StringRef name);
148 
149  /// Emits the variable declaration and assignment prefix for 'op'.
150  /// - emits separate variable followed by std::tie for multi-valued operation;
151  /// - emits single type followed by variable for single result;
152  /// - emits nothing if no value produced by op;
153  /// Emits final '=' operator where a type is produced. Returns failure if
154  /// any result type could not be converted.
155  LogicalResult emitAssignPrefix(Operation &op);
156 
157  /// Emits a global variable declaration or definition.
158  LogicalResult emitGlobalVariable(GlobalOp op);
159 
160  /// Emits a label for the block.
161  LogicalResult emitLabel(Block &block);
162 
163  /// Emits the operands and atttributes of the operation. All operands are
164  /// emitted first and then all attributes in alphabetical order.
165  LogicalResult emitOperandsAndAttributes(Operation &op,
166  ArrayRef<StringRef> exclude = {});
167 
168  /// Emits the operands of the operation. All operands are emitted in order.
169  LogicalResult emitOperands(Operation &op);
170 
171  /// Emits value as an operands of an operation
172  LogicalResult emitOperand(Value value);
173 
174  /// Emit an expression as a C expression.
175  LogicalResult emitExpression(ExpressionOp expressionOp);
176 
177  /// Return the existing or a new name for a Value.
178  StringRef getOrCreateName(Value val);
179 
180  // Returns the textual representation of a subscript operation.
181  std::string getSubscriptName(emitc::SubscriptOp op);
182 
183  /// Return the existing or a new label of a Block.
184  StringRef getOrCreateName(Block &block);
185 
186  /// Whether to map an mlir integer to a unsigned integer in C++.
187  bool shouldMapToUnsigned(IntegerType::SignednessSemantics val);
188 
189  /// RAII helper function to manage entering/exiting C++ scopes.
190  struct Scope {
191  Scope(CppEmitter &emitter)
192  : valueMapperScope(emitter.valueMapper),
193  blockMapperScope(emitter.blockMapper), emitter(emitter) {
194  emitter.valueInScopeCount.push(emitter.valueInScopeCount.top());
195  emitter.labelInScopeCount.push(emitter.labelInScopeCount.top());
196  }
197  ~Scope() {
198  emitter.valueInScopeCount.pop();
199  emitter.labelInScopeCount.pop();
200  }
201 
202  private:
203  llvm::ScopedHashTableScope<Value, std::string> valueMapperScope;
204  llvm::ScopedHashTableScope<Block *, std::string> blockMapperScope;
205  CppEmitter &emitter;
206  };
207 
208  /// Returns wether the Value is assigned to a C++ variable in the scope.
209  bool hasValueInScope(Value val);
210 
211  // Returns whether a label is assigned to the block.
212  bool hasBlockLabel(Block &block);
213 
214  /// Returns the output stream.
215  raw_indented_ostream &ostream() { return os; };
216 
217  /// Returns if all variables for op results and basic block arguments need to
218  /// be declared at the beginning of a function.
219  bool shouldDeclareVariablesAtTop() { return declareVariablesAtTop; };
220 
221  /// Get expression currently being emitted.
222  ExpressionOp getEmittedExpression() { return emittedExpression; }
223 
224  /// Determine whether given value is part of the expression potentially being
225  /// emitted.
226  bool isPartOfCurrentExpression(Value value) {
227  if (!emittedExpression)
228  return false;
229  Operation *def = value.getDefiningOp();
230  if (!def)
231  return false;
232  auto operandExpression = dyn_cast<ExpressionOp>(def->getParentOp());
233  return operandExpression == emittedExpression;
234  };
235 
236 private:
237  using ValueMapper = llvm::ScopedHashTable<Value, std::string>;
238  using BlockMapper = llvm::ScopedHashTable<Block *, std::string>;
239 
240  /// Output stream to emit to.
242 
243  /// Boolean to enforce that all variables for op results and block
244  /// arguments are declared at the beginning of the function. This also
245  /// includes results from ops located in nested regions.
246  bool declareVariablesAtTop;
247 
248  /// Map from value to name of C++ variable that contain the name.
249  ValueMapper valueMapper;
250 
251  /// Map from block to name of C++ label.
252  BlockMapper blockMapper;
253 
254  /// The number of values in the current scope. This is used to declare the
255  /// names of values in a scope.
256  std::stack<int64_t> valueInScopeCount;
257  std::stack<int64_t> labelInScopeCount;
258 
259  /// State of the current expression being emitted.
260  ExpressionOp emittedExpression;
261  SmallVector<int> emittedExpressionPrecedence;
262 
263  void pushExpressionPrecedence(int precedence) {
264  emittedExpressionPrecedence.push_back(precedence);
265  }
266  void popExpressionPrecedence() { emittedExpressionPrecedence.pop_back(); }
267  static int lowestPrecedence() { return 0; }
268  int getExpressionPrecedence() {
269  if (emittedExpressionPrecedence.empty())
270  return lowestPrecedence();
271  return emittedExpressionPrecedence.back();
272  }
273 };
274 } // namespace
275 
276 /// Determine whether expression \p expressionOp should be emitted inline, i.e.
277 /// as part of its user. This function recommends inlining of any expressions
278 /// that can be inlined unless it is used by another expression, under the
279 /// assumption that any expression fusion/re-materialization was taken care of
280 /// by transformations run by the backend.
281 static bool shouldBeInlined(ExpressionOp expressionOp) {
282  // Do not inline if expression is marked as such.
283  if (expressionOp.getDoNotInline())
284  return false;
285 
286  // Do not inline expressions with side effects to prevent side-effect
287  // reordering.
288  if (expressionOp.hasSideEffects())
289  return false;
290 
291  // Do not inline expressions with multiple uses.
292  Value result = expressionOp.getResult();
293  if (!result.hasOneUse())
294  return false;
295 
296  Operation *user = *result.getUsers().begin();
297 
298  // Do not inline expressions used by subscript operations, since the
299  // way the subscript operation translation is implemented requires that
300  // variables be materialized.
301  if (isa<emitc::SubscriptOp>(user))
302  return false;
303 
304  // Do not inline expressions used by other expressions, as any desired
305  // expression folding was taken care of by transformations.
306  return !user->getParentOfType<ExpressionOp>();
307 }
308 
309 static LogicalResult printConstantOp(CppEmitter &emitter, Operation *operation,
310  Attribute value) {
311  OpResult result = operation->getResult(0);
312 
313  // Only emit an assignment as the variable was already declared when printing
314  // the FuncOp.
315  if (emitter.shouldDeclareVariablesAtTop()) {
316  // Skip the assignment if the emitc.constant has no value.
317  if (auto oAttr = dyn_cast<emitc::OpaqueAttr>(value)) {
318  if (oAttr.getValue().empty())
319  return success();
320  }
321 
322  if (failed(emitter.emitVariableAssignment(result)))
323  return failure();
324  return emitter.emitAttribute(operation->getLoc(), value);
325  }
326 
327  // Emit a variable declaration for an emitc.constant op without value.
328  if (auto oAttr = dyn_cast<emitc::OpaqueAttr>(value)) {
329  if (oAttr.getValue().empty())
330  // The semicolon gets printed by the emitOperation function.
331  return emitter.emitVariableDeclaration(result,
332  /*trailingSemicolon=*/false);
333  }
334 
335  // Emit a variable declaration.
336  if (failed(emitter.emitAssignPrefix(*operation)))
337  return failure();
338  return emitter.emitAttribute(operation->getLoc(), value);
339 }
340 
341 static LogicalResult printOperation(CppEmitter &emitter,
342  emitc::ConstantOp constantOp) {
343  Operation *operation = constantOp.getOperation();
344  Attribute value = constantOp.getValue();
345 
346  return printConstantOp(emitter, operation, value);
347 }
348 
349 static LogicalResult printOperation(CppEmitter &emitter,
350  emitc::VariableOp variableOp) {
351  Operation *operation = variableOp.getOperation();
352  Attribute value = variableOp.getValue();
353 
354  return printConstantOp(emitter, operation, value);
355 }
356 
357 static LogicalResult printOperation(CppEmitter &emitter,
358  emitc::GlobalOp globalOp) {
359 
360  return emitter.emitGlobalVariable(globalOp);
361 }
362 
363 static LogicalResult printOperation(CppEmitter &emitter,
364  emitc::AssignOp assignOp) {
365  OpResult result = assignOp.getVar().getDefiningOp()->getResult(0);
366 
367  if (failed(emitter.emitVariableAssignment(result)))
368  return failure();
369 
370  return emitter.emitOperand(assignOp.getValue());
371 }
372 
373 static LogicalResult printOperation(CppEmitter &emitter,
374  emitc::GetGlobalOp op) {
375  // Add name to cache so that `hasValueInScope` works.
376  emitter.getOrCreateName(op.getResult());
377  return success();
378 }
379 
380 static LogicalResult printOperation(CppEmitter &emitter,
381  emitc::SubscriptOp subscriptOp) {
382  // Add name to cache so that `hasValueInScope` works.
383  emitter.getOrCreateName(subscriptOp.getResult());
384  return success();
385 }
386 
387 static LogicalResult printBinaryOperation(CppEmitter &emitter,
388  Operation *operation,
389  StringRef binaryOperator) {
390  raw_ostream &os = emitter.ostream();
391 
392  if (failed(emitter.emitAssignPrefix(*operation)))
393  return failure();
394 
395  if (failed(emitter.emitOperand(operation->getOperand(0))))
396  return failure();
397 
398  os << " " << binaryOperator << " ";
399 
400  if (failed(emitter.emitOperand(operation->getOperand(1))))
401  return failure();
402 
403  return success();
404 }
405 
406 static LogicalResult printUnaryOperation(CppEmitter &emitter,
407  Operation *operation,
408  StringRef unaryOperator) {
409  raw_ostream &os = emitter.ostream();
410 
411  if (failed(emitter.emitAssignPrefix(*operation)))
412  return failure();
413 
414  os << unaryOperator;
415 
416  if (failed(emitter.emitOperand(operation->getOperand(0))))
417  return failure();
418 
419  return success();
420 }
421 
422 static LogicalResult printOperation(CppEmitter &emitter, emitc::AddOp addOp) {
423  Operation *operation = addOp.getOperation();
424 
425  return printBinaryOperation(emitter, operation, "+");
426 }
427 
428 static LogicalResult printOperation(CppEmitter &emitter, emitc::DivOp divOp) {
429  Operation *operation = divOp.getOperation();
430 
431  return printBinaryOperation(emitter, operation, "/");
432 }
433 
434 static LogicalResult printOperation(CppEmitter &emitter, emitc::MulOp mulOp) {
435  Operation *operation = mulOp.getOperation();
436 
437  return printBinaryOperation(emitter, operation, "*");
438 }
439 
440 static LogicalResult printOperation(CppEmitter &emitter, emitc::RemOp remOp) {
441  Operation *operation = remOp.getOperation();
442 
443  return printBinaryOperation(emitter, operation, "%");
444 }
445 
446 static LogicalResult printOperation(CppEmitter &emitter, emitc::SubOp subOp) {
447  Operation *operation = subOp.getOperation();
448 
449  return printBinaryOperation(emitter, operation, "-");
450 }
451 
452 static LogicalResult printOperation(CppEmitter &emitter, emitc::CmpOp cmpOp) {
453  Operation *operation = cmpOp.getOperation();
454 
455  StringRef binaryOperator;
456 
457  switch (cmpOp.getPredicate()) {
458  case emitc::CmpPredicate::eq:
459  binaryOperator = "==";
460  break;
461  case emitc::CmpPredicate::ne:
462  binaryOperator = "!=";
463  break;
464  case emitc::CmpPredicate::lt:
465  binaryOperator = "<";
466  break;
467  case emitc::CmpPredicate::le:
468  binaryOperator = "<=";
469  break;
470  case emitc::CmpPredicate::gt:
471  binaryOperator = ">";
472  break;
473  case emitc::CmpPredicate::ge:
474  binaryOperator = ">=";
475  break;
476  case emitc::CmpPredicate::three_way:
477  binaryOperator = "<=>";
478  break;
479  }
480 
481  return printBinaryOperation(emitter, operation, binaryOperator);
482 }
483 
484 static LogicalResult printOperation(CppEmitter &emitter,
485  emitc::ConditionalOp conditionalOp) {
486  raw_ostream &os = emitter.ostream();
487 
488  if (failed(emitter.emitAssignPrefix(*conditionalOp)))
489  return failure();
490 
491  if (failed(emitter.emitOperand(conditionalOp.getCondition())))
492  return failure();
493 
494  os << " ? ";
495 
496  if (failed(emitter.emitOperand(conditionalOp.getTrueValue())))
497  return failure();
498 
499  os << " : ";
500 
501  if (failed(emitter.emitOperand(conditionalOp.getFalseValue())))
502  return failure();
503 
504  return success();
505 }
506 
507 static LogicalResult printOperation(CppEmitter &emitter,
508  emitc::VerbatimOp verbatimOp) {
509  raw_ostream &os = emitter.ostream();
510 
511  os << verbatimOp.getValue();
512 
513  return success();
514 }
515 
516 static LogicalResult printOperation(CppEmitter &emitter,
517  cf::BranchOp branchOp) {
518  raw_ostream &os = emitter.ostream();
519  Block &successor = *branchOp.getSuccessor();
520 
521  for (auto pair :
522  llvm::zip(branchOp.getOperands(), successor.getArguments())) {
523  Value &operand = std::get<0>(pair);
524  BlockArgument &argument = std::get<1>(pair);
525  os << emitter.getOrCreateName(argument) << " = "
526  << emitter.getOrCreateName(operand) << ";\n";
527  }
528 
529  os << "goto ";
530  if (!(emitter.hasBlockLabel(successor)))
531  return branchOp.emitOpError("unable to find label for successor block");
532  os << emitter.getOrCreateName(successor);
533  return success();
534 }
535 
536 static LogicalResult printOperation(CppEmitter &emitter,
537  cf::CondBranchOp condBranchOp) {
538  raw_indented_ostream &os = emitter.ostream();
539  Block &trueSuccessor = *condBranchOp.getTrueDest();
540  Block &falseSuccessor = *condBranchOp.getFalseDest();
541 
542  os << "if (" << emitter.getOrCreateName(condBranchOp.getCondition())
543  << ") {\n";
544 
545  os.indent();
546 
547  // If condition is true.
548  for (auto pair : llvm::zip(condBranchOp.getTrueOperands(),
549  trueSuccessor.getArguments())) {
550  Value &operand = std::get<0>(pair);
551  BlockArgument &argument = std::get<1>(pair);
552  os << emitter.getOrCreateName(argument) << " = "
553  << emitter.getOrCreateName(operand) << ";\n";
554  }
555 
556  os << "goto ";
557  if (!(emitter.hasBlockLabel(trueSuccessor))) {
558  return condBranchOp.emitOpError("unable to find label for successor block");
559  }
560  os << emitter.getOrCreateName(trueSuccessor) << ";\n";
561  os.unindent() << "} else {\n";
562  os.indent();
563  // If condition is false.
564  for (auto pair : llvm::zip(condBranchOp.getFalseOperands(),
565  falseSuccessor.getArguments())) {
566  Value &operand = std::get<0>(pair);
567  BlockArgument &argument = std::get<1>(pair);
568  os << emitter.getOrCreateName(argument) << " = "
569  << emitter.getOrCreateName(operand) << ";\n";
570  }
571 
572  os << "goto ";
573  if (!(emitter.hasBlockLabel(falseSuccessor))) {
574  return condBranchOp.emitOpError()
575  << "unable to find label for successor block";
576  }
577  os << emitter.getOrCreateName(falseSuccessor) << ";\n";
578  os.unindent() << "}";
579  return success();
580 }
581 
582 static LogicalResult printCallOperation(CppEmitter &emitter, Operation *callOp,
583  StringRef callee) {
584  if (failed(emitter.emitAssignPrefix(*callOp)))
585  return failure();
586 
587  raw_ostream &os = emitter.ostream();
588  os << callee << "(";
589  if (failed(emitter.emitOperands(*callOp)))
590  return failure();
591  os << ")";
592  return success();
593 }
594 
595 static LogicalResult printOperation(CppEmitter &emitter, func::CallOp callOp) {
596  Operation *operation = callOp.getOperation();
597  StringRef callee = callOp.getCallee();
598 
599  return printCallOperation(emitter, operation, callee);
600 }
601 
602 static LogicalResult printOperation(CppEmitter &emitter, emitc::CallOp callOp) {
603  Operation *operation = callOp.getOperation();
604  StringRef callee = callOp.getCallee();
605 
606  return printCallOperation(emitter, operation, callee);
607 }
608 
609 static LogicalResult printOperation(CppEmitter &emitter,
610  emitc::CallOpaqueOp callOpaqueOp) {
611  raw_ostream &os = emitter.ostream();
612  Operation &op = *callOpaqueOp.getOperation();
613 
614  if (failed(emitter.emitAssignPrefix(op)))
615  return failure();
616  os << callOpaqueOp.getCallee();
617 
618  auto emitArgs = [&](Attribute attr) -> LogicalResult {
619  if (auto t = dyn_cast<IntegerAttr>(attr)) {
620  // Index attributes are treated specially as operand index.
621  if (t.getType().isIndex()) {
622  int64_t idx = t.getInt();
623  Value operand = op.getOperand(idx);
624  auto literalDef =
625  dyn_cast_if_present<LiteralOp>(operand.getDefiningOp());
626  if (!literalDef && !emitter.hasValueInScope(operand))
627  return op.emitOpError("operand ")
628  << idx << "'s value not defined in scope";
629  os << emitter.getOrCreateName(operand);
630  return success();
631  }
632  }
633  if (failed(emitter.emitAttribute(op.getLoc(), attr)))
634  return failure();
635 
636  return success();
637  };
638 
639  if (callOpaqueOp.getTemplateArgs()) {
640  os << "<";
641  if (failed(interleaveCommaWithError(*callOpaqueOp.getTemplateArgs(), os,
642  emitArgs)))
643  return failure();
644  os << ">";
645  }
646 
647  os << "(";
648 
649  LogicalResult emittedArgs =
650  callOpaqueOp.getArgs()
651  ? interleaveCommaWithError(*callOpaqueOp.getArgs(), os, emitArgs)
652  : emitter.emitOperands(op);
653  if (failed(emittedArgs))
654  return failure();
655  os << ")";
656  return success();
657 }
658 
659 static LogicalResult printOperation(CppEmitter &emitter,
660  emitc::ApplyOp applyOp) {
661  raw_ostream &os = emitter.ostream();
662  Operation &op = *applyOp.getOperation();
663 
664  if (failed(emitter.emitAssignPrefix(op)))
665  return failure();
666  os << applyOp.getApplicableOperator();
667  os << emitter.getOrCreateName(applyOp.getOperand());
668 
669  return success();
670 }
671 
672 static LogicalResult printOperation(CppEmitter &emitter,
673  emitc::BitwiseAndOp bitwiseAndOp) {
674  Operation *operation = bitwiseAndOp.getOperation();
675  return printBinaryOperation(emitter, operation, "&");
676 }
677 
678 static LogicalResult
679 printOperation(CppEmitter &emitter,
680  emitc::BitwiseLeftShiftOp bitwiseLeftShiftOp) {
681  Operation *operation = bitwiseLeftShiftOp.getOperation();
682  return printBinaryOperation(emitter, operation, "<<");
683 }
684 
685 static LogicalResult printOperation(CppEmitter &emitter,
686  emitc::BitwiseNotOp bitwiseNotOp) {
687  Operation *operation = bitwiseNotOp.getOperation();
688  return printUnaryOperation(emitter, operation, "~");
689 }
690 
691 static LogicalResult printOperation(CppEmitter &emitter,
692  emitc::BitwiseOrOp bitwiseOrOp) {
693  Operation *operation = bitwiseOrOp.getOperation();
694  return printBinaryOperation(emitter, operation, "|");
695 }
696 
697 static LogicalResult
698 printOperation(CppEmitter &emitter,
699  emitc::BitwiseRightShiftOp bitwiseRightShiftOp) {
700  Operation *operation = bitwiseRightShiftOp.getOperation();
701  return printBinaryOperation(emitter, operation, ">>");
702 }
703 
704 static LogicalResult printOperation(CppEmitter &emitter,
705  emitc::BitwiseXorOp bitwiseXorOp) {
706  Operation *operation = bitwiseXorOp.getOperation();
707  return printBinaryOperation(emitter, operation, "^");
708 }
709 
710 static LogicalResult printOperation(CppEmitter &emitter,
711  emitc::UnaryPlusOp unaryPlusOp) {
712  Operation *operation = unaryPlusOp.getOperation();
713  return printUnaryOperation(emitter, operation, "+");
714 }
715 
716 static LogicalResult printOperation(CppEmitter &emitter,
717  emitc::UnaryMinusOp unaryMinusOp) {
718  Operation *operation = unaryMinusOp.getOperation();
719  return printUnaryOperation(emitter, operation, "-");
720 }
721 
722 static LogicalResult printOperation(CppEmitter &emitter, emitc::CastOp castOp) {
723  raw_ostream &os = emitter.ostream();
724  Operation &op = *castOp.getOperation();
725 
726  if (failed(emitter.emitAssignPrefix(op)))
727  return failure();
728  os << "(";
729  if (failed(emitter.emitType(op.getLoc(), op.getResult(0).getType())))
730  return failure();
731  os << ") ";
732  return emitter.emitOperand(castOp.getOperand());
733 }
734 
735 static LogicalResult printOperation(CppEmitter &emitter,
736  emitc::ExpressionOp expressionOp) {
737  if (shouldBeInlined(expressionOp))
738  return success();
739 
740  Operation &op = *expressionOp.getOperation();
741 
742  if (failed(emitter.emitAssignPrefix(op)))
743  return failure();
744 
745  return emitter.emitExpression(expressionOp);
746 }
747 
748 static LogicalResult printOperation(CppEmitter &emitter,
749  emitc::IncludeOp includeOp) {
750  raw_ostream &os = emitter.ostream();
751 
752  os << "#include ";
753  if (includeOp.getIsStandardInclude())
754  os << "<" << includeOp.getInclude() << ">";
755  else
756  os << "\"" << includeOp.getInclude() << "\"";
757 
758  return success();
759 }
760 
761 static LogicalResult printOperation(CppEmitter &emitter,
762  emitc::LogicalAndOp logicalAndOp) {
763  Operation *operation = logicalAndOp.getOperation();
764  return printBinaryOperation(emitter, operation, "&&");
765 }
766 
767 static LogicalResult printOperation(CppEmitter &emitter,
768  emitc::LogicalNotOp logicalNotOp) {
769  Operation *operation = logicalNotOp.getOperation();
770  return printUnaryOperation(emitter, operation, "!");
771 }
772 
773 static LogicalResult printOperation(CppEmitter &emitter,
774  emitc::LogicalOrOp logicalOrOp) {
775  Operation *operation = logicalOrOp.getOperation();
776  return printBinaryOperation(emitter, operation, "||");
777 }
778 
779 static LogicalResult printOperation(CppEmitter &emitter, emitc::ForOp forOp) {
780 
781  raw_indented_ostream &os = emitter.ostream();
782 
783  // Utility function to determine whether a value is an expression that will be
784  // inlined, and as such should be wrapped in parentheses in order to guarantee
785  // its precedence and associativity.
786  auto requiresParentheses = [&](Value value) {
787  auto expressionOp =
788  dyn_cast_if_present<ExpressionOp>(value.getDefiningOp());
789  if (!expressionOp)
790  return false;
791  return shouldBeInlined(expressionOp);
792  };
793 
794  os << "for (";
795  if (failed(
796  emitter.emitType(forOp.getLoc(), forOp.getInductionVar().getType())))
797  return failure();
798  os << " ";
799  os << emitter.getOrCreateName(forOp.getInductionVar());
800  os << " = ";
801  if (failed(emitter.emitOperand(forOp.getLowerBound())))
802  return failure();
803  os << "; ";
804  os << emitter.getOrCreateName(forOp.getInductionVar());
805  os << " < ";
806  Value upperBound = forOp.getUpperBound();
807  bool upperBoundRequiresParentheses = requiresParentheses(upperBound);
808  if (upperBoundRequiresParentheses)
809  os << "(";
810  if (failed(emitter.emitOperand(upperBound)))
811  return failure();
812  if (upperBoundRequiresParentheses)
813  os << ")";
814  os << "; ";
815  os << emitter.getOrCreateName(forOp.getInductionVar());
816  os << " += ";
817  if (failed(emitter.emitOperand(forOp.getStep())))
818  return failure();
819  os << ") {\n";
820  os.indent();
821 
822  Region &forRegion = forOp.getRegion();
823  auto regionOps = forRegion.getOps();
824 
825  // We skip the trailing yield op.
826  for (auto it = regionOps.begin(); std::next(it) != regionOps.end(); ++it) {
827  if (failed(emitter.emitOperation(*it, /*trailingSemicolon=*/true)))
828  return failure();
829  }
830 
831  os.unindent() << "}";
832 
833  return success();
834 }
835 
836 static LogicalResult printOperation(CppEmitter &emitter, emitc::IfOp ifOp) {
837  raw_indented_ostream &os = emitter.ostream();
838 
839  // Helper function to emit all ops except the last one, expected to be
840  // emitc::yield.
841  auto emitAllExceptLast = [&emitter](Region &region) {
842  Region::OpIterator it = region.op_begin(), end = region.op_end();
843  for (; std::next(it) != end; ++it) {
844  if (failed(emitter.emitOperation(*it, /*trailingSemicolon=*/true)))
845  return failure();
846  }
847  assert(isa<emitc::YieldOp>(*it) &&
848  "Expected last operation in the region to be emitc::yield");
849  return success();
850  };
851 
852  os << "if (";
853  if (failed(emitter.emitOperand(ifOp.getCondition())))
854  return failure();
855  os << ") {\n";
856  os.indent();
857  if (failed(emitAllExceptLast(ifOp.getThenRegion())))
858  return failure();
859  os.unindent() << "}";
860 
861  Region &elseRegion = ifOp.getElseRegion();
862  if (!elseRegion.empty()) {
863  os << " else {\n";
864  os.indent();
865  if (failed(emitAllExceptLast(elseRegion)))
866  return failure();
867  os.unindent() << "}";
868  }
869 
870  return success();
871 }
872 
873 static LogicalResult printOperation(CppEmitter &emitter,
874  func::ReturnOp returnOp) {
875  raw_ostream &os = emitter.ostream();
876  os << "return";
877  switch (returnOp.getNumOperands()) {
878  case 0:
879  return success();
880  case 1:
881  os << " ";
882  if (failed(emitter.emitOperand(returnOp.getOperand(0))))
883  return failure();
884  return success();
885  default:
886  os << " std::make_tuple(";
887  if (failed(emitter.emitOperandsAndAttributes(*returnOp.getOperation())))
888  return failure();
889  os << ")";
890  return success();
891  }
892 }
893 
894 static LogicalResult printOperation(CppEmitter &emitter,
895  emitc::ReturnOp returnOp) {
896  raw_ostream &os = emitter.ostream();
897  os << "return";
898  if (returnOp.getNumOperands() == 0)
899  return success();
900 
901  os << " ";
902  if (failed(emitter.emitOperand(returnOp.getOperand())))
903  return failure();
904  return success();
905 }
906 
907 static LogicalResult printOperation(CppEmitter &emitter, ModuleOp moduleOp) {
908  CppEmitter::Scope scope(emitter);
909 
910  for (Operation &op : moduleOp) {
911  if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/false)))
912  return failure();
913  }
914  return success();
915 }
916 
917 static LogicalResult printFunctionArgs(CppEmitter &emitter,
918  Operation *functionOp,
919  ArrayRef<Type> arguments) {
920  raw_indented_ostream &os = emitter.ostream();
921 
922  return (
923  interleaveCommaWithError(arguments, os, [&](Type arg) -> LogicalResult {
924  return emitter.emitType(functionOp->getLoc(), arg);
925  }));
926 }
927 
928 static LogicalResult printFunctionArgs(CppEmitter &emitter,
929  Operation *functionOp,
930  Region::BlockArgListType arguments) {
931  raw_indented_ostream &os = emitter.ostream();
932 
933  return (interleaveCommaWithError(
934  arguments, os, [&](BlockArgument arg) -> LogicalResult {
935  return emitter.emitVariableDeclaration(
936  functionOp->getLoc(), arg.getType(), emitter.getOrCreateName(arg));
937  }));
938 }
939 
940 static LogicalResult printFunctionBody(CppEmitter &emitter,
941  Operation *functionOp,
942  Region::BlockListType &blocks) {
943  raw_indented_ostream &os = emitter.ostream();
944  os.indent();
945 
946  if (emitter.shouldDeclareVariablesAtTop()) {
947  // Declare all variables that hold op results including those from nested
948  // regions.
949  WalkResult result =
950  functionOp->walk<WalkOrder::PreOrder>([&](Operation *op) -> WalkResult {
951  if (isa<emitc::LiteralOp>(op) ||
952  isa<emitc::ExpressionOp>(op->getParentOp()) ||
953  (isa<emitc::ExpressionOp>(op) &&
954  shouldBeInlined(cast<emitc::ExpressionOp>(op))))
955  return WalkResult::skip();
956  for (OpResult result : op->getResults()) {
957  if (failed(emitter.emitVariableDeclaration(
958  result, /*trailingSemicolon=*/true))) {
959  return WalkResult(
960  op->emitError("unable to declare result variable for op"));
961  }
962  }
963  return WalkResult::advance();
964  });
965  if (result.wasInterrupted())
966  return failure();
967  }
968 
969  // Create label names for basic blocks.
970  for (Block &block : blocks) {
971  emitter.getOrCreateName(block);
972  }
973 
974  // Declare variables for basic block arguments.
975  for (Block &block : llvm::drop_begin(blocks)) {
976  for (BlockArgument &arg : block.getArguments()) {
977  if (emitter.hasValueInScope(arg))
978  return functionOp->emitOpError(" block argument #")
979  << arg.getArgNumber() << " is out of scope";
980  if (isa<ArrayType>(arg.getType()))
981  return functionOp->emitOpError("cannot emit block argument #")
982  << arg.getArgNumber() << " with array type";
983  if (failed(
984  emitter.emitType(block.getParentOp()->getLoc(), arg.getType()))) {
985  return failure();
986  }
987  os << " " << emitter.getOrCreateName(arg) << ";\n";
988  }
989  }
990 
991  for (Block &block : blocks) {
992  // Only print a label if the block has predecessors.
993  if (!block.hasNoPredecessors()) {
994  if (failed(emitter.emitLabel(block)))
995  return failure();
996  }
997  for (Operation &op : block.getOperations()) {
998  // When generating code for an emitc.if or cf.cond_br op no semicolon
999  // needs to be printed after the closing brace.
1000  // When generating code for an emitc.for and emitc.verbatim op, printing a
1001  // trailing semicolon is handled within the printOperation function.
1002  bool trailingSemicolon =
1003  !isa<cf::CondBranchOp, emitc::DeclareFuncOp, emitc::ForOp,
1004  emitc::IfOp, emitc::LiteralOp, emitc::VerbatimOp>(op);
1005 
1006  if (failed(emitter.emitOperation(
1007  op, /*trailingSemicolon=*/trailingSemicolon)))
1008  return failure();
1009  }
1010  }
1011 
1012  os.unindent();
1013 
1014  return success();
1015 }
1016 
1017 static LogicalResult printOperation(CppEmitter &emitter,
1018  func::FuncOp functionOp) {
1019  // We need to declare variables at top if the function has multiple blocks.
1020  if (!emitter.shouldDeclareVariablesAtTop() &&
1021  functionOp.getBlocks().size() > 1) {
1022  return functionOp.emitOpError(
1023  "with multiple blocks needs variables declared at top");
1024  }
1025 
1026  if (llvm::any_of(functionOp.getResultTypes(), llvm::IsaPred<ArrayType>)) {
1027  return functionOp.emitOpError() << "cannot emit array type as result type";
1028  }
1029 
1030  CppEmitter::Scope scope(emitter);
1031  raw_indented_ostream &os = emitter.ostream();
1032  if (failed(emitter.emitTypes(functionOp.getLoc(),
1033  functionOp.getFunctionType().getResults())))
1034  return failure();
1035  os << " " << functionOp.getName();
1036 
1037  os << "(";
1038  Operation *operation = functionOp.getOperation();
1039  if (failed(printFunctionArgs(emitter, operation, functionOp.getArguments())))
1040  return failure();
1041  os << ") {\n";
1042  if (failed(printFunctionBody(emitter, operation, functionOp.getBlocks())))
1043  return failure();
1044  os << "}\n";
1045 
1046  return success();
1047 }
1048 
1049 static LogicalResult printOperation(CppEmitter &emitter,
1050  emitc::FuncOp functionOp) {
1051  // We need to declare variables at top if the function has multiple blocks.
1052  if (!emitter.shouldDeclareVariablesAtTop() &&
1053  functionOp.getBlocks().size() > 1) {
1054  return functionOp.emitOpError(
1055  "with multiple blocks needs variables declared at top");
1056  }
1057 
1058  CppEmitter::Scope scope(emitter);
1059  raw_indented_ostream &os = emitter.ostream();
1060  if (functionOp.getSpecifiers()) {
1061  for (Attribute specifier : functionOp.getSpecifiersAttr()) {
1062  os << cast<StringAttr>(specifier).str() << " ";
1063  }
1064  }
1065 
1066  if (failed(emitter.emitTypes(functionOp.getLoc(),
1067  functionOp.getFunctionType().getResults())))
1068  return failure();
1069  os << " " << functionOp.getName();
1070 
1071  os << "(";
1072  Operation *operation = functionOp.getOperation();
1073  if (functionOp.isExternal()) {
1074  if (failed(printFunctionArgs(emitter, operation,
1075  functionOp.getArgumentTypes())))
1076  return failure();
1077  os << ");";
1078  return success();
1079  }
1080  if (failed(printFunctionArgs(emitter, operation, functionOp.getArguments())))
1081  return failure();
1082  os << ") {\n";
1083  if (failed(printFunctionBody(emitter, operation, functionOp.getBlocks())))
1084  return failure();
1085  os << "}\n";
1086 
1087  return success();
1088 }
1089 
1090 static LogicalResult printOperation(CppEmitter &emitter,
1091  DeclareFuncOp declareFuncOp) {
1092  CppEmitter::Scope scope(emitter);
1093  raw_indented_ostream &os = emitter.ostream();
1094 
1095  auto functionOp = SymbolTable::lookupNearestSymbolFrom<emitc::FuncOp>(
1096  declareFuncOp, declareFuncOp.getSymNameAttr());
1097 
1098  if (!functionOp)
1099  return failure();
1100 
1101  if (functionOp.getSpecifiers()) {
1102  for (Attribute specifier : functionOp.getSpecifiersAttr()) {
1103  os << cast<StringAttr>(specifier).str() << " ";
1104  }
1105  }
1106 
1107  if (failed(emitter.emitTypes(functionOp.getLoc(),
1108  functionOp.getFunctionType().getResults())))
1109  return failure();
1110  os << " " << functionOp.getName();
1111 
1112  os << "(";
1113  Operation *operation = functionOp.getOperation();
1114  if (failed(printFunctionArgs(emitter, operation, functionOp.getArguments())))
1115  return failure();
1116  os << ");";
1117 
1118  return success();
1119 }
1120 
1121 CppEmitter::CppEmitter(raw_ostream &os, bool declareVariablesAtTop)
1122  : os(os), declareVariablesAtTop(declareVariablesAtTop) {
1123  valueInScopeCount.push(0);
1124  labelInScopeCount.push(0);
1125 }
1126 
1127 std::string CppEmitter::getSubscriptName(emitc::SubscriptOp op) {
1128  std::string out;
1129  llvm::raw_string_ostream ss(out);
1130  ss << getOrCreateName(op.getValue());
1131  for (auto index : op.getIndices()) {
1132  ss << "[" << getOrCreateName(index) << "]";
1133  }
1134  return out;
1135 }
1136 
1137 /// Return the existing or a new name for a Value.
1138 StringRef CppEmitter::getOrCreateName(Value val) {
1139  if (auto literal = dyn_cast_if_present<emitc::LiteralOp>(val.getDefiningOp()))
1140  return literal.getValue();
1141  if (!valueMapper.count(val)) {
1142  if (auto subscript =
1143  dyn_cast_if_present<emitc::SubscriptOp>(val.getDefiningOp())) {
1144  valueMapper.insert(val, getSubscriptName(subscript));
1145  } else if (auto getGlobal = dyn_cast_if_present<emitc::GetGlobalOp>(
1146  val.getDefiningOp())) {
1147  valueMapper.insert(val, getGlobal.getName().str());
1148  } else {
1149  valueMapper.insert(val, formatv("v{0}", ++valueInScopeCount.top()));
1150  }
1151  }
1152  return *valueMapper.begin(val);
1153 }
1154 
1155 /// Return the existing or a new label for a Block.
1156 StringRef CppEmitter::getOrCreateName(Block &block) {
1157  if (!blockMapper.count(&block))
1158  blockMapper.insert(&block, formatv("label{0}", ++labelInScopeCount.top()));
1159  return *blockMapper.begin(&block);
1160 }
1161 
1162 bool CppEmitter::shouldMapToUnsigned(IntegerType::SignednessSemantics val) {
1163  switch (val) {
1164  case IntegerType::Signless:
1165  return false;
1166  case IntegerType::Signed:
1167  return false;
1168  case IntegerType::Unsigned:
1169  return true;
1170  }
1171  llvm_unreachable("Unexpected IntegerType::SignednessSemantics");
1172 }
1173 
1174 bool CppEmitter::hasValueInScope(Value val) { return valueMapper.count(val); }
1175 
1176 bool CppEmitter::hasBlockLabel(Block &block) {
1177  return blockMapper.count(&block);
1178 }
1179 
1180 LogicalResult CppEmitter::emitAttribute(Location loc, Attribute attr) {
1181  auto printInt = [&](const APInt &val, bool isUnsigned) {
1182  if (val.getBitWidth() == 1) {
1183  if (val.getBoolValue())
1184  os << "true";
1185  else
1186  os << "false";
1187  } else {
1188  SmallString<128> strValue;
1189  val.toString(strValue, 10, !isUnsigned, false);
1190  os << strValue;
1191  }
1192  };
1193 
1194  auto printFloat = [&](const APFloat &val) {
1195  if (val.isFinite()) {
1196  SmallString<128> strValue;
1197  // Use default values of toString except don't truncate zeros.
1198  val.toString(strValue, 0, 0, false);
1199  os << strValue;
1200  switch (llvm::APFloatBase::SemanticsToEnum(val.getSemantics())) {
1201  case llvm::APFloatBase::S_IEEEsingle:
1202  os << "f";
1203  break;
1204  case llvm::APFloatBase::S_IEEEdouble:
1205  break;
1206  default:
1207  llvm_unreachable("unsupported floating point type");
1208  };
1209  } else if (val.isNaN()) {
1210  os << "NAN";
1211  } else if (val.isInfinity()) {
1212  if (val.isNegative())
1213  os << "-";
1214  os << "INFINITY";
1215  }
1216  };
1217 
1218  // Print floating point attributes.
1219  if (auto fAttr = dyn_cast<FloatAttr>(attr)) {
1220  if (!isa<Float32Type, Float64Type>(fAttr.getType())) {
1221  return emitError(loc,
1222  "expected floating point attribute to be f32 or f64");
1223  }
1224  printFloat(fAttr.getValue());
1225  return success();
1226  }
1227  if (auto dense = dyn_cast<DenseFPElementsAttr>(attr)) {
1228  if (!isa<Float32Type, Float64Type>(dense.getElementType())) {
1229  return emitError(loc,
1230  "expected floating point attribute to be f32 or f64");
1231  }
1232  os << '{';
1233  interleaveComma(dense, os, [&](const APFloat &val) { printFloat(val); });
1234  os << '}';
1235  return success();
1236  }
1237 
1238  // Print integer attributes.
1239  if (auto iAttr = dyn_cast<IntegerAttr>(attr)) {
1240  if (auto iType = dyn_cast<IntegerType>(iAttr.getType())) {
1241  printInt(iAttr.getValue(), shouldMapToUnsigned(iType.getSignedness()));
1242  return success();
1243  }
1244  if (auto iType = dyn_cast<IndexType>(iAttr.getType())) {
1245  printInt(iAttr.getValue(), false);
1246  return success();
1247  }
1248  }
1249  if (auto dense = dyn_cast<DenseIntElementsAttr>(attr)) {
1250  if (auto iType = dyn_cast<IntegerType>(
1251  cast<TensorType>(dense.getType()).getElementType())) {
1252  os << '{';
1253  interleaveComma(dense, os, [&](const APInt &val) {
1254  printInt(val, shouldMapToUnsigned(iType.getSignedness()));
1255  });
1256  os << '}';
1257  return success();
1258  }
1259  if (auto iType = dyn_cast<IndexType>(
1260  cast<TensorType>(dense.getType()).getElementType())) {
1261  os << '{';
1262  interleaveComma(dense, os,
1263  [&](const APInt &val) { printInt(val, false); });
1264  os << '}';
1265  return success();
1266  }
1267  }
1268 
1269  // Print opaque attributes.
1270  if (auto oAttr = dyn_cast<emitc::OpaqueAttr>(attr)) {
1271  os << oAttr.getValue();
1272  return success();
1273  }
1274 
1275  // Print symbolic reference attributes.
1276  if (auto sAttr = dyn_cast<SymbolRefAttr>(attr)) {
1277  if (sAttr.getNestedReferences().size() > 1)
1278  return emitError(loc, "attribute has more than 1 nested reference");
1279  os << sAttr.getRootReference().getValue();
1280  return success();
1281  }
1282 
1283  // Print type attributes.
1284  if (auto type = dyn_cast<TypeAttr>(attr))
1285  return emitType(loc, type.getValue());
1286 
1287  return emitError(loc, "cannot emit attribute: ") << attr;
1288 }
1289 
1290 LogicalResult CppEmitter::emitExpression(ExpressionOp expressionOp) {
1291  assert(emittedExpressionPrecedence.empty() &&
1292  "Expected precedence stack to be empty");
1293  Operation *rootOp = expressionOp.getRootOp();
1294 
1295  emittedExpression = expressionOp;
1296  FailureOr<int> precedence = getOperatorPrecedence(rootOp);
1297  if (failed(precedence))
1298  return failure();
1299  pushExpressionPrecedence(precedence.value());
1300 
1301  if (failed(emitOperation(*rootOp, /*trailingSemicolon=*/false)))
1302  return failure();
1303 
1304  popExpressionPrecedence();
1305  assert(emittedExpressionPrecedence.empty() &&
1306  "Expected precedence stack to be empty");
1307  emittedExpression = nullptr;
1308 
1309  return success();
1310 }
1311 
1312 LogicalResult CppEmitter::emitOperand(Value value) {
1313  if (isPartOfCurrentExpression(value)) {
1314  Operation *def = value.getDefiningOp();
1315  assert(def && "Expected operand to be defined by an operation");
1316  FailureOr<int> precedence = getOperatorPrecedence(def);
1317  if (failed(precedence))
1318  return failure();
1319  bool encloseInParenthesis = precedence.value() < getExpressionPrecedence();
1320  if (encloseInParenthesis) {
1321  os << "(";
1322  pushExpressionPrecedence(lowestPrecedence());
1323  } else
1324  pushExpressionPrecedence(precedence.value());
1325 
1326  if (failed(emitOperation(*def, /*trailingSemicolon=*/false)))
1327  return failure();
1328 
1329  if (encloseInParenthesis)
1330  os << ")";
1331 
1332  popExpressionPrecedence();
1333  return success();
1334  }
1335 
1336  auto expressionOp = dyn_cast_if_present<ExpressionOp>(value.getDefiningOp());
1337  if (expressionOp && shouldBeInlined(expressionOp))
1338  return emitExpression(expressionOp);
1339 
1340  auto literalOp = dyn_cast_if_present<LiteralOp>(value.getDefiningOp());
1341  if (!literalOp && !hasValueInScope(value))
1342  return failure();
1343  os << getOrCreateName(value);
1344  return success();
1345 }
1346 
1347 LogicalResult CppEmitter::emitOperands(Operation &op) {
1348  return interleaveCommaWithError(op.getOperands(), os, [&](Value operand) {
1349  // If an expression is being emitted, push lowest precedence as these
1350  // operands are either wrapped by parenthesis.
1351  if (getEmittedExpression())
1352  pushExpressionPrecedence(lowestPrecedence());
1353  if (failed(emitOperand(operand)))
1354  return failure();
1355  if (getEmittedExpression())
1356  popExpressionPrecedence();
1357  return success();
1358  });
1359 }
1360 
1362 CppEmitter::emitOperandsAndAttributes(Operation &op,
1363  ArrayRef<StringRef> exclude) {
1364  if (failed(emitOperands(op)))
1365  return failure();
1366  // Insert comma in between operands and non-filtered attributes if needed.
1367  if (op.getNumOperands() > 0) {
1368  for (NamedAttribute attr : op.getAttrs()) {
1369  if (!llvm::is_contained(exclude, attr.getName().strref())) {
1370  os << ", ";
1371  break;
1372  }
1373  }
1374  }
1375  // Emit attributes.
1376  auto emitNamedAttribute = [&](NamedAttribute attr) -> LogicalResult {
1377  if (llvm::is_contained(exclude, attr.getName().strref()))
1378  return success();
1379  os << "/* " << attr.getName().getValue() << " */";
1380  if (failed(emitAttribute(op.getLoc(), attr.getValue())))
1381  return failure();
1382  return success();
1383  };
1384  return interleaveCommaWithError(op.getAttrs(), os, emitNamedAttribute);
1385 }
1386 
1387 LogicalResult CppEmitter::emitVariableAssignment(OpResult result) {
1388  if (!hasValueInScope(result)) {
1389  return result.getDefiningOp()->emitOpError(
1390  "result variable for the operation has not been declared");
1391  }
1392  os << getOrCreateName(result) << " = ";
1393  return success();
1394 }
1395 
1396 LogicalResult CppEmitter::emitVariableDeclaration(OpResult result,
1397  bool trailingSemicolon) {
1398  if (isa<emitc::SubscriptOp>(result.getDefiningOp()))
1399  return success();
1400  if (hasValueInScope(result)) {
1401  return result.getDefiningOp()->emitError(
1402  "result variable for the operation already declared");
1403  }
1404  if (failed(emitVariableDeclaration(result.getOwner()->getLoc(),
1405  result.getType(),
1406  getOrCreateName(result))))
1407  return failure();
1408  if (trailingSemicolon)
1409  os << ";\n";
1410  return success();
1411 }
1412 
1413 LogicalResult CppEmitter::emitGlobalVariable(GlobalOp op) {
1414  if (op.getExternSpecifier())
1415  os << "extern ";
1416  else if (op.getStaticSpecifier())
1417  os << "static ";
1418  if (op.getConstSpecifier())
1419  os << "const ";
1420 
1421  if (failed(emitVariableDeclaration(op->getLoc(), op.getType(),
1422  op.getSymName()))) {
1423  return failure();
1424  }
1425 
1426  std::optional<Attribute> initialValue = op.getInitialValue();
1427  if (initialValue) {
1428  os << " = ";
1429  if (failed(emitAttribute(op->getLoc(), *initialValue)))
1430  return failure();
1431  }
1432 
1433  os << ";";
1434  return success();
1435 }
1436 
1437 LogicalResult CppEmitter::emitAssignPrefix(Operation &op) {
1438  // If op is being emitted as part of an expression, bail out.
1439  if (getEmittedExpression())
1440  return success();
1441 
1442  switch (op.getNumResults()) {
1443  case 0:
1444  break;
1445  case 1: {
1446  OpResult result = op.getResult(0);
1447  if (shouldDeclareVariablesAtTop()) {
1448  if (failed(emitVariableAssignment(result)))
1449  return failure();
1450  } else {
1451  if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/false)))
1452  return failure();
1453  os << " = ";
1454  }
1455  break;
1456  }
1457  default:
1458  if (!shouldDeclareVariablesAtTop()) {
1459  for (OpResult result : op.getResults()) {
1460  if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/true)))
1461  return failure();
1462  }
1463  }
1464  os << "std::tie(";
1465  interleaveComma(op.getResults(), os,
1466  [&](Value result) { os << getOrCreateName(result); });
1467  os << ") = ";
1468  }
1469  return success();
1470 }
1471 
1472 LogicalResult CppEmitter::emitLabel(Block &block) {
1473  if (!hasBlockLabel(block))
1474  return block.getParentOp()->emitError("label for block not found");
1475  // FIXME: Add feature in `raw_indented_ostream` to ignore indent for block
1476  // label instead of using `getOStream`.
1477  os.getOStream() << getOrCreateName(block) << ":\n";
1478  return success();
1479 }
1480 
1481 LogicalResult CppEmitter::emitOperation(Operation &op, bool trailingSemicolon) {
1482  LogicalResult status =
1484  // Builtin ops.
1485  .Case<ModuleOp>([&](auto op) { return printOperation(*this, op); })
1486  // CF ops.
1487  .Case<cf::BranchOp, cf::CondBranchOp>(
1488  [&](auto op) { return printOperation(*this, op); })
1489  // EmitC ops.
1490  .Case<emitc::AddOp, emitc::ApplyOp, emitc::AssignOp,
1491  emitc::BitwiseAndOp, emitc::BitwiseLeftShiftOp,
1492  emitc::BitwiseNotOp, emitc::BitwiseOrOp,
1493  emitc::BitwiseRightShiftOp, emitc::BitwiseXorOp, emitc::CallOp,
1494  emitc::CallOpaqueOp, emitc::CastOp, emitc::CmpOp,
1495  emitc::ConditionalOp, emitc::ConstantOp, emitc::DeclareFuncOp,
1496  emitc::DivOp, emitc::ExpressionOp, emitc::ForOp, emitc::FuncOp,
1497  emitc::GlobalOp, emitc::GetGlobalOp, emitc::IfOp,
1498  emitc::IncludeOp, emitc::LogicalAndOp, emitc::LogicalNotOp,
1499  emitc::LogicalOrOp, emitc::MulOp, emitc::RemOp, emitc::ReturnOp,
1500  emitc::SubOp, emitc::SubscriptOp, emitc::UnaryMinusOp,
1501  emitc::UnaryPlusOp, emitc::VariableOp, emitc::VerbatimOp>(
1502  [&](auto op) { return printOperation(*this, op); })
1503  // Func ops.
1504  .Case<func::CallOp, func::FuncOp, func::ReturnOp>(
1505  [&](auto op) { return printOperation(*this, op); })
1506  .Case<emitc::LiteralOp>([&](auto op) { return success(); })
1507  .Default([&](Operation *) {
1508  return op.emitOpError("unable to find printer for op");
1509  });
1510 
1511  if (failed(status))
1512  return failure();
1513 
1514  if (isa<emitc::LiteralOp, emitc::SubscriptOp, emitc::GetGlobalOp>(op))
1515  return success();
1516 
1517  if (getEmittedExpression() ||
1518  (isa<emitc::ExpressionOp>(op) &&
1519  shouldBeInlined(cast<emitc::ExpressionOp>(op))))
1520  return success();
1521 
1522  os << (trailingSemicolon ? ";\n" : "\n");
1523 
1524  return success();
1525 }
1526 
1527 LogicalResult CppEmitter::emitVariableDeclaration(Location loc, Type type,
1528  StringRef name) {
1529  if (auto arrType = dyn_cast<emitc::ArrayType>(type)) {
1530  if (failed(emitType(loc, arrType.getElementType())))
1531  return failure();
1532  os << " " << name;
1533  for (auto dim : arrType.getShape()) {
1534  os << "[" << dim << "]";
1535  }
1536  return success();
1537  }
1538  if (failed(emitType(loc, type)))
1539  return failure();
1540  os << " " << name;
1541  return success();
1542 }
1543 
1544 LogicalResult CppEmitter::emitType(Location loc, Type type) {
1545  if (auto iType = dyn_cast<IntegerType>(type)) {
1546  switch (iType.getWidth()) {
1547  case 1:
1548  return (os << "bool"), success();
1549  case 8:
1550  case 16:
1551  case 32:
1552  case 64:
1553  if (shouldMapToUnsigned(iType.getSignedness()))
1554  return (os << "uint" << iType.getWidth() << "_t"), success();
1555  else
1556  return (os << "int" << iType.getWidth() << "_t"), success();
1557  default:
1558  return emitError(loc, "cannot emit integer type ") << type;
1559  }
1560  }
1561  if (auto fType = dyn_cast<FloatType>(type)) {
1562  switch (fType.getWidth()) {
1563  case 32:
1564  return (os << "float"), success();
1565  case 64:
1566  return (os << "double"), success();
1567  default:
1568  return emitError(loc, "cannot emit float type ") << type;
1569  }
1570  }
1571  if (auto iType = dyn_cast<IndexType>(type))
1572  return (os << "size_t"), success();
1573  if (auto tType = dyn_cast<TensorType>(type)) {
1574  if (!tType.hasRank())
1575  return emitError(loc, "cannot emit unranked tensor type");
1576  if (!tType.hasStaticShape())
1577  return emitError(loc, "cannot emit tensor type with non static shape");
1578  os << "Tensor<";
1579  if (isa<ArrayType>(tType.getElementType()))
1580  return emitError(loc, "cannot emit tensor of array type ") << type;
1581  if (failed(emitType(loc, tType.getElementType())))
1582  return failure();
1583  auto shape = tType.getShape();
1584  for (auto dimSize : shape) {
1585  os << ", ";
1586  os << dimSize;
1587  }
1588  os << ">";
1589  return success();
1590  }
1591  if (auto tType = dyn_cast<TupleType>(type))
1592  return emitTupleType(loc, tType.getTypes());
1593  if (auto oType = dyn_cast<emitc::OpaqueType>(type)) {
1594  os << oType.getValue();
1595  return success();
1596  }
1597  if (auto aType = dyn_cast<emitc::ArrayType>(type)) {
1598  if (failed(emitType(loc, aType.getElementType())))
1599  return failure();
1600  for (auto dim : aType.getShape())
1601  os << "[" << dim << "]";
1602  return success();
1603  }
1604  if (auto pType = dyn_cast<emitc::PointerType>(type)) {
1605  if (isa<ArrayType>(pType.getPointee()))
1606  return emitError(loc, "cannot emit pointer to array type ") << type;
1607  if (failed(emitType(loc, pType.getPointee())))
1608  return failure();
1609  os << "*";
1610  return success();
1611  }
1612  return emitError(loc, "cannot emit type ") << type;
1613 }
1614 
1615 LogicalResult CppEmitter::emitTypes(Location loc, ArrayRef<Type> types) {
1616  switch (types.size()) {
1617  case 0:
1618  os << "void";
1619  return success();
1620  case 1:
1621  return emitType(loc, types.front());
1622  default:
1623  return emitTupleType(loc, types);
1624  }
1625 }
1626 
1627 LogicalResult CppEmitter::emitTupleType(Location loc, ArrayRef<Type> types) {
1628  if (llvm::any_of(types, llvm::IsaPred<ArrayType>)) {
1629  return emitError(loc, "cannot emit tuple of array type");
1630  }
1631  os << "std::tuple<";
1633  types, os, [&](Type type) { return emitType(loc, type); })))
1634  return failure();
1635  os << ">";
1636  return success();
1637 }
1638 
1640  bool declareVariablesAtTop) {
1641  CppEmitter emitter(os, declareVariablesAtTop);
1642  return emitter.emitOperation(*op, /*trailingSemicolon=*/false);
1643 }
static LogicalResult printCallOperation(CppEmitter &emitter, Operation *callOp, StringRef callee)
static bool shouldBeInlined(ExpressionOp expressionOp)
Determine whether expression expressionOp should be emitted inline, i.e.
LogicalResult interleaveCommaWithError(const Container &c, raw_ostream &os, UnaryFunctor eachFn)
static FailureOr< int > getOperatorPrecedence(Operation *operation)
Return the precedence of a operator as an integer, higher values imply higher precedence.
static LogicalResult printFunctionArgs(CppEmitter &emitter, Operation *functionOp, ArrayRef< Type > arguments)
static LogicalResult printFunctionBody(CppEmitter &emitter, Operation *functionOp, Region::BlockListType &blocks)
static LogicalResult printConstantOp(CppEmitter &emitter, Operation *operation, Attribute value)
LogicalResult interleaveWithError(ForwardIterator begin, ForwardIterator end, UnaryFunctor eachFn, NullaryFunctor betweenFn)
Convenience functions to produce interleaved output with functions returning a LogicalResult.
static LogicalResult printBinaryOperation(CppEmitter &emitter, Operation *operation, StringRef binaryOperator)
static LogicalResult printOperation(CppEmitter &emitter, emitc::ConstantOp constantOp)
static LogicalResult printUnaryOperation(CppEmitter &emitter, Operation *operation, StringRef unaryOperator)
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class represents an argument of a Block.
Definition: Value.h:319
Block represents an ordered list of Operations.
Definition: Block.h:31
BlockArgListType getArguments()
Definition: Block.h:85
Block * getSuccessor(unsigned i)
Definition: Block.cpp:258
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition: Block.cpp:30
This class provides support for representing a failure result, or a valid value of type T.
Definition: LogicalResult.h:78
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:207
This is a value defined by a result of an operation.
Definition: Value.h:457
Operation * getOwner() const
Returns the operation that owns this result.
Definition: Value.h:466
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
Value getOperand(unsigned idx)
Definition: Operation.h:345
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition: Operation.h:402
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition: Operation.h:793
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
unsigned getNumOperands()
Definition: Operation.h:341
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition: Operation.h:234
ArrayRef< NamedAttribute > getAttrs()
Return all of the attributes on this operation.
Definition: Operation.h:507
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:268
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition: Operation.h:238
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition: Operation.h:373
result_range getResults()
Definition: Operation.h:410
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Definition: Operation.cpp:671
unsigned getNumResults()
Return the number of results held by this operation.
Definition: Operation.h:399
This class provides iteration over the held operations of blocks directly within a region.
Definition: Region.h:134
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
iterator_range< OpIterator > getOps()
Definition: Region.h:172
llvm::iplist< Block > BlockListType
Definition: Region.h:44
bool empty()
Definition: Region.h:60
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:129
user_range getUsers() const
Definition: Value.h:228
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition: Value.h:215
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:20
A utility result that is used to signal how to proceed with an ongoing walk:
Definition: Visitors.h:34
static WalkResult skip()
Definition: Visitors.h:53
static WalkResult advance()
Definition: Visitors.h:52
bool wasInterrupted() const
Returns true if the walk was interrupted.
Definition: Visitors.h:56
raw_ostream subclass that simplifies indention a sequence of code.
raw_indented_ostream & unindent()
Decreases the indent and returning this raw_indented_ostream.
raw_indented_ostream & indent()
Increases the indent and returning this raw_indented_ostream.
LogicalResult translateToCpp(Operation *op, raw_ostream &os, bool declareVariablesAtTop=false)
Translates the given operation to C++ code.
Include the generated interface declarations.
LogicalResult failure(bool isFailure=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:62
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
Definition: LogicalResult.h:72
This iterator enumerates the elements in "forward" order.
Definition: Visitors.h:66
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26