MLIR 24.0.0git
EmitC.cpp
Go to the documentation of this file.
1//===- EmitC.cpp - EmitC Dialect ------------------------------------------===//
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
11#include "mlir/IR/Builders.h"
14#include "mlir/IR/IRMapping.h"
15#include "mlir/IR/Types.h"
17#include "mlir/Support/LLVM.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/Casting.h"
21
22using namespace mlir;
23using namespace mlir::emitc;
24
25#include "mlir/Dialect/EmitC/IR/EmitCDialect.cpp.inc"
26
27//===----------------------------------------------------------------------===//
28// EmitCDialect
29//===----------------------------------------------------------------------===//
30
31/// Materialize a single constant operation from a given attribute value with
32/// the desired resultant type.
33Operation *EmitCDialect::materializeConstant(OpBuilder &builder,
34 Attribute value, Type type,
35 Location loc) {
36 return emitc::ConstantOp::create(builder, loc, type, value);
37}
38
39/// Default callback for builders of ops carrying a region. Inserts a yield
40/// without arguments.
42 emitc::YieldOp::create(builder, loc);
43}
44
46 if (llvm::isa<emitc::OpaqueType>(type))
47 return true;
48 if (auto ptrType = llvm::dyn_cast<emitc::PointerType>(type))
49 return isSupportedEmitCType(ptrType.getPointee());
50 if (auto arrayType = llvm::dyn_cast<emitc::ArrayType>(type)) {
51 auto elemType = arrayType.getElementType();
52 return !llvm::isa<emitc::ArrayType>(elemType) &&
53 isSupportedEmitCType(elemType);
54 }
55 if (type.isIndex() || emitc::isPointerWideType(type))
56 return true;
57 if (llvm::isa<IntegerType>(type))
58 return isSupportedIntegerType(type);
59 if (llvm::isa<FloatType>(type))
60 return isSupportedFloatType(type);
61 if (auto tensorType = llvm::dyn_cast<TensorType>(type)) {
62 if (!tensorType.hasStaticShape()) {
63 return false;
64 }
65 auto elemType = tensorType.getElementType();
66 if (llvm::isa<emitc::ArrayType>(elemType)) {
67 return false;
68 }
69 return isSupportedEmitCType(elemType);
70 }
71 if (auto tupleType = llvm::dyn_cast<TupleType>(type)) {
72 return llvm::all_of(tupleType.getTypes(), [](Type type) {
73 return !llvm::isa<emitc::ArrayType>(type) && isSupportedEmitCType(type);
74 });
75 }
76 return false;
77}
78
80 if (auto intType = llvm::dyn_cast<IntegerType>(type)) {
81 switch (intType.getWidth()) {
82 case 1:
83 case 8:
84 case 16:
85 case 32:
86 case 64:
87 return true;
88 default:
89 return false;
90 }
91 }
92 return false;
93}
94
96 return llvm::isa<IndexType, emitc::OpaqueType>(type) ||
98}
99
101 if (auto floatType = llvm::dyn_cast<FloatType>(type)) {
102 switch (floatType.getWidth()) {
103 case 16:
104 return llvm::isa<Float16Type, BFloat16Type>(type);
105 case 32:
106 case 64:
107 return true;
108 default:
109 return false;
110 }
111 }
112 return false;
113}
114
116 return isa<emitc::SignedSizeTType, emitc::SizeTType, emitc::PtrDiffTType>(
117 type);
118}
119
121 return llvm::isa<IndexType>(type) || isPointerWideType(type) ||
123 isa<emitc::PointerType>(type);
124}
125
126/// Check that the type of the initial value is compatible with the operations
127/// result type.
129 Attribute value) {
130 assert(op->getNumResults() == 1 && "operation must have 1 result");
131
132 if (llvm::isa<emitc::OpaqueAttr>(value))
133 return success();
134
135 if (llvm::isa<StringAttr>(value))
136 return op->emitOpError()
137 << "string attributes are not supported, use #emitc.opaque instead";
138
139 Type resultType = op->getResult(0).getType();
140 if (auto lType = dyn_cast<LValueType>(resultType))
141 resultType = lType.getValueType();
142 Type attrType = cast<TypedAttr>(value).getType();
143
144 if (isPointerWideType(resultType) && attrType.isIndex())
145 return success();
146
147 if (resultType != attrType)
148 return op->emitOpError()
149 << "requires attribute to either be an #emitc.opaque attribute or "
150 "it's type ("
151 << attrType << ") to match the op's result type (" << resultType
152 << ")";
153
154 return success();
155}
156
157/// Parse a format string and return a list of its parts.
158/// A part is either a StringRef that has to be printed as-is, or
159/// a Placeholder which requires printing the next operand of the VerbatimOp.
160/// In the format string, all `{}` are replaced by Placeholders, except if the
161/// `{` is escaped by `{{` - then it doesn't start a placeholder.
162template <class ArgType>
163FailureOr<SmallVector<ReplacementItem>> parseFormatString(
164 StringRef toParse, ArgType fmtArgs,
167
168 // If there are not operands, the format string is not interpreted.
169 if (fmtArgs.empty()) {
170 items.push_back(toParse);
171 return items;
172 }
173
174 while (!toParse.empty()) {
175 size_t idx = toParse.find('{');
176 if (idx == StringRef::npos) {
177 // No '{'
178 items.push_back(toParse);
179 break;
180 }
181 if (idx > 0) {
182 // Take all chars excluding the '{'.
183 items.push_back(toParse.take_front(idx));
184 toParse = toParse.drop_front(idx);
185 continue;
186 }
187 if (toParse.size() < 2) {
188 return emitError() << "expected '}' after unescaped '{' at end of string";
189 }
190 // toParse contains at least two characters and starts with `{`.
191 char nextChar = toParse[1];
192 if (nextChar == '{') {
193 // Double '{{' -> '{' (escaping).
194 items.push_back(toParse.take_front(1));
195 toParse = toParse.drop_front(2);
196 continue;
197 }
198 if (nextChar == '}') {
199 items.push_back(Placeholder{});
200 toParse = toParse.drop_front(2);
201 continue;
202 }
203
204 if (emitError) {
205 return emitError() << "expected '}' after unescaped '{'";
206 }
207 return failure();
208 }
209 return items;
210}
211
212//===----------------------------------------------------------------------===//
213// AddressOfOp
214//===----------------------------------------------------------------------===//
215
216LogicalResult AddressOfOp::verify() {
217 emitc::LValueType referenceType = getReference().getType();
218 emitc::PointerType resultType = getResult().getType();
219
220 if (referenceType.getValueType() != resultType.getPointee())
221 return emitOpError("requires result to be a pointer to the type "
222 "referenced by operand");
223
224 return success();
225}
226
227//===----------------------------------------------------------------------===//
228// AddOp
229//===----------------------------------------------------------------------===//
230
231LogicalResult AddOp::verify() {
232 Type lhsType = getLhs().getType();
233 Type rhsType = getRhs().getType();
234
235 if (isa<emitc::PointerType>(lhsType) && isa<emitc::PointerType>(rhsType))
236 return emitOpError("requires that at most one operand is a pointer");
237
238 if ((isa<emitc::PointerType>(lhsType) &&
239 !isa<IntegerType, emitc::OpaqueType>(rhsType)) ||
240 (isa<emitc::PointerType>(rhsType) &&
241 !isa<IntegerType, emitc::OpaqueType>(lhsType)))
242 return emitOpError("requires that one operand is an integer or of opaque "
243 "type if the other is a pointer");
244
245 return success();
246}
247
248//===----------------------------------------------------------------------===//
249// Assignment operations
250//===----------------------------------------------------------------------===//
251
252template <typename AssignmentOp>
253static LogicalResult verifyAssignmentOp(AssignmentOp op) {
254 TypedValue<emitc::LValueType> variable = op.getVar();
255
256 if (!variable.getDefiningOp())
257 return op.emitOpError() << "cannot assign to block argument";
258
259 Type valueType = op.getValue().getType();
260 Type variableType = variable.getType().getValueType();
261 if (variableType != valueType)
262 return op.emitOpError() << "requires value's type (" << valueType
263 << ") to match variable's type (" << variableType
264 << ")\n variable: " << variable
265 << "\n value: " << op.getValue() << "\n";
266 return success();
267}
268
269LogicalResult emitc::AssignOp::verify() { return verifyAssignmentOp(*this); }
270
271LogicalResult emitc::AddAssignOp::verify() { return verifyAssignmentOp(*this); }
272
273LogicalResult emitc::SubAssignOp::verify() { return verifyAssignmentOp(*this); }
274
275LogicalResult emitc::MulAssignOp::verify() { return verifyAssignmentOp(*this); }
276
277LogicalResult emitc::DivAssignOp::verify() { return verifyAssignmentOp(*this); }
278
279LogicalResult emitc::RemAssignOp::verify() { return verifyAssignmentOp(*this); }
280
281//===----------------------------------------------------------------------===//
282// CastOp
283//===----------------------------------------------------------------------===//
284
285bool CastOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
286 Type input = inputs.front(), output = outputs.front();
287
288 if (auto arrayType = dyn_cast<emitc::ArrayType>(input)) {
289 if (auto pointerType = dyn_cast<emitc::PointerType>(output)) {
290 return (arrayType.getElementType() == pointerType.getPointee()) &&
291 arrayType.getShape().size() == 1 && arrayType.getShape()[0] >= 1;
292 }
293 return false;
294 }
295
296 return (
298 emitc::isSupportedFloatType(input) || isa<emitc::PointerType>(input)) &&
300 emitc::isSupportedFloatType(output) || isa<emitc::PointerType>(output)));
301}
302
303Speculation::Speculatability emitc::CastOp::getSpeculatability() {
305}
306
307void emitc::CastOp::getEffects(
309 if (getPure())
310 return;
311
312 effects.emplace_back(MemoryEffects::Read::get());
313 effects.emplace_back(MemoryEffects::Write::get());
314}
315
316//===----------------------------------------------------------------------===//
317// CallOpaqueOp
318//===----------------------------------------------------------------------===//
319
320static LogicalResult
321verifyOpaqueCallCommon(Operation *op, StringRef callee,
322 std::optional<ArrayAttr> args,
323 std::optional<ArrayAttr> templateArgs,
324 TypeRange resultTypes, size_t numArgsOperands) {
325 // Callee must not be empty.
326 if (callee.empty())
327 return op->emitOpError("callee must not be empty");
328
329 if (args) {
330 for (Attribute arg : *args) {
331 auto intAttr = llvm::dyn_cast<IntegerAttr>(arg);
332 if (intAttr && llvm::isa<IndexType>(intAttr.getType())) {
333 int64_t index = intAttr.getInt();
334 // Args with elements of type index must be in range
335 // [0..numArgsOperands).
336 if ((index < 0) || (index >= static_cast<int64_t>(numArgsOperands)))
337 return op->emitOpError("index argument is out of range");
338
339 } else if (llvm::isa<ArrayAttr>(arg)) {
340 return op->emitOpError("array argument has no type");
341 }
342 }
343 }
344
345 if (templateArgs) {
346 for (Attribute tArg : *templateArgs) {
347 if (!llvm::isa<TypeAttr, IntegerAttr, FloatAttr, emitc::OpaqueAttr>(tArg))
348 return op->emitOpError("template argument has invalid type");
349 }
350 }
351
352 if (llvm::any_of(resultTypes, llvm::IsaPred<ArrayType>)) {
353 return op->emitOpError() << "cannot return array type";
354 }
355
356 return success();
357}
358
359LogicalResult emitc::CallOpaqueOp::verify() {
360 return verifyOpaqueCallCommon(getOperation(), getCallee(), getArgs(),
361 getTemplateArgs(), getResultTypes(),
362 getNumOperands());
363}
364
365LogicalResult emitc::MemberCallOpaqueOp::verify() {
366 return verifyOpaqueCallCommon(getOperation(), getCallee(), getArgs(),
367 getTemplateArgs(), getResultTypes(),
368 getArgOperands().size());
369}
370
371//===----------------------------------------------------------------------===//
372// ConstantOp
373//===----------------------------------------------------------------------===//
374
375LogicalResult emitc::ConstantOp::verify() {
376 Attribute value = getValueAttr();
377 if (failed(verifyInitializationAttribute(getOperation(), value)))
378 return failure();
379 if (auto opaqueValue = llvm::dyn_cast<emitc::OpaqueAttr>(value)) {
380 if (opaqueValue.getValue().empty())
381 return emitOpError() << "value must not be empty";
382 }
383 return success();
384}
385
386OpFoldResult emitc::ConstantOp::fold(FoldAdaptor adaptor) { return getValue(); }
387
388//===----------------------------------------------------------------------===//
389// DereferenceOp
390//===----------------------------------------------------------------------===//
391
392LogicalResult DereferenceOp::verify() {
393 emitc::PointerType pointerType = getPointer().getType();
394
395 if (pointerType.getPointee() != getResult().getType().getValueType())
396 return emitOpError("requires result to be an lvalue of the type "
397 "pointed to by operand");
398
399 return success();
400}
401
402//===----------------------------------------------------------------------===//
403// ExpressionOp
404//===----------------------------------------------------------------------===//
405
406namespace {
407
408struct RemoveRecurringExpressionOperands
409 : public OpRewritePattern<ExpressionOp> {
410 using OpRewritePattern<ExpressionOp>::OpRewritePattern;
411 LogicalResult matchAndRewrite(ExpressionOp expressionOp,
412 PatternRewriter &rewriter) const override {
413 SetVector<Value> uniqueOperands;
414 DenseMap<Value, int> firstIndexOf;
415
416 // Collect duplicate operands and prepare to remove excessive copies.
417 for (auto [i, operand] : llvm::enumerate(expressionOp.getDefs())) {
418 if (uniqueOperands.contains(operand))
419 continue;
420 uniqueOperands.insert(operand);
421 firstIndexOf[operand] = i;
422 }
423
424 // If every operand is unique, bail out.
425 if (uniqueOperands.size() == expressionOp.getDefs().size())
426 return failure();
427
428 // Create a new expression with unique operands.
429 rewriter.setInsertionPointAfter(expressionOp);
430 auto uniqueExpression = emitc::ExpressionOp::create(
431 rewriter, expressionOp.getLoc(), expressionOp.getResult().getType(),
432 uniqueOperands.getArrayRef(), expressionOp.getDoNotInline());
433 Block &uniqueExpressionBody = uniqueExpression.createBody();
434
435 // Map each original block arguments to the unique block argument taking
436 // the same operand.
437 IRMapping mapper;
438 Block *expressionBody = expressionOp.getBody();
439 for (auto [operand, arg] :
440 llvm::zip(expressionOp.getOperands(), expressionBody->getArguments()))
441 mapper.map(arg, uniqueExpressionBody.getArgument(firstIndexOf[operand]));
442
443 rewriter.setInsertionPointToStart(&uniqueExpressionBody);
444 for (Operation &opToClone : *expressionOp.getBody())
445 rewriter.clone(opToClone, mapper);
446
447 // Complete the rewrite.
448 rewriter.replaceOp(expressionOp, uniqueExpression);
449
450 return success();
451 }
452};
453
454/// If an ExpressionOp body yields a block argument directly (no root op),
455/// this means a contained op was folded away (e.g., an identity cast whose
456/// in/out types match). Canonicalize by replacing the expression with the
457/// corresponding operand value.
458struct FoldTrivialExpressionOp : public OpRewritePattern<ExpressionOp> {
459 using OpRewritePattern<ExpressionOp>::OpRewritePattern;
460 LogicalResult matchAndRewrite(ExpressionOp expressionOp,
461 PatternRewriter &rewriter) const override {
462 auto yieldOp = cast<YieldOp>(expressionOp.getBody()->getTerminator());
463 Value yieldedValue = yieldOp.getResult();
464 auto blockArg = dyn_cast_if_present<BlockArgument>(yieldedValue);
465 if (!blockArg)
466 return failure();
467 rewriter.replaceOp(expressionOp,
468 expressionOp.getOperand(blockArg.getArgNumber()));
469 return success();
470 }
471};
472
473} // namespace
474
475void ExpressionOp::getCanonicalizationPatterns(RewritePatternSet &results,
476 MLIRContext *context) {
477 results.add<RemoveRecurringExpressionOperands, FoldTrivialExpressionOp>(
478 context);
479}
480
481ParseResult ExpressionOp::parse(OpAsmParser &parser, OperationState &result) {
483 if (parser.parseOperandList(operands))
484 return parser.emitError(parser.getCurrentLocation()) << "expected operands";
485 if (succeeded(parser.parseOptionalKeyword("noinline")))
486 result.addAttribute(ExpressionOp::getDoNotInlineAttrName(result.name),
487 parser.getBuilder().getUnitAttr());
488 Type type;
489 if (parser.parseColonType(type))
490 return parser.emitError(parser.getCurrentLocation(),
491 "expected function type");
492 auto fnType = llvm::dyn_cast<FunctionType>(type);
493 if (!fnType)
494 return parser.emitError(parser.getCurrentLocation(),
495 "expected function type");
496 if (parser.resolveOperands(operands, fnType.getInputs(),
497 parser.getCurrentLocation(), result.operands))
498 return failure();
499 if (fnType.getNumResults() != 1)
500 return parser.emitError(parser.getCurrentLocation(),
501 "expected single return type");
502 result.addTypes(fnType.getResults());
503 Region *body = result.addRegion();
504 DenseSet<Value> uniqueOperands(result.operands.begin(),
505 result.operands.end());
506 bool enableNameShadowing = uniqueOperands.size() == result.operands.size();
508 if (enableNameShadowing) {
509 for (auto [unresolvedOperand, operandType] :
510 llvm::zip(operands, fnType.getInputs())) {
511 OpAsmParser::Argument argInfo;
512 argInfo.ssaName = unresolvedOperand;
513 argInfo.type = operandType;
514 argsInfo.push_back(argInfo);
515 }
516 }
517 SMLoc beforeRegionLoc = parser.getCurrentLocation();
518 if (parser.parseRegion(*body, argsInfo, enableNameShadowing))
519 return failure();
520 if (!enableNameShadowing) {
521 if (body->front().getArguments().size() < result.operands.size()) {
522 return parser.emitError(
523 beforeRegionLoc, "with recurring operands expected block arguments");
524 }
525 }
526 return success();
527}
528
529void emitc::ExpressionOp::print(OpAsmPrinter &p) {
530 p << ' ';
531 auto operands = getDefs();
532 p.printOperands(operands);
533 p << " : ";
534 p.printFunctionalType(getOperation());
535 DenseSet<Value> uniqueOperands(operands.begin(), operands.end());
536 bool printEntryBlockArgs = true;
537 if (uniqueOperands.size() == operands.size()) {
538 p.shadowRegionArgs(getRegion(), getDefs());
539 printEntryBlockArgs = false;
540 }
541 p << ' ';
542 p.printRegion(getRegion(), printEntryBlockArgs);
543}
544
545Operation *ExpressionOp::getRootOp() {
546 auto yieldOp = cast<YieldOp>(getBody()->getTerminator());
547 Value yieldedValue = yieldOp.getResult();
548 return yieldedValue.getDefiningOp();
549}
550
551LogicalResult ExpressionOp::verify() {
552 Type resultType = getResult().getType();
553 Region &region = getRegion();
554
555 Block &body = region.front();
556
557 if (!body.mightHaveTerminator())
558 return emitOpError("must yield a value at termination");
559
560 auto yield = cast<YieldOp>(body.getTerminator());
561 Value yieldResult = yield.getResult();
562
563 if (!yieldResult)
564 return emitOpError("must yield a value at termination");
565
566 Operation *rootOp = yieldResult.getDefiningOp();
567
568 if (!rootOp)
569 return emitOpError("yielded value has no defining op");
570
571 if (rootOp->getParentOp() != getOperation())
572 return emitOpError("yielded value not defined within expression");
573
574 Type yieldType = yieldResult.getType();
575
576 if (resultType != yieldType)
577 return emitOpError("requires yielded type to match return type");
578
579 for (Operation &op : region.front().without_terminator()) {
580 auto expressionInterface = dyn_cast<emitc::CExpressionInterface>(op);
581 if (!expressionInterface)
582 return emitOpError("contains an unsupported operation");
583 if (op.getNumResults() != 1)
584 return emitOpError("requires exactly one result for each operation");
585 Value result = op.getResult(0);
586 if (result.use_empty())
587 return emitOpError("contains an unused operation");
588 }
589
590 // Make sure any operation with side effect is only reachable once from
591 // the root op, otherwise emission will be replicating side effects.
594 worklist.push_back(rootOp);
595 while (!worklist.empty()) {
596 Operation *op = worklist.back();
597 worklist.pop_back();
598 if (visited.contains(op)) {
599 auto cExpr = cast<CExpressionInterface>(op);
600 if (!cExpr.alwaysInline() && cExpr.hasSideEffects())
601 return emitOpError(
602 "requires exactly one use for operations with side effects");
603 }
604 visited.insert(op);
605 for (Value operand : op->getOperands())
606 if (Operation *def = operand.getDefiningOp()) {
607 worklist.push_back(def);
608 }
609 }
610
611 // It is illegal to forbid inlining of expressions whose root operation must
612 // be inlined.
613 if (getDoNotInline() &&
614 cast<emitc::CExpressionInterface>(rootOp).alwaysInline()) {
615 return emitOpError("root operation must be inlined but expression is marked"
616 " do-not-inline");
617 }
618
619 return success();
620}
621
622//===----------------------------------------------------------------------===//
623// ForOp
624//===----------------------------------------------------------------------===//
625
626void ForOp::build(OpBuilder &builder, OperationState &result, Value lb,
627 Value ub, Value step, BodyBuilderFn bodyBuilder) {
628 OpBuilder::InsertionGuard g(builder);
629 result.addOperands({lb, ub, step});
630 Type t = lb.getType();
631 Region *bodyRegion = result.addRegion();
632 Block *bodyBlock = builder.createBlock(bodyRegion);
633 bodyBlock->addArgument(t, result.location);
634
635 // Create the default terminator if the builder is not provided.
636 if (!bodyBuilder) {
637 ForOp::ensureTerminator(*bodyRegion, builder, result.location);
638 } else {
639 OpBuilder::InsertionGuard guard(builder);
640 builder.setInsertionPointToStart(bodyBlock);
641 bodyBuilder(builder, result.location, bodyBlock->getArgument(0));
642 }
643}
644
645void ForOp::getCanonicalizationPatterns(RewritePatternSet &, MLIRContext *) {}
646
647ParseResult ForOp::parse(OpAsmParser &parser, OperationState &result) {
648 Builder &builder = parser.getBuilder();
649 Type type;
650
651 OpAsmParser::Argument inductionVariable;
653
654 // Parse the induction variable followed by '='.
655 if (parser.parseOperand(inductionVariable.ssaName) || parser.parseEqual() ||
656 // Parse loop bounds.
657 parser.parseOperand(lb) || parser.parseKeyword("to") ||
658 parser.parseOperand(ub) || parser.parseKeyword("step") ||
659 parser.parseOperand(step))
660 return failure();
661
662 // Parse the optional initial iteration arguments.
664 regionArgs.push_back(inductionVariable);
665
666 // Parse optional type, else assume Index.
667 if (parser.parseOptionalColon())
668 type = builder.getIndexType();
669 else if (parser.parseType(type))
670 return failure();
671
672 // Resolve input operands.
673 regionArgs.front().type = type;
674 if (parser.resolveOperand(lb, type, result.operands) ||
675 parser.resolveOperand(ub, type, result.operands) ||
676 parser.resolveOperand(step, type, result.operands))
677 return failure();
678
679 // Parse the body region.
680 Region *body = result.addRegion();
681 if (parser.parseRegion(*body, regionArgs))
682 return failure();
683
684 ForOp::ensureTerminator(*body, builder, result.location);
685
686 // Parse the optional attribute list.
687 if (parser.parseOptionalAttrDict(result.attributes))
688 return failure();
689
690 return success();
691}
692
693void ForOp::print(OpAsmPrinter &p) {
694 p << " " << getInductionVar() << " = " << getLowerBound() << " to "
695 << getUpperBound() << " step " << getStep();
696
697 p << ' ';
698 if (Type t = getInductionVar().getType(); !t.isIndex())
699 p << " : " << t << ' ';
700 p.printRegion(getRegion(),
701 /*printEntryBlockArgs=*/false,
702 /*printBlockTerminators=*/false);
703 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
704}
705
706LogicalResult ForOp::verifyRegions() {
707 // Check that the body defines as single block argument for the induction
708 // variable.
709 if (getBody()->getNumArguments() != 1)
710 return emitOpError("expected body to have a single block argument for the "
711 "induction variable");
712
713 if (getInductionVar().getType() != getLowerBound().getType())
714 return emitOpError(
715 "expected induction variable to be same type as bounds and step");
716
717 return success();
718}
719
720//===----------------------------------------------------------------------===//
721// CallOp
722//===----------------------------------------------------------------------===//
723
724LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
725 // Check that the callee attribute was specified.
726 auto fnAttr = getCalleeAttr();
727 if (!fnAttr)
728 return emitOpError("requires a 'callee' symbol reference attribute");
729 FuncOp fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(*this, fnAttr);
730 if (!fn)
731 return emitOpError() << "'" << fnAttr.getValue()
732 << "' does not reference a valid function";
733
734 // Verify that the operand and result types match the callee.
736}
737
738FunctionType CallOp::getCalleeType() {
739 return FunctionType::get(getContext(), getOperandTypes(), getResultTypes());
740}
741
742//===----------------------------------------------------------------------===//
743// DeclareFuncOp
744//===----------------------------------------------------------------------===//
745
746LogicalResult
747DeclareFuncOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
748 // Check that the sym_name attribute was specified.
749 auto fnAttr = getSymNameAttr();
750 if (!fnAttr)
751 return emitOpError("requires a 'sym_name' symbol reference attribute");
752 FuncOp fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(*this, fnAttr);
753 if (!fn)
754 return emitOpError() << "'" << fnAttr.getValue()
755 << "' does not reference a valid function";
756
757 return success();
758}
759
760//===----------------------------------------------------------------------===//
761// FuncOp
762//===----------------------------------------------------------------------===//
763
764void FuncOp::build(OpBuilder &builder, OperationState &state, StringRef name,
765 FunctionType type, ArrayRef<NamedAttribute> attrs,
766 ArrayRef<DictionaryAttr> argAttrs) {
767 state.addAttribute(getSymNameAttrName(state.name),
768 builder.getStringAttr(name));
769 state.addAttribute(getFunctionTypeAttrName(state.name), TypeAttr::get(type));
770 state.attributes.append(attrs.begin(), attrs.end());
771 state.addRegion();
772
773 if (argAttrs.empty())
774 return;
775 assert(type.getNumInputs() == argAttrs.size());
777 builder, state, argAttrs, /*resultAttrs=*/{},
778 getArgAttrsAttrName(state.name), getResAttrsAttrName(state.name));
779}
780
781ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
782 auto buildFuncType =
783 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
785 std::string &) { return builder.getFunctionType(argTypes, results); };
786
788 parser, result, /*allowVariadic=*/false,
789 getFunctionTypeAttrName(result.name), buildFuncType,
790 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
791}
792
793void FuncOp::print(OpAsmPrinter &p) {
795 p, *this, /*isVariadic=*/false, getFunctionTypeAttrName(),
796 getArgAttrsAttrName(), getResAttrsAttrName());
797}
798
799LogicalResult FuncOp::verify() {
800 if (llvm::any_of(getArgumentTypes(), llvm::IsaPred<LValueType>)) {
801 return emitOpError("cannot have lvalue type as argument");
802 }
803
804 if (getNumResults() > 1)
805 return emitOpError("requires zero or exactly one result, but has ")
806 << getNumResults();
807
808 if (getNumResults() == 1 && isa<ArrayType>(getResultTypes()[0]))
809 return emitOpError("cannot return array type");
810
811 return success();
812}
813
814//===----------------------------------------------------------------------===//
815// ReturnOp
816//===----------------------------------------------------------------------===//
817
818LogicalResult ReturnOp::verify() {
819 auto function = cast<FuncOp>((*this)->getParentOp());
820
821 // The operand number and types must match the function signature.
822 if (getNumOperands() != function.getNumResults())
823 return emitOpError("has ")
824 << getNumOperands() << " operands, but enclosing function (@"
825 << function.getName() << ") returns " << function.getNumResults();
826
827 if (function.getNumResults() == 1)
828 if (getOperand().getType() != function.getResultTypes()[0])
829 return emitError() << "type of the return operand ("
830 << getOperand().getType()
831 << ") doesn't match function result type ("
832 << function.getResultTypes()[0] << ")"
833 << " in function @" << function.getName();
834 return success();
835}
836
837//===----------------------------------------------------------------------===//
838// IfOp
839//===----------------------------------------------------------------------===//
840
841void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
842 bool addThenBlock, bool addElseBlock) {
843 assert((!addElseBlock || addThenBlock) &&
844 "must not create else block w/o then block");
845 result.addOperands(cond);
846
847 // Add regions and blocks.
848 OpBuilder::InsertionGuard guard(builder);
849 Region *thenRegion = result.addRegion();
850 if (addThenBlock)
851 builder.createBlock(thenRegion);
852 Region *elseRegion = result.addRegion();
853 if (addElseBlock)
854 builder.createBlock(elseRegion);
855}
856
857void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
858 bool withElseRegion) {
859 result.addOperands(cond);
860
861 // Build then region.
862 OpBuilder::InsertionGuard guard(builder);
863 Region *thenRegion = result.addRegion();
864 builder.createBlock(thenRegion);
865
866 // Build else region.
867 Region *elseRegion = result.addRegion();
868 if (withElseRegion) {
869 builder.createBlock(elseRegion);
870 }
871}
872
873void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
874 function_ref<void(OpBuilder &, Location)> thenBuilder,
875 function_ref<void(OpBuilder &, Location)> elseBuilder) {
876 assert(thenBuilder && "the builder callback for 'then' must be present");
877 result.addOperands(cond);
878
879 // Build then region.
880 OpBuilder::InsertionGuard guard(builder);
881 Region *thenRegion = result.addRegion();
882 builder.createBlock(thenRegion);
883 thenBuilder(builder, result.location);
884
885 // Build else region.
886 Region *elseRegion = result.addRegion();
887 if (elseBuilder) {
888 builder.createBlock(elseRegion);
889 elseBuilder(builder, result.location);
890 }
891}
892
893ParseResult IfOp::parse(OpAsmParser &parser, OperationState &result) {
894 // Create the regions for 'then'.
895 result.regions.reserve(2);
896 Region *thenRegion = result.addRegion();
897 Region *elseRegion = result.addRegion();
898
899 Builder &builder = parser.getBuilder();
901 Type i1Type = builder.getIntegerType(1);
902 if (parser.parseOperand(cond) ||
903 parser.resolveOperand(cond, i1Type, result.operands))
904 return failure();
905 // Parse the 'then' region.
906 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
907 return failure();
908 IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location);
909
910 // If we find an 'else' keyword then parse the 'else' region.
911 if (!parser.parseOptionalKeyword("else")) {
912 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
913 return failure();
914 IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location);
915 }
916
917 // Parse the optional attribute list.
918 if (parser.parseOptionalAttrDict(result.attributes))
919 return failure();
920 return success();
921}
922
923void IfOp::print(OpAsmPrinter &p) {
924 bool printBlockTerminators = false;
925
926 p << " " << getCondition();
927 p << ' ';
928 p.printRegion(getThenRegion(),
929 /*printEntryBlockArgs=*/false,
930 /*printBlockTerminators=*/printBlockTerminators);
931
932 // Print the 'else' regions if it exists and has a block.
933 Region &elseRegion = getElseRegion();
934 if (!elseRegion.empty()) {
935 p << " else ";
936 p.printRegion(elseRegion,
937 /*printEntryBlockArgs=*/false,
938 /*printBlockTerminators=*/printBlockTerminators);
939 }
940
941 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
942}
943
944/// Given the region at `index`, or the parent operation if `index` is None,
945/// return the successor regions. These are the regions that may be selected
946/// during the flow of control. `operands` is a set of optional attributes
947/// that correspond to a constant value for each operand, or null if that
948/// operand is not a constant.
949void IfOp::getSuccessorRegions(RegionBranchPoint point,
951 // The `then` and the `else` region branch back to the parent operation.
952 if (!point.isParent()) {
953 regions.push_back(RegionSuccessor(getOperation()));
954 return;
955 }
956
957 regions.push_back(RegionSuccessor(&getThenRegion()));
958
959 // Don't consider the else region if it is empty.
960 Region *elseRegion = &this->getElseRegion();
961 if (elseRegion->empty())
962 regions.push_back(RegionSuccessor(getOperation()));
963 else
964 regions.push_back(RegionSuccessor(elseRegion));
965}
966
967ValueRange IfOp::getSuccessorInputs(RegionSuccessor successor) {
968 return successor.isOperation() ? ValueRange(getOperation()->getResults())
969 : ValueRange();
970}
971
972void IfOp::getEntrySuccessorRegions(ArrayRef<Attribute> operands,
974 FoldAdaptor adaptor(operands, *this);
975 auto boolAttr = dyn_cast_or_null<BoolAttr>(adaptor.getCondition());
976 if (!boolAttr || boolAttr.getValue())
977 regions.emplace_back(&getThenRegion());
978
979 // If the else region is empty, execution continues after the parent op.
980 if (!boolAttr || !boolAttr.getValue()) {
981 if (!getElseRegion().empty())
982 regions.emplace_back(&getElseRegion());
983 else
984 regions.emplace_back(RegionSuccessor(getOperation()));
985 }
986}
987
988void IfOp::getRegionInvocationBounds(
989 ArrayRef<Attribute> operands,
990 SmallVectorImpl<InvocationBounds> &invocationBounds) {
991 if (auto cond = llvm::dyn_cast_or_null<BoolAttr>(operands[0])) {
992 // If the condition is known, then one region is known to be executed once
993 // and the other zero times.
994 invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0);
995 invocationBounds.emplace_back(0, cond.getValue() ? 0 : 1);
996 } else {
997 // Non-constant condition. Each region may be executed 0 or 1 times.
998 invocationBounds.assign(2, {0, 1});
999 }
1000}
1001
1002//===----------------------------------------------------------------------===//
1003// IncludeOp
1004//===----------------------------------------------------------------------===//
1005
1006void IncludeOp::print(OpAsmPrinter &p) {
1007 bool standardInclude = getIsStandardInclude();
1008
1009 p << " ";
1010 if (standardInclude)
1011 p << "<";
1012 p << "\"" << getInclude() << "\"";
1013 if (standardInclude)
1014 p << ">";
1015}
1016
1017ParseResult IncludeOp::parse(OpAsmParser &parser, OperationState &result) {
1018 bool standardInclude = !parser.parseOptionalLess();
1019
1020 StringAttr include;
1021 OptionalParseResult includeParseResult =
1022 parser.parseOptionalAttribute(include, "include", result.attributes);
1023 if (!includeParseResult.has_value())
1024 return parser.emitError(parser.getNameLoc()) << "expected string attribute";
1025
1026 if (standardInclude && parser.parseOptionalGreater())
1027 return parser.emitError(parser.getNameLoc())
1028 << "expected trailing '>' for standard include";
1029
1030 if (standardInclude)
1031 result.addAttribute("is_standard_include",
1032 UnitAttr::get(parser.getContext()));
1033
1034 return success();
1035}
1036
1037//===----------------------------------------------------------------------===//
1038// LiteralOp
1039//===----------------------------------------------------------------------===//
1040
1041/// The literal op requires a non-empty value.
1042LogicalResult emitc::LiteralOp::verify() {
1043 if (getValue().empty())
1044 return emitOpError() << "value must not be empty";
1045 return success();
1046}
1047
1048//===----------------------------------------------------------------------===//
1049// MemberOp
1050//===----------------------------------------------------------------------===//
1051
1052LogicalResult MemberOp::verify() {
1053 Type operandType = getOperand().getType();
1054 Type resultType = getResult().getType();
1055 bool resultIsWritable = isa<emitc::LValueType, emitc::ArrayType>(resultType);
1056
1057 // Make sure the operand and return type agree on value/memory semantics:
1058 // If the operand is an lvalue it models a memory location and as such its
1059 // elements are also memory locations: They require a load operation to use
1060 // their value and they can be assigned new values.
1061 // If the operand isn't an lvalue it models an aggregate SSA value and as
1062 // such its elements are also SSA values: Their value can be used directly
1063 // but they cannot be assigned to.
1064
1065 if (isa<emitc::LValueType>(operandType) && !resultIsWritable)
1066 return emitOpError("lvalues must return lvalues or arrays");
1067
1068 if (!isa<emitc::LValueType>(operandType) && resultIsWritable)
1069 return emitOpError("non-lvalues cannot return lvalues or arrays");
1070
1071 return success();
1072}
1073
1074//===----------------------------------------------------------------------===//
1075// SubOp
1076//===----------------------------------------------------------------------===//
1077
1078LogicalResult SubOp::verify() {
1079 Type lhsType = getLhs().getType();
1080 Type rhsType = getRhs().getType();
1081 Type resultType = getResult().getType();
1082
1083 if (isa<emitc::PointerType>(rhsType) && !isa<emitc::PointerType>(lhsType))
1084 return emitOpError("rhs can only be a pointer if lhs is a pointer");
1085
1086 if (isa<emitc::PointerType>(lhsType) &&
1087 !isa<IntegerType, emitc::OpaqueType, emitc::PointerType>(rhsType))
1088 return emitOpError("requires that rhs is an integer, pointer or of opaque "
1089 "type if lhs is a pointer");
1090
1091 if (isa<emitc::PointerType>(lhsType) && isa<emitc::PointerType>(rhsType) &&
1092 !isa<IntegerType, emitc::PtrDiffTType, emitc::OpaqueType>(resultType))
1093 return emitOpError("requires that the result is an integer, ptrdiff_t or "
1094 "of opaque type if lhs and rhs are pointers");
1095 return success();
1096}
1097
1098//===----------------------------------------------------------------------===//
1099// VariableOp
1100//===----------------------------------------------------------------------===//
1101
1102LogicalResult emitc::VariableOp::verify() {
1103 return verifyInitializationAttribute(getOperation(), getValueAttr());
1104}
1105
1106//===----------------------------------------------------------------------===//
1107// YieldOp
1108//===----------------------------------------------------------------------===//
1109
1110LogicalResult emitc::YieldOp::verify() {
1111 Value result = getResult();
1112 Operation *containingOp = getOperation()->getParentOp();
1113
1114 if (!isa<DoOp>(containingOp) && result && containingOp->getNumResults() != 1)
1115 return emitOpError() << "yields a value not returned by parent";
1116
1117 if (!isa<DoOp>(containingOp) && !result && containingOp->getNumResults() != 0)
1118 return emitOpError() << "does not yield a value to be returned by parent";
1119
1120 if (result && isa<emitc::LValueType>(result.getType()) &&
1121 !isa<ExpressionOp>(containingOp))
1122 return emitOpError() << "yielding lvalues is not supported for this op";
1123
1124 return success();
1125}
1126
1127//===----------------------------------------------------------------------===//
1128// SubscriptOp
1129//===----------------------------------------------------------------------===//
1130
1131LogicalResult emitc::SubscriptOp::verify() {
1132 // Checks for array operand.
1133 if (auto arrayType = llvm::dyn_cast<emitc::ArrayType>(getValue().getType())) {
1134 // Check number of indices.
1135 if (getIndices().size() != (size_t)arrayType.getRank()) {
1136 return emitOpError() << "on array operand requires number of indices ("
1137 << getIndices().size()
1138 << ") to match the rank of the array type ("
1139 << arrayType.getRank() << ")";
1140 }
1141 // Check types of index operands.
1142 for (unsigned i = 0, e = getIndices().size(); i != e; ++i) {
1143 Type type = getIndices()[i].getType();
1144 if (!isIntegerIndexOrOpaqueType(type)) {
1145 return emitOpError() << "on array operand requires index operand " << i
1146 << " to be integer-like, but got " << type;
1147 }
1148 }
1149 // Check element type.
1150 Type elementType = arrayType.getElementType();
1151 Type resultType = getType().getValueType();
1152 if (elementType != resultType) {
1153 return emitOpError() << "on array operand requires element type ("
1154 << elementType << ") and result type (" << resultType
1155 << ") to match";
1156 }
1157 return success();
1158 }
1159
1160 // Checks for pointer operand.
1161 if (auto pointerType =
1162 llvm::dyn_cast<emitc::PointerType>(getValue().getType())) {
1163 // Check number of indices.
1164 if (getIndices().size() != 1) {
1165 return emitOpError()
1166 << "on pointer operand requires one index operand, but got "
1167 << getIndices().size();
1168 }
1169 // Check types of index operand.
1170 Type type = getIndices()[0].getType();
1171 if (!isIntegerIndexOrOpaqueType(type)) {
1172 return emitOpError() << "on pointer operand requires index operand to be "
1173 "integer-like, but got "
1174 << type;
1175 }
1176 // Check pointee type.
1177 Type pointeeType = pointerType.getPointee();
1178 Type resultType = getType().getValueType();
1179 if (pointeeType != resultType) {
1180 return emitOpError() << "on pointer operand requires pointee type ("
1181 << pointeeType << ") and result type (" << resultType
1182 << ") to match";
1183 }
1184 return success();
1185 }
1186
1187 // The operand has opaque type, so we can't assume anything about the number
1188 // or types of index operands.
1189 return success();
1190}
1191
1192//===----------------------------------------------------------------------===//
1193// VerbatimOp
1194//===----------------------------------------------------------------------===//
1195
1196LogicalResult emitc::VerbatimOp::verify() {
1197 auto errorCallback = [&]() -> InFlightDiagnostic {
1198 return this->emitOpError();
1199 };
1200 FailureOr<SmallVector<ReplacementItem>> fmt =
1201 ::parseFormatString(getValue(), getFmtArgs(), errorCallback);
1202 if (failed(fmt))
1203 return failure();
1204
1205 size_t numPlaceholders = llvm::count_if(*fmt, [](ReplacementItem &item) {
1206 return std::holds_alternative<Placeholder>(item);
1207 });
1208
1209 if (numPlaceholders != getFmtArgs().size()) {
1210 return emitOpError()
1211 << "requires operands for each placeholder in the format string";
1212 }
1213 return success();
1214}
1215
1216FailureOr<SmallVector<ReplacementItem>> emitc::VerbatimOp::parseFormatString() {
1217 // Error checking is done in verify.
1218 return ::parseFormatString(getValue(), getFmtArgs());
1219}
1220
1221//===----------------------------------------------------------------------===//
1222// EmitC Enums
1223//===----------------------------------------------------------------------===//
1224
1225#include "mlir/Dialect/EmitC/IR/EmitCEnums.cpp.inc"
1226
1227//===----------------------------------------------------------------------===//
1228// EmitC Attributes
1229//===----------------------------------------------------------------------===//
1230
1231#define GET_ATTRDEF_CLASSES
1232#include "mlir/Dialect/EmitC/IR/EmitCAttributes.cpp.inc"
1233
1234//===----------------------------------------------------------------------===//
1235// EmitC Types
1236//===----------------------------------------------------------------------===//
1237
1238#define GET_TYPEDEF_CLASSES
1239#include "mlir/Dialect/EmitC/IR/EmitCTypes.cpp.inc"
1240
1241//===----------------------------------------------------------------------===//
1242// ArrayType
1243//===----------------------------------------------------------------------===//
1244
1245Type emitc::ArrayType::parse(AsmParser &parser) {
1246 if (parser.parseLess())
1247 return Type();
1248
1249 SmallVector<int64_t, 4> dimensions;
1250 if (parser.parseDimensionList(dimensions, /*allowDynamic=*/false,
1251 /*withTrailingX=*/true))
1252 return Type();
1253 // Parse the element type.
1254 auto typeLoc = parser.getCurrentLocation();
1255 Type elementType;
1256 if (parser.parseType(elementType))
1257 return Type();
1258
1259 // Check that array is formed from allowed types.
1260 if (!isValidElementType(elementType))
1261 return parser.emitError(typeLoc, "invalid array element type '")
1262 << elementType << "'",
1263 Type();
1264 if (parser.parseGreater())
1265 return Type();
1266 return parser.getChecked<ArrayType>(dimensions, elementType);
1267}
1268
1269void emitc::ArrayType::print(AsmPrinter &printer) const {
1270 printer << "<";
1271 for (int64_t dim : getShape()) {
1272 printer << dim << 'x';
1273 }
1274 printer.printType(getElementType());
1275 printer << ">";
1276}
1277
1278LogicalResult emitc::ArrayType::verify(
1280 ::llvm::ArrayRef<int64_t> shape, Type elementType) {
1281 if (shape.empty())
1282 return emitError() << "shape must not be empty";
1283
1284 for (int64_t dim : shape) {
1285 if (dim < 0)
1286 return emitError() << "dimensions must have non-negative size";
1287 }
1288
1289 if (!elementType)
1290 return emitError() << "element type must not be none";
1291
1292 if (!isValidElementType(elementType))
1293 return emitError() << "invalid array element type";
1294
1295 return success();
1296}
1297
1298emitc::ArrayType
1299emitc::ArrayType::cloneWith(std::optional<ArrayRef<int64_t>> shape,
1300 Type elementType) const {
1301 if (!shape)
1302 return emitc::ArrayType::get(getShape(), elementType);
1303 return emitc::ArrayType::get(*shape, elementType);
1304}
1305
1306//===----------------------------------------------------------------------===//
1307// LValueType
1308//===----------------------------------------------------------------------===//
1309
1310LogicalResult mlir::emitc::LValueType::verify(
1312 mlir::Type value) {
1313 // Check that the wrapped type is valid. This especially forbids nested
1314 // lvalue types.
1315 if (!isSupportedEmitCType(value))
1316 return emitError()
1317 << "!emitc.lvalue must wrap supported emitc type, but got " << value;
1318
1319 if (llvm::isa<emitc::ArrayType>(value))
1320 return emitError() << "!emitc.lvalue cannot wrap !emitc.array type";
1321
1322 return success();
1323}
1324
1325//===----------------------------------------------------------------------===//
1326// OpaqueType
1327//===----------------------------------------------------------------------===//
1328
1329LogicalResult mlir::emitc::OpaqueType::verify(
1331 llvm::StringRef value) {
1332 if (value.empty()) {
1333 return emitError() << "expected non empty string in !emitc.opaque type";
1334 }
1335 if (value.back() == '*') {
1336 return emitError() << "pointer not allowed as outer type with "
1337 "!emitc.opaque, use !emitc.ptr instead";
1338 }
1339 return success();
1340}
1341
1342//===----------------------------------------------------------------------===//
1343// PointerType
1344//===----------------------------------------------------------------------===//
1345
1346LogicalResult mlir::emitc::PointerType::verify(
1348 if (llvm::isa<emitc::LValueType>(value))
1349 return emitError() << "pointers to lvalues are not allowed";
1350
1351 return success();
1352}
1353
1354//===----------------------------------------------------------------------===//
1355// GlobalOp
1356//===----------------------------------------------------------------------===//
1358 TypeAttr type,
1359 Attribute initialValue) {
1360 p << type;
1361 if (initialValue) {
1362 p << " = ";
1363 p.printAttributeWithoutType(initialValue);
1364 }
1365}
1366
1368 if (auto array = llvm::dyn_cast<ArrayType>(type))
1369 return RankedTensorType::get(array.getShape(), array.getElementType());
1370 return type;
1371}
1372
1373static ParseResult
1375 Attribute &initialValue) {
1376 Type type;
1377 if (parser.parseType(type))
1378 return failure();
1379
1380 typeAttr = TypeAttr::get(type);
1381
1382 if (parser.parseOptionalEqual())
1383 return success();
1384
1385 if (parser.parseAttribute(initialValue, getInitializerTypeForGlobal(type)))
1386 return failure();
1387
1388 if (!llvm::isa<ElementsAttr, IntegerAttr, FloatAttr, emitc::OpaqueAttr>(
1389 initialValue))
1390 return parser.emitError(parser.getNameLoc())
1391 << "initial value should be a integer, float, elements or opaque "
1392 "attribute";
1393 return success();
1394}
1395
1396LogicalResult GlobalOp::verify() {
1397 if (!isSupportedEmitCType(getType())) {
1398 return emitOpError("expected valid emitc type");
1399 }
1400 if (getInitialValue().has_value()) {
1401 Attribute initValue = getInitialValue().value();
1402 // Check that the type of the initial value is compatible with the type of
1403 // the global variable.
1404 if (auto elementsAttr = llvm::dyn_cast<ElementsAttr>(initValue)) {
1405 auto arrayType = llvm::dyn_cast<ArrayType>(getType());
1406 if (!arrayType)
1407 return emitOpError("expected array type, but got ") << getType();
1408
1409 Type initType = elementsAttr.getType();
1411 if (initType != tensorType) {
1412 return emitOpError("initial value expected to be of type ")
1413 << getType() << ", but was of type " << initType;
1414 }
1415 } else if (auto intAttr = dyn_cast<IntegerAttr>(initValue)) {
1416 if (intAttr.getType() != getType()) {
1417 return emitOpError("initial value expected to be of type ")
1418 << getType() << ", but was of type " << intAttr.getType();
1419 }
1420 } else if (auto floatAttr = dyn_cast<FloatAttr>(initValue)) {
1421 if (floatAttr.getType() != getType()) {
1422 return emitOpError("initial value expected to be of type ")
1423 << getType() << ", but was of type " << floatAttr.getType();
1424 }
1425 } else if (!isa<emitc::OpaqueAttr>(initValue)) {
1426 return emitOpError("initial value should be a integer, float, elements "
1427 "or opaque attribute, but got ")
1428 << initValue;
1429 }
1430 }
1431 if (getStaticSpecifier() && getExternSpecifier()) {
1432 return emitOpError("cannot have both static and extern specifiers");
1433 }
1434 return success();
1435}
1436
1437//===----------------------------------------------------------------------===//
1438// GetGlobalOp
1439//===----------------------------------------------------------------------===//
1440
1441LogicalResult
1442GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1443 // Verify that the type matches the type of the global variable.
1444 auto global =
1445 symbolTable.lookupNearestSymbolFrom<GlobalOp>(*this, getNameAttr());
1446 if (!global)
1447 return emitOpError("'")
1448 << getName() << "' does not reference a valid emitc.global";
1449
1450 Type resultType = getResult().getType();
1451 Type globalType = global.getType();
1452
1453 // global has array type
1454 if (llvm::isa<ArrayType>(globalType)) {
1455 if (globalType != resultType)
1456 return emitOpError("on array type expects result type ")
1457 << resultType << " to match type " << globalType
1458 << " of the global @" << getName();
1459 return success();
1460 }
1461
1462 // global has non-array type
1463 auto lvalueType = dyn_cast<LValueType>(resultType);
1464 if (!lvalueType)
1465 return emitOpError("on non-array type expects result type to be an "
1466 "lvalue type for the global @")
1467 << getName();
1468 if (lvalueType.getValueType() != globalType)
1469 return emitOpError("on non-array type expects result inner type ")
1470 << lvalueType.getValueType() << " to match type " << globalType
1471 << " of the global @" << getName();
1472 return success();
1473}
1474
1475//===----------------------------------------------------------------------===//
1476// SwitchOp
1477//===----------------------------------------------------------------------===//
1478
1479/// Parse the case regions and values.
1480static ParseResult
1482 SmallVectorImpl<std::unique_ptr<Region>> &caseRegions) {
1483 SmallVector<int64_t> caseValues;
1484 while (succeeded(parser.parseOptionalKeyword("case"))) {
1485 int64_t value;
1486 Region &region = *caseRegions.emplace_back(std::make_unique<Region>());
1487 if (parser.parseInteger(value) ||
1488 parser.parseRegion(region, /*arguments=*/{}))
1489 return failure();
1490 caseValues.push_back(value);
1491 }
1492 cases = parser.getBuilder().getDenseI64ArrayAttr(caseValues);
1493 return success();
1494}
1495
1496/// Print the case regions and values.
1498 DenseI64ArrayAttr cases, RegionRange caseRegions) {
1499 for (auto [value, region] : llvm::zip(cases.asArrayRef(), caseRegions)) {
1500 p.printNewline();
1501 p << "case " << value << ' ';
1502 p.printRegion(*region, /*printEntryBlockArgs=*/false);
1503 }
1504}
1505
1506static LogicalResult verifyRegion(emitc::SwitchOp op, Region &region,
1507 const Twine &name) {
1508 auto yield = dyn_cast<emitc::YieldOp>(region.front().back());
1509 if (!yield)
1510 return op.emitOpError("expected region to end with emitc.yield, but got ")
1511 << region.front().back().getName();
1512
1513 if (yield.getNumOperands() != 0) {
1514 return (op.emitOpError("expected each region to return ")
1515 << "0 values, but " << name << " returns "
1516 << yield.getNumOperands())
1517 .attachNote(yield.getLoc())
1518 << "see yield operation here";
1519 }
1520
1521 return success();
1522}
1523
1524LogicalResult emitc::SwitchOp::verify() {
1525 if (!isIntegerIndexOrOpaqueType(getArg().getType()))
1526 return emitOpError("unsupported type ") << getArg().getType();
1527
1528 if (getCases().size() != getCaseRegions().size()) {
1529 return emitOpError("has ")
1530 << getCaseRegions().size() << " case regions but "
1531 << getCases().size() << " case values";
1532 }
1533
1534 DenseSet<int64_t> valueSet;
1535 for (int64_t value : getCases())
1536 if (!valueSet.insert(value).second)
1537 return emitOpError("has duplicate case value: ") << value;
1538
1539 if (failed(verifyRegion(*this, getDefaultRegion(), "default region")))
1540 return failure();
1541
1542 for (auto [idx, caseRegion] : llvm::enumerate(getCaseRegions()))
1543 if (failed(verifyRegion(*this, caseRegion, "case region #" + Twine(idx))))
1544 return failure();
1545
1546 return success();
1547}
1548
1549unsigned emitc::SwitchOp::getNumCases() { return getCases().size(); }
1550
1551Block &emitc::SwitchOp::getDefaultBlock() { return getDefaultRegion().front(); }
1552
1553Block &emitc::SwitchOp::getCaseBlock(unsigned idx) {
1554 assert(idx < getNumCases() && "case index out-of-bounds");
1555 return getCaseRegions()[idx].front();
1556}
1557
1558void SwitchOp::getSuccessorRegions(
1560 llvm::append_range(successors, getRegions());
1561}
1562
1563/// Returns the int64_t value of an IntegerAttr regardless of whether its type
1564/// is signless, signed, or unsigned. Returns std::nullopt for unknown types.
1565static std::optional<int64_t> getIntAttrValue(IntegerAttr attr) {
1566 Type type = attr.getType();
1567 if (type.isIndex() || type.isSignlessInteger())
1568 return attr.getInt();
1569 if (type.isSignedInteger())
1570 return attr.getSInt();
1571 if (type.isUnsignedInteger())
1572 return static_cast<int64_t>(attr.getUInt());
1573 return std::nullopt;
1574}
1575
1576void SwitchOp::getEntrySuccessorRegions(
1577 ArrayRef<Attribute> operands,
1579 FoldAdaptor adaptor(operands, *this);
1580
1581 // If a constant was not provided, all regions are possible successors.
1582 auto arg = dyn_cast_or_null<IntegerAttr>(adaptor.getArg());
1583 if (!arg) {
1584 llvm::append_range(successors, getRegions());
1585 return;
1586 }
1587
1588 std::optional<int64_t> argValue = getIntAttrValue(arg);
1589 if (!argValue) {
1590 // Unknown type; conservatively treat all regions as possible.
1591 llvm::append_range(successors, getRegions());
1592 return;
1593 }
1594
1595 // Otherwise, try to find a case with a matching value. If not, the
1596 // default region is the only successor.
1597 for (auto [caseValue, caseRegion] : llvm::zip(getCases(), getCaseRegions())) {
1598 if (caseValue == *argValue) {
1599 successors.emplace_back(&caseRegion);
1600 return;
1601 }
1602 }
1603 successors.emplace_back(&getDefaultRegion());
1604}
1605
1606void SwitchOp::getRegionInvocationBounds(
1608 auto operandValue = llvm::dyn_cast_or_null<IntegerAttr>(operands.front());
1609 if (!operandValue) {
1610 // All regions are invoked at most once.
1611 bounds.append(getNumRegions(), InvocationBounds(/*lb=*/0, /*ub=*/1));
1612 return;
1613 }
1614
1615 std::optional<int64_t> maybeIntValue = getIntAttrValue(operandValue);
1616 if (!maybeIntValue) {
1617 // Unknown type; conservatively treat all regions as possible.
1618 bounds.append(getNumRegions(), InvocationBounds(/*lb=*/0, /*ub=*/1));
1619 return;
1620 }
1621
1622 unsigned liveIndex = getNumRegions() - 1;
1623 const auto *iteratorToInt = llvm::find(getCases(), *maybeIntValue);
1624
1625 liveIndex = iteratorToInt != getCases().end()
1626 ? std::distance(getCases().begin(), iteratorToInt)
1627 : liveIndex;
1628
1629 for (unsigned regIndex = 0, regNum = getNumRegions(); regIndex < regNum;
1630 ++regIndex)
1631 bounds.emplace_back(/*lb=*/0, /*ub=*/regIndex == liveIndex);
1632}
1633
1634//===----------------------------------------------------------------------===//
1635// FileOp
1636//===----------------------------------------------------------------------===//
1637void FileOp::build(OpBuilder &builder, OperationState &state, StringRef id) {
1638 state.addRegion()->emplaceBlock();
1639 state.attributes.push_back(
1640 builder.getNamedAttr("id", builder.getStringAttr(id)));
1641}
1642
1643//===----------------------------------------------------------------------===//
1644// FieldOp
1645//===----------------------------------------------------------------------===//
1646
1648 TypeAttr type,
1649 Attribute initialValue) {
1650 p << type;
1651 if (initialValue) {
1652 p << " = ";
1653 p.printAttributeWithoutType(initialValue);
1654 }
1655}
1656
1658 if (auto array = llvm::dyn_cast<ArrayType>(type))
1659 return RankedTensorType::get(array.getShape(), array.getElementType());
1660 return type;
1661}
1662
1663static ParseResult
1665 Attribute &initialValue) {
1666 Type type;
1667 if (parser.parseType(type))
1668 return failure();
1669
1670 typeAttr = TypeAttr::get(type);
1671
1672 if (parser.parseOptionalEqual())
1673 return success();
1674
1675 if (parser.parseAttribute(initialValue, getInitializerTypeForField(type)))
1676 return failure();
1677
1678 if (!llvm::isa<ElementsAttr, IntegerAttr, FloatAttr, emitc::OpaqueAttr>(
1679 initialValue))
1680 return parser.emitError(parser.getNameLoc())
1681 << "initial value should be a integer, float, elements or opaque "
1682 "attribute";
1683 return success();
1684}
1685
1686LogicalResult FieldOp::verify() {
1688 return emitOpError("expected valid emitc type");
1689
1690 Operation *parentOp = getOperation()->getParentOp();
1691 if (!parentOp || !isa<emitc::ClassOp>(parentOp))
1692 return emitOpError("field must be nested within an emitc.class operation");
1693
1694 StringAttr symName = getSymNameAttr();
1695 if (!symName || symName.getValue().empty())
1696 return emitOpError("field must have a non-empty symbol name");
1697
1698 return success();
1699}
1700
1701//===----------------------------------------------------------------------===//
1702// GetFieldOp
1703//===----------------------------------------------------------------------===//
1704
1705LogicalResult GetFieldOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1706 mlir::FlatSymbolRefAttr fieldNameAttr = getFieldNameAttr();
1707 FieldOp fieldOp =
1708 symbolTable.lookupNearestSymbolFrom<FieldOp>(*this, fieldNameAttr);
1709 if (!fieldOp)
1710 return emitOpError("field '")
1711 << fieldNameAttr << "' not found in the class";
1712
1713 Type getFieldResultType = getResult().getType();
1714 Type fieldType = fieldOp.getType();
1715
1716 if (fieldType != getFieldResultType)
1717 return emitOpError("result type ")
1718 << getFieldResultType << " does not match field '" << fieldNameAttr
1719 << "' type " << fieldType;
1720
1721 return success();
1722}
1723
1724//===----------------------------------------------------------------------===//
1725// DoOp
1726//===----------------------------------------------------------------------===//
1727
1728void DoOp::print(OpAsmPrinter &p) {
1729 p << ' ';
1730 p.printRegion(getBodyRegion(), /*printEntryBlockArgs=*/false);
1731 p << " while ";
1732 p.printRegion(getConditionRegion());
1734 getOperation()->getDiscardableAttrDictionary().getValue());
1735}
1736
1737LogicalResult emitc::DoOp::verify() {
1738 Block &condBlock = getConditionRegion().front();
1739
1740 if (condBlock.getOperations().size() != 2)
1741 return emitOpError(
1742 "condition region must contain exactly two operations: "
1743 "'emitc.expression' followed by 'emitc.yield', but found ")
1744 << condBlock.getOperations().size() << " operations";
1745
1746 Operation &first = condBlock.front();
1747 auto exprOp = dyn_cast<emitc::ExpressionOp>(first);
1748 if (!exprOp)
1749 return emitOpError("expected first op in condition region to be "
1750 "'emitc.expression', but got ")
1751 << first.getName();
1752
1753 if (!exprOp.getResult().getType().isInteger(1))
1754 return emitOpError("emitc.expression in condition region must return "
1755 "'i1', but returns ")
1756 << exprOp.getResult().getType();
1757
1758 Operation &last = condBlock.back();
1759 auto condYield = dyn_cast<emitc::YieldOp>(last);
1760 if (!condYield)
1761 return emitOpError("expected last op in condition region to be "
1762 "'emitc.yield', but got ")
1763 << last.getName();
1764
1765 if (condYield.getNumOperands() != 1)
1766 return emitOpError("expected condition region to return 1 value, but "
1767 "it returns ")
1768 << condYield.getNumOperands() << " values";
1769
1770 if (condYield.getOperand(0) != exprOp.getResult())
1771 return emitError("'emitc.yield' must return result of "
1772 "'emitc.expression' from this condition region");
1773
1774 Block &bodyBlock = getBodyRegion().front();
1775 if (bodyBlock.mightHaveTerminator())
1776 return emitOpError("body region must not contain terminator");
1777
1778 return success();
1779}
1780
1781ParseResult DoOp::parse(OpAsmParser &parser, OperationState &result) {
1782 Region *bodyRegion = result.addRegion();
1783 Region *condRegion = result.addRegion();
1784
1785 if (parser.parseRegion(*bodyRegion) || parser.parseKeyword("while") ||
1786 parser.parseRegion(*condRegion))
1787 return failure();
1788
1789 if (bodyRegion->empty())
1790 bodyRegion->emplaceBlock();
1791
1792 return parser.parseOptionalAttrDictWithKeyword(result.attributes);
1793}
1794
1795//===----------------------------------------------------------------------===//
1796// TableGen'd op method definitions
1797//===----------------------------------------------------------------------===//
1798
1799#include "mlir/Dialect/EmitC/IR/EmitCInterfaces.cpp.inc"
1800
1801#define GET_OP_CLASSES
1802#include "mlir/Dialect/EmitC/IR/EmitC.cpp.inc"
static Value getPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
return success()
static std::optional< int64_t > getUpperBound(Value iv)
Gets the constant upper bound on an affine.for iv.
static std::optional< int64_t > getLowerBound(Value iv)
Gets the constant lower bound on an iv.
static std::optional< int64_t > getIntAttrValue(IntegerAttr attr)
Returns the int64_t value of an IntegerAttr regardless of whether its type is signless,...
Definition EmitC.cpp:1565
static LogicalResult verifyInitializationAttribute(Operation *op, Attribute value)
Check that the type of the initial value is compatible with the operations result type.
Definition EmitC.cpp:128
static LogicalResult verifyRegion(emitc::SwitchOp op, Region &region, const Twine &name)
Definition EmitC.cpp:1506
static ParseResult parseEmitCGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValue)
Definition EmitC.cpp:1374
static Type getInitializerTypeForField(Type type)
Definition EmitC.cpp:1657
static ParseResult parseEmitCFieldOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValue)
Definition EmitC.cpp:1664
FailureOr< SmallVector< ReplacementItem > > parseFormatString(StringRef toParse, ArgType fmtArgs, llvm::function_ref< mlir::InFlightDiagnostic()> emitError={})
Parse a format string and return a list of its parts.
Definition EmitC.cpp:163
static void printEmitCGlobalOpTypeAndInitialValue(OpAsmPrinter &p, GlobalOp op, TypeAttr type, Attribute initialValue)
Definition EmitC.cpp:1357
static LogicalResult verifyAssignmentOp(AssignmentOp op)
Definition EmitC.cpp:253
static ParseResult parseSwitchCases(OpAsmParser &parser, DenseI64ArrayAttr &cases, SmallVectorImpl< std::unique_ptr< Region > > &caseRegions)
Parse the case regions and values.
Definition EmitC.cpp:1481
static LogicalResult verifyOpaqueCallCommon(Operation *op, StringRef callee, std::optional< ArrayAttr > args, std::optional< ArrayAttr > templateArgs, TypeRange resultTypes, size_t numArgsOperands)
Definition EmitC.cpp:321
static void printEmitCFieldOpTypeAndInitialValue(OpAsmPrinter &p, FieldOp op, TypeAttr type, Attribute initialValue)
Definition EmitC.cpp:1647
static void printSwitchCases(OpAsmPrinter &p, Operation *op, DenseI64ArrayAttr cases, RegionRange caseRegions)
Print the case regions and values.
Definition EmitC.cpp:1497
static Type getInitializerTypeForGlobal(Type type)
Definition EmitC.cpp:1367
b getContext())
static Type getValueType(Attribute attr)
Definition SPIRVOps.cpp:846
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseOptionalGreater()=0
Parse a '>' token if present.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual OptionalParseResult parseOptionalAttribute(Attribute &result, Type type={})=0
Parse an arbitrary optional attribute of a given type and return it in result.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
virtual void printType(Type type)
virtual void printNewline()
Print a newline and indent the printer to the start of the current operation/attribute/type.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument getArgument(unsigned i)
Definition Block.h:154
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
Operation & back()
Definition Block.h:177
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
Definition Block.cpp:255
BlockArgListType getArguments()
Definition Block.h:112
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Definition Block.h:222
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
UnitAttr getUnitAttr()
Definition Builders.cpp:106
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:175
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
IndexType getIndexType()
Definition Builders.cpp:59
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition Builders.cpp:102
A symbol reference with a reference path containing a single element.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
This class represents a diagnostic that is inflight and set to be reported.
This class represents upper and lower bounds on the number of times a region of a RegionBranchOpInter...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void push_back(NamedAttribute newAttribute)
Add an attribute with the specified name.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void shadowRegionArgs(Region &region, ValueRange namesToUse)=0
Renumber the arguments for the specified region to the same names as the SSA values in namesToUse.
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
void printOperands(OperandRange operands)
Print a comma separated range of operation operands out of line to avoid instantiating the range iter...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
This class represents a single result from folding an operation.
type_range getType() const
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class provides an abstraction over the different types of ranges over Regions.
Definition Region.h:363
This class represents a successor of a region.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
Block & emplaceBlock()
Definition Region.h:46
bool empty()
Definition Region.h:60
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
Definition Types.cpp:78
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isIndex() const
Definition Types.cpp:56
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition Types.cpp:90
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
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:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A named class for passing around the variadic flag.
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
LogicalResult verifyCallOpInterface(CallOpInterface call, TypeRange argumentTypes, TypeRange resultTypes)
Verify that the forwarded operands and results of call are in a 1:1 relationship with the given argum...
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
void buildTerminatedBody(OpBuilder &builder, Location loc)
Default callback for builders of ops carrying a region.
Definition EmitC.cpp:41
std::variant< StringRef, Placeholder > ReplacementItem
Definition EmitC.h:48
bool isFundamentalType(mlir::Type type)
Determines whether type is a valid fundamental C++ type in EmitC.
Definition EmitC.cpp:120
bool isSupportedFloatType(mlir::Type type)
Determines whether type is a valid floating-point type in EmitC.
Definition EmitC.cpp:100
bool isSupportedEmitCType(mlir::Type type)
Determines whether type is valid in EmitC.
Definition EmitC.cpp:45
bool isPointerWideType(mlir::Type type)
Determines whether type is a emitc.size_t/ssize_t type.
Definition EmitC.cpp:115
bool isIntegerIndexOrOpaqueType(Type type)
Determines whether type is integer like, i.e.
Definition EmitC.cpp:95
bool isSupportedIntegerType(mlir::Type type)
Determines whether type is a valid integer type in EmitC.
Definition EmitC.cpp:79
void printFunctionOp(OpAsmPrinter &p, FunctionOpInterface op, bool isVariadic, StringRef typeAttrName, StringAttr argAttrsName, StringAttr resAttrsName)
Printer implementation for function-like operations.
ParseResult parseFunctionOp(OpAsmParser &parser, OperationState &result, bool allowVariadic, StringAttr typeAttrName, FuncTypeBuilder funcTypeBuilder, StringAttr argAttrsName, StringAttr resAttrsName)
Parser implementation for function-like operations.
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition Utils.cpp:18
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
Region * addRegion()
Create a region that should be attached to the operation.