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 9 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 10 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" 11 #include "mlir/Dialect/EmitC/IR/EmitC.h" 12 #include "mlir/Dialect/Func/IR/FuncOps.h" 13 #include "mlir/Dialect/SCF/SCF.h" 14 #include "mlir/IR/BuiltinOps.h" 15 #include "mlir/IR/BuiltinTypes.h" 16 #include "mlir/IR/Dialect.h" 17 #include "mlir/IR/Operation.h" 18 #include "mlir/Support/IndentedOstream.h" 19 #include "mlir/Target/Cpp/CppEmitter.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringMap.h" 23 #include "llvm/ADT/TypeSwitch.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/FormatVariadic.h" 26 #include <utility> 27 28 #define DEBUG_TYPE "translate-to-cpp" 29 30 using namespace mlir; 31 using namespace mlir::emitc; 32 using llvm::formatv; 33 34 /// Convenience functions to produce interleaved output with functions returning 35 /// a LogicalResult. This is different than those in STLExtras as functions used 36 /// on each element doesn't return a string. 37 template <typename ForwardIterator, typename UnaryFunctor, 38 typename NullaryFunctor> 39 inline LogicalResult 40 interleaveWithError(ForwardIterator begin, ForwardIterator end, 41 UnaryFunctor eachFn, NullaryFunctor betweenFn) { 42 if (begin == end) 43 return success(); 44 if (failed(eachFn(*begin))) 45 return failure(); 46 ++begin; 47 for (; begin != end; ++begin) { 48 betweenFn(); 49 if (failed(eachFn(*begin))) 50 return failure(); 51 } 52 return success(); 53 } 54 55 template <typename Container, typename UnaryFunctor, typename NullaryFunctor> 56 inline LogicalResult interleaveWithError(const Container &c, 57 UnaryFunctor eachFn, 58 NullaryFunctor betweenFn) { 59 return interleaveWithError(c.begin(), c.end(), eachFn, betweenFn); 60 } 61 62 template <typename Container, typename UnaryFunctor> 63 inline LogicalResult interleaveCommaWithError(const Container &c, 64 raw_ostream &os, 65 UnaryFunctor eachFn) { 66 return interleaveWithError(c.begin(), c.end(), eachFn, [&]() { os << ", "; }); 67 } 68 69 namespace { 70 /// Emitter that uses dialect specific emitters to emit C++ code. 71 struct CppEmitter { 72 explicit CppEmitter(raw_ostream &os, bool declareVariablesAtTop); 73 74 /// Emits attribute or returns failure. 75 LogicalResult emitAttribute(Location loc, Attribute attr); 76 77 /// Emits operation 'op' with/without training semicolon or returns failure. 78 LogicalResult emitOperation(Operation &op, bool trailingSemicolon); 79 80 /// Emits type 'type' or returns failure. 81 LogicalResult emitType(Location loc, Type type); 82 83 /// Emits array of types as a std::tuple of the emitted types. 84 /// - emits void for an empty array; 85 /// - emits the type of the only element for arrays of size one; 86 /// - emits a std::tuple otherwise; 87 LogicalResult emitTypes(Location loc, ArrayRef<Type> types); 88 89 /// Emits array of types as a std::tuple of the emitted types independently of 90 /// the array size. 91 LogicalResult emitTupleType(Location loc, ArrayRef<Type> types); 92 93 /// Emits an assignment for a variable which has been declared previously. 94 LogicalResult emitVariableAssignment(OpResult result); 95 96 /// Emits a variable declaration for a result of an operation. 97 LogicalResult emitVariableDeclaration(OpResult result, 98 bool trailingSemicolon); 99 100 /// Emits the variable declaration and assignment prefix for 'op'. 101 /// - emits separate variable followed by std::tie for multi-valued operation; 102 /// - emits single type followed by variable for single result; 103 /// - emits nothing if no value produced by op; 104 /// Emits final '=' operator where a type is produced. Returns failure if 105 /// any result type could not be converted. 106 LogicalResult emitAssignPrefix(Operation &op); 107 108 /// Emits a label for the block. 109 LogicalResult emitLabel(Block &block); 110 111 /// Emits the operands and atttributes of the operation. All operands are 112 /// emitted first and then all attributes in alphabetical order. 113 LogicalResult emitOperandsAndAttributes(Operation &op, 114 ArrayRef<StringRef> exclude = {}); 115 116 /// Emits the operands of the operation. All operands are emitted in order. 117 LogicalResult emitOperands(Operation &op); 118 119 /// Return the existing or a new name for a Value. 120 StringRef getOrCreateName(Value val); 121 122 /// Return the existing or a new label of a Block. 123 StringRef getOrCreateName(Block &block); 124 125 /// Whether to map an mlir integer to a unsigned integer in C++. 126 bool shouldMapToUnsigned(IntegerType::SignednessSemantics val); 127 128 /// RAII helper function to manage entering/exiting C++ scopes. 129 struct Scope { 130 Scope(CppEmitter &emitter) 131 : valueMapperScope(emitter.valueMapper), 132 blockMapperScope(emitter.blockMapper), emitter(emitter) { 133 emitter.valueInScopeCount.push(emitter.valueInScopeCount.top()); 134 emitter.labelInScopeCount.push(emitter.labelInScopeCount.top()); 135 } 136 ~Scope() { 137 emitter.valueInScopeCount.pop(); 138 emitter.labelInScopeCount.pop(); 139 } 140 141 private: 142 llvm::ScopedHashTableScope<Value, std::string> valueMapperScope; 143 llvm::ScopedHashTableScope<Block *, std::string> blockMapperScope; 144 CppEmitter &emitter; 145 }; 146 147 /// Returns wether the Value is assigned to a C++ variable in the scope. 148 bool hasValueInScope(Value val); 149 150 // Returns whether a label is assigned to the block. 151 bool hasBlockLabel(Block &block); 152 153 /// Returns the output stream. 154 raw_indented_ostream &ostream() { return os; }; 155 156 /// Returns if all variables for op results and basic block arguments need to 157 /// be declared at the beginning of a function. 158 bool shouldDeclareVariablesAtTop() { return declareVariablesAtTop; }; 159 160 private: 161 using ValueMapper = llvm::ScopedHashTable<Value, std::string>; 162 using BlockMapper = llvm::ScopedHashTable<Block *, std::string>; 163 164 /// Output stream to emit to. 165 raw_indented_ostream os; 166 167 /// Boolean to enforce that all variables for op results and block 168 /// arguments are declared at the beginning of the function. This also 169 /// includes results from ops located in nested regions. 170 bool declareVariablesAtTop; 171 172 /// Map from value to name of C++ variable that contain the name. 173 ValueMapper valueMapper; 174 175 /// Map from block to name of C++ label. 176 BlockMapper blockMapper; 177 178 /// The number of values in the current scope. This is used to declare the 179 /// names of values in a scope. 180 std::stack<int64_t> valueInScopeCount; 181 std::stack<int64_t> labelInScopeCount; 182 }; 183 } // namespace 184 185 static LogicalResult printConstantOp(CppEmitter &emitter, Operation *operation, 186 Attribute value) { 187 OpResult result = operation->getResult(0); 188 189 // Only emit an assignment as the variable was already declared when printing 190 // the FuncOp. 191 if (emitter.shouldDeclareVariablesAtTop()) { 192 // Skip the assignment if the emitc.constant has no value. 193 if (auto oAttr = value.dyn_cast<emitc::OpaqueAttr>()) { 194 if (oAttr.getValue().empty()) 195 return success(); 196 } 197 198 if (failed(emitter.emitVariableAssignment(result))) 199 return failure(); 200 return emitter.emitAttribute(operation->getLoc(), value); 201 } 202 203 // Emit a variable declaration for an emitc.constant op without value. 204 if (auto oAttr = value.dyn_cast<emitc::OpaqueAttr>()) { 205 if (oAttr.getValue().empty()) 206 // The semicolon gets printed by the emitOperation function. 207 return emitter.emitVariableDeclaration(result, 208 /*trailingSemicolon=*/false); 209 } 210 211 // Emit a variable declaration. 212 if (failed(emitter.emitAssignPrefix(*operation))) 213 return failure(); 214 return emitter.emitAttribute(operation->getLoc(), value); 215 } 216 217 static LogicalResult printOperation(CppEmitter &emitter, 218 emitc::ConstantOp constantOp) { 219 Operation *operation = constantOp.getOperation(); 220 Attribute value = constantOp.value(); 221 222 return printConstantOp(emitter, operation, value); 223 } 224 225 static LogicalResult printOperation(CppEmitter &emitter, 226 emitc::VariableOp variableOp) { 227 Operation *operation = variableOp.getOperation(); 228 Attribute value = variableOp.value(); 229 230 return printConstantOp(emitter, operation, value); 231 } 232 233 static LogicalResult printOperation(CppEmitter &emitter, 234 arith::ConstantOp constantOp) { 235 Operation *operation = constantOp.getOperation(); 236 Attribute value = constantOp.getValue(); 237 238 return printConstantOp(emitter, operation, value); 239 } 240 241 static LogicalResult printOperation(CppEmitter &emitter, 242 func::ConstantOp constantOp) { 243 Operation *operation = constantOp.getOperation(); 244 Attribute value = constantOp.getValueAttr(); 245 246 return printConstantOp(emitter, operation, value); 247 } 248 249 static LogicalResult printOperation(CppEmitter &emitter, 250 cf::BranchOp branchOp) { 251 raw_ostream &os = emitter.ostream(); 252 Block &successor = *branchOp.getSuccessor(); 253 254 for (auto pair : 255 llvm::zip(branchOp.getOperands(), successor.getArguments())) { 256 Value &operand = std::get<0>(pair); 257 BlockArgument &argument = std::get<1>(pair); 258 os << emitter.getOrCreateName(argument) << " = " 259 << emitter.getOrCreateName(operand) << ";\n"; 260 } 261 262 os << "goto "; 263 if (!(emitter.hasBlockLabel(successor))) 264 return branchOp.emitOpError("unable to find label for successor block"); 265 os << emitter.getOrCreateName(successor); 266 return success(); 267 } 268 269 static LogicalResult printOperation(CppEmitter &emitter, 270 cf::CondBranchOp condBranchOp) { 271 raw_indented_ostream &os = emitter.ostream(); 272 Block &trueSuccessor = *condBranchOp.getTrueDest(); 273 Block &falseSuccessor = *condBranchOp.getFalseDest(); 274 275 os << "if (" << emitter.getOrCreateName(condBranchOp.getCondition()) 276 << ") {\n"; 277 278 os.indent(); 279 280 // If condition is true. 281 for (auto pair : llvm::zip(condBranchOp.getTrueOperands(), 282 trueSuccessor.getArguments())) { 283 Value &operand = std::get<0>(pair); 284 BlockArgument &argument = std::get<1>(pair); 285 os << emitter.getOrCreateName(argument) << " = " 286 << emitter.getOrCreateName(operand) << ";\n"; 287 } 288 289 os << "goto "; 290 if (!(emitter.hasBlockLabel(trueSuccessor))) { 291 return condBranchOp.emitOpError("unable to find label for successor block"); 292 } 293 os << emitter.getOrCreateName(trueSuccessor) << ";\n"; 294 os.unindent() << "} else {\n"; 295 os.indent(); 296 // If condition is false. 297 for (auto pair : llvm::zip(condBranchOp.getFalseOperands(), 298 falseSuccessor.getArguments())) { 299 Value &operand = std::get<0>(pair); 300 BlockArgument &argument = std::get<1>(pair); 301 os << emitter.getOrCreateName(argument) << " = " 302 << emitter.getOrCreateName(operand) << ";\n"; 303 } 304 305 os << "goto "; 306 if (!(emitter.hasBlockLabel(falseSuccessor))) { 307 return condBranchOp.emitOpError() 308 << "unable to find label for successor block"; 309 } 310 os << emitter.getOrCreateName(falseSuccessor) << ";\n"; 311 os.unindent() << "}"; 312 return success(); 313 } 314 315 static LogicalResult printOperation(CppEmitter &emitter, func::CallOp callOp) { 316 if (failed(emitter.emitAssignPrefix(*callOp.getOperation()))) 317 return failure(); 318 319 raw_ostream &os = emitter.ostream(); 320 os << callOp.getCallee() << "("; 321 if (failed(emitter.emitOperands(*callOp.getOperation()))) 322 return failure(); 323 os << ")"; 324 return success(); 325 } 326 327 static LogicalResult printOperation(CppEmitter &emitter, emitc::CallOp callOp) { 328 raw_ostream &os = emitter.ostream(); 329 Operation &op = *callOp.getOperation(); 330 331 if (failed(emitter.emitAssignPrefix(op))) 332 return failure(); 333 os << callOp.callee(); 334 335 auto emitArgs = [&](Attribute attr) -> LogicalResult { 336 if (auto t = attr.dyn_cast<IntegerAttr>()) { 337 // Index attributes are treated specially as operand index. 338 if (t.getType().isIndex()) { 339 int64_t idx = t.getInt(); 340 if ((idx < 0) || (idx >= op.getNumOperands())) 341 return op.emitOpError("invalid operand index"); 342 if (!emitter.hasValueInScope(op.getOperand(idx))) 343 return op.emitOpError("operand ") 344 << idx << "'s value not defined in scope"; 345 os << emitter.getOrCreateName(op.getOperand(idx)); 346 return success(); 347 } 348 } 349 if (failed(emitter.emitAttribute(op.getLoc(), attr))) 350 return failure(); 351 352 return success(); 353 }; 354 355 if (callOp.template_args()) { 356 os << "<"; 357 if (failed(interleaveCommaWithError(*callOp.template_args(), os, emitArgs))) 358 return failure(); 359 os << ">"; 360 } 361 362 os << "("; 363 364 LogicalResult emittedArgs = 365 callOp.args() ? interleaveCommaWithError(*callOp.args(), os, emitArgs) 366 : emitter.emitOperands(op); 367 if (failed(emittedArgs)) 368 return failure(); 369 os << ")"; 370 return success(); 371 } 372 373 static LogicalResult printOperation(CppEmitter &emitter, 374 emitc::ApplyOp applyOp) { 375 raw_ostream &os = emitter.ostream(); 376 Operation &op = *applyOp.getOperation(); 377 378 if (failed(emitter.emitAssignPrefix(op))) 379 return failure(); 380 os << applyOp.applicableOperator(); 381 os << emitter.getOrCreateName(applyOp.getOperand()); 382 383 return success(); 384 } 385 386 static LogicalResult printOperation(CppEmitter &emitter, emitc::CastOp castOp) { 387 raw_ostream &os = emitter.ostream(); 388 Operation &op = *castOp.getOperation(); 389 390 if (failed(emitter.emitAssignPrefix(op))) 391 return failure(); 392 os << "("; 393 if (failed(emitter.emitType(op.getLoc(), op.getResult(0).getType()))) 394 return failure(); 395 os << ") "; 396 os << emitter.getOrCreateName(castOp.getOperand()); 397 398 return success(); 399 } 400 401 static LogicalResult printOperation(CppEmitter &emitter, 402 emitc::IncludeOp includeOp) { 403 raw_ostream &os = emitter.ostream(); 404 405 os << "#include "; 406 if (includeOp.is_standard_include()) 407 os << "<" << includeOp.include() << ">"; 408 else 409 os << "\"" << includeOp.include() << "\""; 410 411 return success(); 412 } 413 414 static LogicalResult printOperation(CppEmitter &emitter, scf::ForOp forOp) { 415 416 raw_indented_ostream &os = emitter.ostream(); 417 418 OperandRange operands = forOp.getIterOperands(); 419 Block::BlockArgListType iterArgs = forOp.getRegionIterArgs(); 420 Operation::result_range results = forOp.getResults(); 421 422 if (!emitter.shouldDeclareVariablesAtTop()) { 423 for (OpResult result : results) { 424 if (failed(emitter.emitVariableDeclaration(result, 425 /*trailingSemicolon=*/true))) 426 return failure(); 427 } 428 } 429 430 for (auto pair : llvm::zip(iterArgs, operands)) { 431 if (failed(emitter.emitType(forOp.getLoc(), std::get<0>(pair).getType()))) 432 return failure(); 433 os << " " << emitter.getOrCreateName(std::get<0>(pair)) << " = "; 434 os << emitter.getOrCreateName(std::get<1>(pair)) << ";"; 435 os << "\n"; 436 } 437 438 os << "for ("; 439 if (failed( 440 emitter.emitType(forOp.getLoc(), forOp.getInductionVar().getType()))) 441 return failure(); 442 os << " "; 443 os << emitter.getOrCreateName(forOp.getInductionVar()); 444 os << " = "; 445 os << emitter.getOrCreateName(forOp.getLowerBound()); 446 os << "; "; 447 os << emitter.getOrCreateName(forOp.getInductionVar()); 448 os << " < "; 449 os << emitter.getOrCreateName(forOp.getUpperBound()); 450 os << "; "; 451 os << emitter.getOrCreateName(forOp.getInductionVar()); 452 os << " += "; 453 os << emitter.getOrCreateName(forOp.getStep()); 454 os << ") {\n"; 455 os.indent(); 456 457 Region &forRegion = forOp.getRegion(); 458 auto regionOps = forRegion.getOps(); 459 460 // We skip the trailing yield op because this updates the result variables 461 // of the for op in the generated code. Instead we update the iterArgs at 462 // the end of a loop iteration and set the result variables after the for 463 // loop. 464 for (auto it = regionOps.begin(); std::next(it) != regionOps.end(); ++it) { 465 if (failed(emitter.emitOperation(*it, /*trailingSemicolon=*/true))) 466 return failure(); 467 } 468 469 Operation *yieldOp = forRegion.getBlocks().front().getTerminator(); 470 // Copy yield operands into iterArgs at the end of a loop iteration. 471 for (auto pair : llvm::zip(iterArgs, yieldOp->getOperands())) { 472 BlockArgument iterArg = std::get<0>(pair); 473 Value operand = std::get<1>(pair); 474 os << emitter.getOrCreateName(iterArg) << " = " 475 << emitter.getOrCreateName(operand) << ";\n"; 476 } 477 478 os.unindent() << "}"; 479 480 // Copy iterArgs into results after the for loop. 481 for (auto pair : llvm::zip(results, iterArgs)) { 482 OpResult result = std::get<0>(pair); 483 BlockArgument iterArg = std::get<1>(pair); 484 os << "\n" 485 << emitter.getOrCreateName(result) << " = " 486 << emitter.getOrCreateName(iterArg) << ";"; 487 } 488 489 return success(); 490 } 491 492 static LogicalResult printOperation(CppEmitter &emitter, scf::IfOp ifOp) { 493 raw_indented_ostream &os = emitter.ostream(); 494 495 if (!emitter.shouldDeclareVariablesAtTop()) { 496 for (OpResult result : ifOp.getResults()) { 497 if (failed(emitter.emitVariableDeclaration(result, 498 /*trailingSemicolon=*/true))) 499 return failure(); 500 } 501 } 502 503 os << "if ("; 504 if (failed(emitter.emitOperands(*ifOp.getOperation()))) 505 return failure(); 506 os << ") {\n"; 507 os.indent(); 508 509 Region &thenRegion = ifOp.getThenRegion(); 510 for (Operation &op : thenRegion.getOps()) { 511 // Note: This prints a superfluous semicolon if the terminating yield op has 512 // zero results. 513 if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/true))) 514 return failure(); 515 } 516 517 os.unindent() << "}"; 518 519 Region &elseRegion = ifOp.getElseRegion(); 520 if (!elseRegion.empty()) { 521 os << " else {\n"; 522 os.indent(); 523 524 for (Operation &op : elseRegion.getOps()) { 525 // Note: This prints a superfluous semicolon if the terminating yield op 526 // has zero results. 527 if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/true))) 528 return failure(); 529 } 530 531 os.unindent() << "}"; 532 } 533 534 return success(); 535 } 536 537 static LogicalResult printOperation(CppEmitter &emitter, scf::YieldOp yieldOp) { 538 raw_ostream &os = emitter.ostream(); 539 Operation &parentOp = *yieldOp.getOperation()->getParentOp(); 540 541 if (yieldOp.getNumOperands() != parentOp.getNumResults()) { 542 return yieldOp.emitError("number of operands does not to match the number " 543 "of the parent op's results"); 544 } 545 546 if (failed(interleaveWithError( 547 llvm::zip(parentOp.getResults(), yieldOp.getOperands()), 548 [&](auto pair) -> LogicalResult { 549 auto result = std::get<0>(pair); 550 auto operand = std::get<1>(pair); 551 os << emitter.getOrCreateName(result) << " = "; 552 553 if (!emitter.hasValueInScope(operand)) 554 return yieldOp.emitError("operand value not in scope"); 555 os << emitter.getOrCreateName(operand); 556 return success(); 557 }, 558 [&]() { os << ";\n"; }))) 559 return failure(); 560 561 return success(); 562 } 563 564 static LogicalResult printOperation(CppEmitter &emitter, 565 func::ReturnOp returnOp) { 566 raw_ostream &os = emitter.ostream(); 567 os << "return"; 568 switch (returnOp.getNumOperands()) { 569 case 0: 570 return success(); 571 case 1: 572 os << " " << emitter.getOrCreateName(returnOp.getOperand(0)); 573 return success(emitter.hasValueInScope(returnOp.getOperand(0))); 574 default: 575 os << " std::make_tuple("; 576 if (failed(emitter.emitOperandsAndAttributes(*returnOp.getOperation()))) 577 return failure(); 578 os << ")"; 579 return success(); 580 } 581 } 582 583 static LogicalResult printOperation(CppEmitter &emitter, ModuleOp moduleOp) { 584 CppEmitter::Scope scope(emitter); 585 586 for (Operation &op : moduleOp) { 587 if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/false))) 588 return failure(); 589 } 590 return success(); 591 } 592 593 static LogicalResult printOperation(CppEmitter &emitter, 594 func::FuncOp functionOp) { 595 // We need to declare variables at top if the function has multiple blocks. 596 if (!emitter.shouldDeclareVariablesAtTop() && 597 functionOp.getBlocks().size() > 1) { 598 return functionOp.emitOpError( 599 "with multiple blocks needs variables declared at top"); 600 } 601 602 CppEmitter::Scope scope(emitter); 603 raw_indented_ostream &os = emitter.ostream(); 604 if (failed(emitter.emitTypes(functionOp.getLoc(), 605 functionOp.getFunctionType().getResults()))) 606 return failure(); 607 os << " " << functionOp.getName(); 608 609 os << "("; 610 if (failed(interleaveCommaWithError( 611 functionOp.getArguments(), os, 612 [&](BlockArgument arg) -> LogicalResult { 613 if (failed(emitter.emitType(functionOp.getLoc(), arg.getType()))) 614 return failure(); 615 os << " " << emitter.getOrCreateName(arg); 616 return success(); 617 }))) 618 return failure(); 619 os << ") {\n"; 620 os.indent(); 621 if (emitter.shouldDeclareVariablesAtTop()) { 622 // Declare all variables that hold op results including those from nested 623 // regions. 624 WalkResult result = 625 functionOp.walk<WalkOrder::PreOrder>([&](Operation *op) -> WalkResult { 626 for (OpResult result : op->getResults()) { 627 if (failed(emitter.emitVariableDeclaration( 628 result, /*trailingSemicolon=*/true))) { 629 return WalkResult( 630 op->emitError("unable to declare result variable for op")); 631 } 632 } 633 return WalkResult::advance(); 634 }); 635 if (result.wasInterrupted()) 636 return failure(); 637 } 638 639 Region::BlockListType &blocks = functionOp.getBlocks(); 640 // Create label names for basic blocks. 641 for (Block &block : blocks) { 642 emitter.getOrCreateName(block); 643 } 644 645 // Declare variables for basic block arguments. 646 for (auto it = std::next(blocks.begin()); it != blocks.end(); ++it) { 647 Block &block = *it; 648 for (BlockArgument &arg : block.getArguments()) { 649 if (emitter.hasValueInScope(arg)) 650 return functionOp.emitOpError(" block argument #") 651 << arg.getArgNumber() << " is out of scope"; 652 if (failed( 653 emitter.emitType(block.getParentOp()->getLoc(), arg.getType()))) { 654 return failure(); 655 } 656 os << " " << emitter.getOrCreateName(arg) << ";\n"; 657 } 658 } 659 660 for (Block &block : blocks) { 661 // Only print a label if the block has predecessors. 662 if (!block.hasNoPredecessors()) { 663 if (failed(emitter.emitLabel(block))) 664 return failure(); 665 } 666 for (Operation &op : block.getOperations()) { 667 // When generating code for an scf.if or cf.cond_br op no semicolon needs 668 // to be printed after the closing brace. 669 // When generating code for an scf.for op, printing a trailing semicolon 670 // is handled within the printOperation function. 671 bool trailingSemicolon = 672 !isa<scf::IfOp, scf::ForOp, cf::CondBranchOp>(op); 673 674 if (failed(emitter.emitOperation( 675 op, /*trailingSemicolon=*/trailingSemicolon))) 676 return failure(); 677 } 678 } 679 os.unindent() << "}\n"; 680 return success(); 681 } 682 683 CppEmitter::CppEmitter(raw_ostream &os, bool declareVariablesAtTop) 684 : os(os), declareVariablesAtTop(declareVariablesAtTop) { 685 valueInScopeCount.push(0); 686 labelInScopeCount.push(0); 687 } 688 689 /// Return the existing or a new name for a Value. 690 StringRef CppEmitter::getOrCreateName(Value val) { 691 if (!valueMapper.count(val)) 692 valueMapper.insert(val, formatv("v{0}", ++valueInScopeCount.top())); 693 return *valueMapper.begin(val); 694 } 695 696 /// Return the existing or a new label for a Block. 697 StringRef CppEmitter::getOrCreateName(Block &block) { 698 if (!blockMapper.count(&block)) 699 blockMapper.insert(&block, formatv("label{0}", ++labelInScopeCount.top())); 700 return *blockMapper.begin(&block); 701 } 702 703 bool CppEmitter::shouldMapToUnsigned(IntegerType::SignednessSemantics val) { 704 switch (val) { 705 case IntegerType::Signless: 706 return false; 707 case IntegerType::Signed: 708 return false; 709 case IntegerType::Unsigned: 710 return true; 711 } 712 llvm_unreachable("Unexpected IntegerType::SignednessSemantics"); 713 } 714 715 bool CppEmitter::hasValueInScope(Value val) { return valueMapper.count(val); } 716 717 bool CppEmitter::hasBlockLabel(Block &block) { 718 return blockMapper.count(&block); 719 } 720 721 LogicalResult CppEmitter::emitAttribute(Location loc, Attribute attr) { 722 auto printInt = [&](const APInt &val, bool isUnsigned) { 723 if (val.getBitWidth() == 1) { 724 if (val.getBoolValue()) 725 os << "true"; 726 else 727 os << "false"; 728 } else { 729 SmallString<128> strValue; 730 val.toString(strValue, 10, !isUnsigned, false); 731 os << strValue; 732 } 733 }; 734 735 auto printFloat = [&](const APFloat &val) { 736 if (val.isFinite()) { 737 SmallString<128> strValue; 738 // Use default values of toString except don't truncate zeros. 739 val.toString(strValue, 0, 0, false); 740 switch (llvm::APFloatBase::SemanticsToEnum(val.getSemantics())) { 741 case llvm::APFloatBase::S_IEEEsingle: 742 os << "(float)"; 743 break; 744 case llvm::APFloatBase::S_IEEEdouble: 745 os << "(double)"; 746 break; 747 default: 748 break; 749 }; 750 os << strValue; 751 } else if (val.isNaN()) { 752 os << "NAN"; 753 } else if (val.isInfinity()) { 754 if (val.isNegative()) 755 os << "-"; 756 os << "INFINITY"; 757 } 758 }; 759 760 // Print floating point attributes. 761 if (auto fAttr = attr.dyn_cast<FloatAttr>()) { 762 printFloat(fAttr.getValue()); 763 return success(); 764 } 765 if (auto dense = attr.dyn_cast<DenseFPElementsAttr>()) { 766 os << '{'; 767 interleaveComma(dense, os, [&](const APFloat &val) { printFloat(val); }); 768 os << '}'; 769 return success(); 770 } 771 772 // Print integer attributes. 773 if (auto iAttr = attr.dyn_cast<IntegerAttr>()) { 774 if (auto iType = iAttr.getType().dyn_cast<IntegerType>()) { 775 printInt(iAttr.getValue(), shouldMapToUnsigned(iType.getSignedness())); 776 return success(); 777 } 778 if (auto iType = iAttr.getType().dyn_cast<IndexType>()) { 779 printInt(iAttr.getValue(), false); 780 return success(); 781 } 782 } 783 if (auto dense = attr.dyn_cast<DenseIntElementsAttr>()) { 784 if (auto iType = dense.getType() 785 .cast<TensorType>() 786 .getElementType() 787 .dyn_cast<IntegerType>()) { 788 os << '{'; 789 interleaveComma(dense, os, [&](const APInt &val) { 790 printInt(val, shouldMapToUnsigned(iType.getSignedness())); 791 }); 792 os << '}'; 793 return success(); 794 } 795 if (auto iType = dense.getType() 796 .cast<TensorType>() 797 .getElementType() 798 .dyn_cast<IndexType>()) { 799 os << '{'; 800 interleaveComma(dense, os, 801 [&](const APInt &val) { printInt(val, false); }); 802 os << '}'; 803 return success(); 804 } 805 } 806 807 // Print opaque attributes. 808 if (auto oAttr = attr.dyn_cast<emitc::OpaqueAttr>()) { 809 os << oAttr.getValue(); 810 return success(); 811 } 812 813 // Print symbolic reference attributes. 814 if (auto sAttr = attr.dyn_cast<SymbolRefAttr>()) { 815 if (sAttr.getNestedReferences().size() > 1) 816 return emitError(loc, "attribute has more than 1 nested reference"); 817 os << sAttr.getRootReference().getValue(); 818 return success(); 819 } 820 821 // Print type attributes. 822 if (auto type = attr.dyn_cast<TypeAttr>()) 823 return emitType(loc, type.getValue()); 824 825 return emitError(loc, "cannot emit attribute of type ") << attr.getType(); 826 } 827 828 LogicalResult CppEmitter::emitOperands(Operation &op) { 829 auto emitOperandName = [&](Value result) -> LogicalResult { 830 if (!hasValueInScope(result)) 831 return op.emitOpError() << "operand value not in scope"; 832 os << getOrCreateName(result); 833 return success(); 834 }; 835 return interleaveCommaWithError(op.getOperands(), os, emitOperandName); 836 } 837 838 LogicalResult 839 CppEmitter::emitOperandsAndAttributes(Operation &op, 840 ArrayRef<StringRef> exclude) { 841 if (failed(emitOperands(op))) 842 return failure(); 843 // Insert comma in between operands and non-filtered attributes if needed. 844 if (op.getNumOperands() > 0) { 845 for (NamedAttribute attr : op.getAttrs()) { 846 if (!llvm::is_contained(exclude, attr.getName().strref())) { 847 os << ", "; 848 break; 849 } 850 } 851 } 852 // Emit attributes. 853 auto emitNamedAttribute = [&](NamedAttribute attr) -> LogicalResult { 854 if (llvm::is_contained(exclude, attr.getName().strref())) 855 return success(); 856 os << "/* " << attr.getName().getValue() << " */"; 857 if (failed(emitAttribute(op.getLoc(), attr.getValue()))) 858 return failure(); 859 return success(); 860 }; 861 return interleaveCommaWithError(op.getAttrs(), os, emitNamedAttribute); 862 } 863 864 LogicalResult CppEmitter::emitVariableAssignment(OpResult result) { 865 if (!hasValueInScope(result)) { 866 return result.getDefiningOp()->emitOpError( 867 "result variable for the operation has not been declared"); 868 } 869 os << getOrCreateName(result) << " = "; 870 return success(); 871 } 872 873 LogicalResult CppEmitter::emitVariableDeclaration(OpResult result, 874 bool trailingSemicolon) { 875 if (hasValueInScope(result)) { 876 return result.getDefiningOp()->emitError( 877 "result variable for the operation already declared"); 878 } 879 if (failed(emitType(result.getOwner()->getLoc(), result.getType()))) 880 return failure(); 881 os << " " << getOrCreateName(result); 882 if (trailingSemicolon) 883 os << ";\n"; 884 return success(); 885 } 886 887 LogicalResult CppEmitter::emitAssignPrefix(Operation &op) { 888 switch (op.getNumResults()) { 889 case 0: 890 break; 891 case 1: { 892 OpResult result = op.getResult(0); 893 if (shouldDeclareVariablesAtTop()) { 894 if (failed(emitVariableAssignment(result))) 895 return failure(); 896 } else { 897 if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/false))) 898 return failure(); 899 os << " = "; 900 } 901 break; 902 } 903 default: 904 if (!shouldDeclareVariablesAtTop()) { 905 for (OpResult result : op.getResults()) { 906 if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/true))) 907 return failure(); 908 } 909 } 910 os << "std::tie("; 911 interleaveComma(op.getResults(), os, 912 [&](Value result) { os << getOrCreateName(result); }); 913 os << ") = "; 914 } 915 return success(); 916 } 917 918 LogicalResult CppEmitter::emitLabel(Block &block) { 919 if (!hasBlockLabel(block)) 920 return block.getParentOp()->emitError("label for block not found"); 921 // FIXME: Add feature in `raw_indented_ostream` to ignore indent for block 922 // label instead of using `getOStream`. 923 os.getOStream() << getOrCreateName(block) << ":\n"; 924 return success(); 925 } 926 927 LogicalResult CppEmitter::emitOperation(Operation &op, bool trailingSemicolon) { 928 LogicalResult status = 929 llvm::TypeSwitch<Operation *, LogicalResult>(&op) 930 // Builtin ops. 931 .Case<ModuleOp>([&](auto op) { return printOperation(*this, op); }) 932 // CF ops. 933 .Case<cf::BranchOp, cf::CondBranchOp>( 934 [&](auto op) { return printOperation(*this, op); }) 935 // EmitC ops. 936 .Case<emitc::ApplyOp, emitc::CallOp, emitc::CastOp, emitc::ConstantOp, 937 emitc::IncludeOp, emitc::VariableOp>( 938 [&](auto op) { return printOperation(*this, op); }) 939 // Func ops. 940 .Case<func::CallOp, func::ConstantOp, func::FuncOp, func::ReturnOp>( 941 [&](auto op) { return printOperation(*this, op); }) 942 // SCF ops. 943 .Case<scf::ForOp, scf::IfOp, scf::YieldOp>( 944 [&](auto op) { return printOperation(*this, op); }) 945 // Arithmetic ops. 946 .Case<arith::ConstantOp>( 947 [&](auto op) { return printOperation(*this, op); }) 948 .Default([&](Operation *) { 949 return op.emitOpError("unable to find printer for op"); 950 }); 951 952 if (failed(status)) 953 return failure(); 954 os << (trailingSemicolon ? ";\n" : "\n"); 955 return success(); 956 } 957 958 LogicalResult CppEmitter::emitType(Location loc, Type type) { 959 if (auto iType = type.dyn_cast<IntegerType>()) { 960 switch (iType.getWidth()) { 961 case 1: 962 return (os << "bool"), success(); 963 case 8: 964 case 16: 965 case 32: 966 case 64: 967 if (shouldMapToUnsigned(iType.getSignedness())) 968 return (os << "uint" << iType.getWidth() << "_t"), success(); 969 else 970 return (os << "int" << iType.getWidth() << "_t"), success(); 971 default: 972 return emitError(loc, "cannot emit integer type ") << type; 973 } 974 } 975 if (auto fType = type.dyn_cast<FloatType>()) { 976 switch (fType.getWidth()) { 977 case 32: 978 return (os << "float"), success(); 979 case 64: 980 return (os << "double"), success(); 981 default: 982 return emitError(loc, "cannot emit float type ") << type; 983 } 984 } 985 if (auto iType = type.dyn_cast<IndexType>()) 986 return (os << "size_t"), success(); 987 if (auto tType = type.dyn_cast<TensorType>()) { 988 if (!tType.hasRank()) 989 return emitError(loc, "cannot emit unranked tensor type"); 990 if (!tType.hasStaticShape()) 991 return emitError(loc, "cannot emit tensor type with non static shape"); 992 os << "Tensor<"; 993 if (failed(emitType(loc, tType.getElementType()))) 994 return failure(); 995 auto shape = tType.getShape(); 996 for (auto dimSize : shape) { 997 os << ", "; 998 os << dimSize; 999 } 1000 os << ">"; 1001 return success(); 1002 } 1003 if (auto tType = type.dyn_cast<TupleType>()) 1004 return emitTupleType(loc, tType.getTypes()); 1005 if (auto oType = type.dyn_cast<emitc::OpaqueType>()) { 1006 os << oType.getValue(); 1007 return success(); 1008 } 1009 if (auto pType = type.dyn_cast<emitc::PointerType>()) { 1010 if (failed(emitType(loc, pType.getPointee()))) 1011 return failure(); 1012 os << "*"; 1013 return success(); 1014 } 1015 return emitError(loc, "cannot emit type ") << type; 1016 } 1017 1018 LogicalResult CppEmitter::emitTypes(Location loc, ArrayRef<Type> types) { 1019 switch (types.size()) { 1020 case 0: 1021 os << "void"; 1022 return success(); 1023 case 1: 1024 return emitType(loc, types.front()); 1025 default: 1026 return emitTupleType(loc, types); 1027 } 1028 } 1029 1030 LogicalResult CppEmitter::emitTupleType(Location loc, ArrayRef<Type> types) { 1031 os << "std::tuple<"; 1032 if (failed(interleaveCommaWithError( 1033 types, os, [&](Type type) { return emitType(loc, type); }))) 1034 return failure(); 1035 os << ">"; 1036 return success(); 1037 } 1038 1039 LogicalResult emitc::translateToCpp(Operation *op, raw_ostream &os, 1040 bool declareVariablesAtTop) { 1041 CppEmitter emitter(os, declareVariablesAtTop); 1042 return emitter.emitOperation(*op, /*trailingSemicolon=*/false); 1043 } 1044