MLIR 24.0.0git
LLVMModuleOps.cpp
Go to the documentation of this file.
1//===- LLVMModuleOps.cpp - LLVM dialect module-level ops ------------------===//
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// This file defines the ops of op partition `Module` of the LLVM dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "IR/LLVMOps.h"
20#include "mlir/IR/Builders.h"
21#include "mlir/IR/BuiltinOps.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/TypeSwitch.h"
27
28#include <optional>
29
30using namespace mlir;
31using namespace mlir::LLVM;
32
36 op, [&](StringRef name, Attribute &attr) { attrs.set(name, attr); });
37 return attrs;
38}
39
40// TODO: Split inherent attributes from discardable attributes in the assembly
41// syntax of GlobalOp and AliasOp. For now, print the selected inherent
42// attributes in the regular attribute dictionary.
45 ArrayRef<StringAttr> inherentAttrNames) {
47 for (StringAttr name : inherentAttrNames)
48 if (std::optional<Attribute> attr = op->getInherentAttr(name);
49 attr && *attr)
50 attrs.set(name, *attr);
51 return attrs;
52}
53
54/// Verifies `symbol`'s use in `op` to ensure the symbol is a valid and
55/// fully defined llvm.func.
56static LogicalResult verifySymbolAttrUse(FlatSymbolRefAttr symbol,
57 Operation *op,
58 SymbolTableCollection &symbolTable) {
59 StringRef name = symbol.getValue();
60 auto func =
61 symbolTable.lookupNearestSymbolFrom<LLVMFuncOp>(op, symbol.getAttr());
62 if (!func)
63 return op->emitOpError("'")
64 << name << "' does not reference a valid LLVM function";
65 if (func.isExternal())
66 return op->emitOpError("'") << name << "' does not have a definition";
67 return success();
68}
69
70// Parses one of the keywords provided in the list `keywords` and returns the
71// position of the parsed keyword in the list. If none of the keywords from the
72// list is parsed, returns -1.
74 ArrayRef<StringRef> keywords) {
75 for (const auto &en : llvm::enumerate(keywords)) {
76 if (succeeded(parser.parseOptionalKeyword(en.value())))
77 return en.index();
78 }
79 return -1;
80}
81
83 LinkageAttr val) {
84 p << stringifyLinkage(val.getLinkage());
85}
86
87ParseResult mlir::LLVM::parseLLVMLinkage(OpAsmParser &p, LinkageAttr &val) {
88 val = LinkageAttr::get(
89 p.getContext(),
90 parseOptionalLLVMKeyword<LLVM::Linkage>(p, LLVM::Linkage::External));
91 return success();
92}
93
94//===----------------------------------------------------------------------===//
95// Verifier for LLVM::ComdatOp.
96//===----------------------------------------------------------------------===//
97
98void ComdatOp::build(OpBuilder &builder, OperationState &result,
99 StringRef symName) {
100 result.addAttribute(getSymNameAttrName(result.name),
101 builder.getStringAttr(symName));
102 Region *body = result.addRegion();
103 body->emplaceBlock();
104}
105
106LogicalResult ComdatOp::verifyRegions() {
107 Region &body = getBody();
108 for (Operation &op : body.getOps())
109 if (!isa<ComdatSelectorOp>(op))
110 return op.emitError(
111 "only comdat selector symbols can appear in a comdat region");
112
113 return success();
114}
115
116//===----------------------------------------------------------------------===//
117// Builder, printer and verifier for LLVM::GlobalOp.
118//===----------------------------------------------------------------------===//
119
120void GlobalOp::build(OpBuilder &builder, OperationState &result, Type type,
121 bool isConstant, Linkage linkage, StringRef name,
122 Attribute value, uint64_t alignment, unsigned addrSpace,
123 bool dsoLocal, ThreadLocalMode threadModel,
124 SymbolRefAttr comdat, ArrayRef<NamedAttribute> attrs,
125 ArrayRef<Attribute> dbgExprs) {
126 result.getOrAddProperties<Properties>().sym_name =
127 builder.getStringAttr(name);
128 result.addAttribute(getGlobalTypeAttrName(result.name), TypeAttr::get(type));
129 result.addAttribute(
130 getTlsModeAttrName(result.name),
131 ThreadLocalModeAttr::get(builder.getContext(), threadModel));
132 if (isConstant)
133 result.addAttribute(getConstantAttrName(result.name),
134 builder.getUnitAttr());
135 if (value)
136 result.addAttribute(getValueAttrName(result.name), value);
137 if (dsoLocal)
138 result.addAttribute(getDsoLocalAttrName(result.name),
139 builder.getUnitAttr());
140 if (comdat)
141 result.addAttribute(getComdatAttrName(result.name), comdat);
142
143 // Only add an alignment attribute if the "alignment" input
144 // is different from 0. The value must also be a power of two, but
145 // this is tested in GlobalOp::verify, not here.
146 if (alignment != 0)
147 result.addAttribute(getAlignmentAttrName(result.name),
148 builder.getI64IntegerAttr(alignment));
149
150 result.addAttribute(getLinkageAttrName(result.name),
151 LinkageAttr::get(builder.getContext(), linkage));
152 if (addrSpace != 0)
153 result.addAttribute(getAddrSpaceAttrName(result.name),
154 builder.getI32IntegerAttr(addrSpace));
155 result.attributes.append(attrs.begin(), attrs.end());
156
157 if (!dbgExprs.empty())
158 result.addAttribute(getDbgExprsAttrName(result.name),
159 ArrayAttr::get(builder.getContext(), dbgExprs));
160
161 result.addRegion();
162}
163
164template <typename OpType>
165static void printCommonGlobalAndAlias(OpAsmPrinter &p, OpType op) {
166 p << ' ' << stringifyLinkage(op.getLinkage()) << ' ';
167 StringRef visibility = stringifyVisibility(op.getVisibility_());
168 if (!visibility.empty())
169 p << visibility << ' ';
170
171 if (ThreadLocalMode mode = op.getTlsMode();
172 mode != ThreadLocalMode::NotThreadLocal) {
173 p << "thread_local";
174 if (mode != ThreadLocalMode::GeneralDynamic)
175 p << '(' << mode << ')';
176 p << ' ';
177 }
178
179 if (auto unnamedAddr = op.getUnnamedAddr()) {
180 StringRef str = stringifyUnnamedAddr(*unnamedAddr);
181 if (!str.empty())
182 p << str << ' ';
183 }
184}
185
186void GlobalOp::print(OpAsmPrinter &p) {
188 if (getConstant())
189 p << "constant ";
190 p.printSymbolName(getSymName());
191 p << '(';
192 if (auto value = getValueOrNull())
193 p.printAttribute(value);
194 p << ')';
195 if (auto comdat = getComdat())
196 p << " comdat(" << *comdat << ')';
197
198 // Note that the alignment attribute is printed using the
199 // default syntax here, even though it is an inherent attribute
200 // (as defined in https://mlir.llvm.org/docs/LangRef/#attributes)
203 *this, {getDsoLocalAttrName(), getExternallyInitializedAttrName(),
204 getAlignmentAttrName(), getAddrSpaceAttrName(),
205 getSectionAttrName(), getAssociatedAttrName(),
206 getAbsoluteSymbolAttrName(), getDbgExprsAttrName(),
207 getTargetSpecificAttrsAttrName(), getSymVisibilityAttrName()})
208 .getAttrs(),
209 {getSymNameAttrName(), getGlobalTypeAttrName(), getConstantAttrName(),
210 getValueAttrName(), getLinkageAttrName(), getUnnamedAddrAttrName(),
211 getTlsModeAttrName(), getVisibility_AttrName(), getComdatAttrName()});
212
213 // Print the trailing type unless it's a string global.
214 if (llvm::dyn_cast_or_null<StringAttr>(getValueOrNull()))
215 return;
216 p << " : " << getType();
217
218 Region &initializer = getInitializerRegion();
219 if (!initializer.empty()) {
220 p << ' ';
221 p.printRegion(initializer, /*printEntryBlockArgs=*/false);
222 }
223}
224
225static LogicalResult verifyComdat(Operation *op,
226 std::optional<SymbolRefAttr> attr,
227 SymbolTableCollection &symbolTable) {
228 if (!attr)
229 return success();
230
231 auto *comdatSelector = symbolTable.lookupNearestSymbolFrom(op, *attr);
232 if (!isa_and_nonnull<ComdatSelectorOp>(comdatSelector))
233 return op->emitError() << "expected comdat symbol";
234
235 return success();
236}
237
238static LogicalResult verifyBlockTags(LLVMFuncOp funcOp) {
240 // Note that presence of `BlockTagOp`s currently can't prevent an unrecheable
241 // block to be removed by canonicalizer's region simplify pass, which needs to
242 // be dialect aware to allow extra constraints to be described.
243 WalkResult res = funcOp.walk([&](BlockTagOp blockTagOp) {
244 if (blockTags.contains(blockTagOp.getTag())) {
245 blockTagOp.emitError()
246 << "duplicate block tag '" << blockTagOp.getTag().getId()
247 << "' in the same function: ";
248 return WalkResult::interrupt();
249 }
250 blockTags.insert(blockTagOp.getTag());
251 return WalkResult::advance();
252 });
253
254 return failure(res.wasInterrupted());
255}
256
257/// Parse common attributes that might show up in the same order in both
258/// GlobalOp and AliasOp.
259template <typename OpType>
260static ParseResult parseCommonGlobalAndAlias(OpAsmParser &parser,
262 MLIRContext *ctx = parser.getContext();
263
264 // Parse optional linkage, default to External.
265 result.addAttribute(
266 OpType::getLinkageAttrName(result.name),
267 LLVM::LinkageAttr::get(ctx, parseOptionalLLVMKeyword<Linkage>(
268 parser, LLVM::Linkage::External)));
269
270 // Parse optional visibility, default to Default.
271 result.addAttribute(OpType::getVisibility_AttrName(result.name),
274 parser, LLVM::Visibility::Default)));
275
276 if (succeeded(parser.parseOptionalKeyword("thread_local"))) {
277 ThreadLocalMode threadModel = ThreadLocalMode::GeneralDynamic;
278
279 if (succeeded(parser.parseOptionalLParen())) {
280 SMLoc kwLoc;
281 if (parser.getCurrentLocation(&kwLoc))
282 return failure();
284 parser, ThreadLocalMode::NotThreadLocal);
285 if (threadModel == ThreadLocalMode::NotThreadLocal) {
286 parser.emitError(kwLoc, "invalid value for thread_local");
287 return failure();
288 }
289 if (parser.parseRParen())
290 return failure();
291 }
292 result.addAttribute(OpType::getTlsModeAttrName(result.name),
293 ThreadLocalModeAttr::get(ctx, threadModel));
294 }
295
296 // Parse optional UnnamedAddr, default to None.
297 result.addAttribute(OpType::getUnnamedAddrAttrName(result.name),
300 parser, LLVM::UnnamedAddr::None)));
301
302 return success();
303}
304
305// operation ::= `llvm.mlir.global` linkage? visibility?
306// (`unnamed_addr` | `local_unnamed_addr`)?
307// (`thread_local` (`(` tls-mode `)`)? )?
308// `constant`? `@` identifier
309// `(` attribute? `)` (`comdat(` symbol-ref-id `)`)?
310// attribute-list? (`:` type)? region?
311//
312// The type can be omitted for string attributes, in which case it will be
313// inferred from the value of the string as [strlen(value) x i8].
314ParseResult GlobalOp::parse(OpAsmParser &parser, OperationState &result) {
315 // Call into common parsing between GlobalOp and AliasOp.
317 return failure();
318
319 if (succeeded(parser.parseOptionalKeyword("constant")))
320 result.addAttribute(getConstantAttrName(result.name),
321 parser.getBuilder().getUnitAttr());
322
323 StringAttr name;
324 if (parser.parseSymbolName(name, getSymNameAttrName(result.name),
325 result.attributes) ||
326 parser.parseLParen())
327 return failure();
328
329 Attribute value;
330 if (parser.parseOptionalRParen()) {
331 if (parser.parseAttribute(value, getValueAttrName(result.name),
332 result.attributes) ||
333 parser.parseRParen())
334 return failure();
335 }
336
337 if (succeeded(parser.parseOptionalKeyword("comdat"))) {
338 SymbolRefAttr comdat;
339 if (parser.parseLParen() || parser.parseAttribute(comdat) ||
340 parser.parseRParen())
341 return failure();
342
343 result.addAttribute(getComdatAttrName(result.name), comdat);
344 }
345
347 if (parser.parseOptionalAttrDict(result.attributes) ||
348 parser.parseOptionalColonTypeList(types))
349 return failure();
350
351 if (types.size() > 1)
352 return parser.emitError(parser.getNameLoc(), "expected zero or one type");
353
354 Region &initRegion = *result.addRegion();
355 if (types.empty()) {
356 if (auto strAttr = llvm::dyn_cast_or_null<StringAttr>(value)) {
357 MLIRContext *context = parser.getContext();
358 auto arrayType = LLVM::LLVMArrayType::get(IntegerType::get(context, 8),
359 strAttr.getValue().size());
360 types.push_back(arrayType);
361 } else {
362 return parser.emitError(parser.getNameLoc(),
363 "type can only be omitted for string globals");
364 }
365 } else {
366 OptionalParseResult parseResult =
367 parser.parseOptionalRegion(initRegion, /*arguments=*/{},
368 /*argTypes=*/{});
369 if (parseResult.has_value() && failed(*parseResult))
370 return failure();
371 }
372
373 result.addAttribute(getGlobalTypeAttrName(result.name),
374 TypeAttr::get(types[0]));
375 return success();
376}
377
378static bool isZeroAttribute(Attribute value) {
379 if (auto intValue = llvm::dyn_cast<IntegerAttr>(value))
380 return intValue.getValue().isZero();
381 if (auto fpValue = llvm::dyn_cast<FloatAttr>(value))
382 return fpValue.getValue().isZero();
383 if (auto splatValue = llvm::dyn_cast<SplatElementsAttr>(value))
384 return isZeroAttribute(splatValue.getSplatValue<Attribute>());
385 if (auto elementsValue = llvm::dyn_cast<ElementsAttr>(value))
386 return llvm::all_of(elementsValue.getValues<Attribute>(), isZeroAttribute);
387 if (auto arrayValue = llvm::dyn_cast<ArrayAttr>(value))
388 return llvm::all_of(arrayValue.getValue(), isZeroAttribute);
389 return false;
390}
391
392LogicalResult GlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
393 return verifyComdat(*this, getComdat(), symbolTable);
394}
395
396LogicalResult GlobalOp::verify() {
397 bool validType = isCompatibleOuterType(getType())
398 ? !llvm::isa<LLVMVoidType, TokenType, LLVMMetadataType,
399 LLVMLabelType>(getType())
400 : llvm::isa<PointerElementTypeInterface>(getType());
401 if (!validType)
402 return emitOpError(
403 "expects type to be a valid element type for an LLVM global");
404 if ((*this)->getParentOp() && !satisfiesLLVMModule((*this)->getParentOp()))
405 return emitOpError("must appear at the module level");
406
407 if (auto strAttr = llvm::dyn_cast_or_null<StringAttr>(getValueOrNull())) {
408 auto type = llvm::dyn_cast<LLVMArrayType>(getType());
409 IntegerType elementType =
410 type ? llvm::dyn_cast<IntegerType>(type.getElementType()) : nullptr;
411 if (!elementType || elementType.getWidth() != 8 ||
412 type.getNumElements() != strAttr.getValue().size())
413 return emitOpError(
414 "requires an i8 array type of the length equal to that of the string "
415 "attribute");
416 }
417
418 if (auto targetExtType = dyn_cast<LLVMTargetExtType>(getType())) {
419 if (!targetExtType.hasProperty(LLVMTargetExtType::CanBeGlobal))
420 return emitOpError()
421 << "this target extension type cannot be used in a global";
422
423 if (Attribute value = getValueOrNull())
424 return emitOpError() << "global with target extension type can only be "
425 "initialized with zero-initializer";
426 }
427
428 if (getLinkage() == Linkage::Common) {
429 if (Attribute value = getValueOrNull()) {
430 if (!isZeroAttribute(value)) {
431 return emitOpError()
432 << "expected zero value for '"
433 << stringifyLinkage(Linkage::Common) << "' linkage";
434 }
435 }
436 }
437
438 if (getLinkage() == Linkage::Appending) {
439 if (!llvm::isa<LLVMArrayType>(getType())) {
440 return emitOpError() << "expected array type for '"
441 << stringifyLinkage(Linkage::Appending)
442 << "' linkage";
443 }
444 }
445
446 std::optional<uint64_t> alignAttr = getAlignment();
447 if (alignAttr.has_value()) {
448 uint64_t value = alignAttr.value();
449 if (!llvm::isPowerOf2_64(value))
450 return emitError() << "alignment attribute is not a power of 2";
451 }
452
453 if (FlatSymbolRefAttr associated = getAssociatedAttr()) {
454 if (associated.getValue() == getSymName())
455 return emitOpError("associated cannot refer to the global itself");
456 }
457
458 if (ArrayAttr absSym = getAbsoluteSymbolAttr()) {
459 if (absSym.empty() || absSym.size() % 2 != 0)
460 return emitOpError(
461 "absolute_symbol must contain one or more integer range pairs");
462 Type pairType;
463 for (Attribute attr : absSym) {
464 auto intAttr = dyn_cast<IntegerAttr>(attr);
465 if (!intAttr)
466 return emitOpError("absolute_symbol operands must be integers");
467 if (!pairType)
468 pairType = intAttr.getType();
469 else if (intAttr.getType() != pairType)
470 return emitOpError("absolute_symbol range pair types must match");
471 }
472 }
473
474 return success();
475}
476
477LogicalResult GlobalOp::verifyRegions() {
478 if (Block *b = getInitializerBlock()) {
479 ReturnOp ret = cast<ReturnOp>(b->getTerminator());
480 if (ret.operand_type_begin() == ret.operand_type_end())
481 return emitOpError("initializer region cannot return void");
482 if (*ret.operand_type_begin() != getType())
483 return emitOpError("initializer region type ")
484 << *ret.operand_type_begin() << " does not match global type "
485 << getType();
486
487 for (Operation &op : *b) {
488 auto iface = dyn_cast<MemoryEffectOpInterface>(op);
489 if (!iface || !iface.hasNoEffect())
490 return op.emitError()
491 << "ops with side effects not allowed in global initializers";
492 }
493
494 if (getValueOrNull())
495 return emitOpError("cannot have both initializer value and region");
496 }
497
498 return success();
499}
500
501//===----------------------------------------------------------------------===//
502// LLVM::GlobalCtorsOp
503//===----------------------------------------------------------------------===//
504
505static LogicalResult checkGlobalXtorData(Operation *op, ArrayAttr data) {
506 if (data.empty())
507 return success();
508
509 if (llvm::all_of(data.getAsRange<Attribute>(), [](Attribute v) {
510 return isa<FlatSymbolRefAttr, ZeroAttr>(v);
511 }))
512 return success();
513 return op->emitError("data element must be symbol or #llvm.zero");
514}
515
516LogicalResult
517GlobalCtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
518 for (Attribute ctor : getCtors()) {
519 if (failed(verifySymbolAttrUse(llvm::cast<FlatSymbolRefAttr>(ctor), *this,
520 symbolTable)))
521 return failure();
522 }
523 return success();
524}
525
526LogicalResult GlobalCtorsOp::verify() {
527 if (checkGlobalXtorData(*this, getData()).failed())
528 return failure();
529
530 if (getCtors().size() == getPriorities().size() &&
531 getCtors().size() == getData().size())
532 return success();
533 return emitError(
534 "ctors, priorities, and data must have the same number of elements");
535}
536
537//===----------------------------------------------------------------------===//
538// LLVM::GlobalDtorsOp
539//===----------------------------------------------------------------------===//
540
541LogicalResult
542GlobalDtorsOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
543 for (Attribute dtor : getDtors()) {
544 if (failed(verifySymbolAttrUse(llvm::cast<FlatSymbolRefAttr>(dtor), *this,
545 symbolTable)))
546 return failure();
547 }
548 return success();
549}
550
551LogicalResult GlobalDtorsOp::verify() {
552 if (checkGlobalXtorData(*this, getData()).failed())
553 return failure();
554
555 if (getDtors().size() == getPriorities().size() &&
556 getDtors().size() == getData().size())
557 return success();
558 return emitError(
559 "dtors, priorities, and data must have the same number of elements");
560}
561
562//===----------------------------------------------------------------------===//
563// Builder, printer and verifier for LLVM::AliasOp.
564//===----------------------------------------------------------------------===//
565
566void AliasOp::build(OpBuilder &builder, OperationState &result, Type type,
567 Linkage linkage, StringRef name, bool dsoLocal,
568 ThreadLocalMode threadModel,
570 result.addAttribute(getSymNameAttrName(result.name),
571 builder.getStringAttr(name));
572 result.addAttribute(getAliasTypeAttrName(result.name), TypeAttr::get(type));
573 result.addAttribute(
574 getTlsModeAttrName(result.name),
575 ThreadLocalModeAttr::get(builder.getContext(), threadModel));
576 if (dsoLocal)
577 result.addAttribute(getDsoLocalAttrName(result.name),
578 builder.getUnitAttr());
579
580 result.addAttribute(getLinkageAttrName(result.name),
581 LinkageAttr::get(builder.getContext(), linkage));
582 result.attributes.append(attrs.begin(), attrs.end());
583
584 result.addRegion();
585}
586
587void AliasOp::print(OpAsmPrinter &p) {
589
590 p.printSymbolName(getSymName());
593 {getDsoLocalAttrName(), getSymVisibilityAttrName()})
594 .getAttrs(),
595 {getSymNameAttrName(), getAliasTypeAttrName(), getLinkageAttrName(),
596 getUnnamedAddrAttrName(), getTlsModeAttrName(),
597 getVisibility_AttrName()});
598
599 // Print the trailing type.
600 p << " : " << getType() << ' ';
601 // Print the initializer region.
602 p.printRegion(getInitializerRegion(), /*printEntryBlockArgs=*/false);
603}
604
605// operation ::= `llvm.mlir.alias` linkage? visibility?
606// (`unnamed_addr` | `local_unnamed_addr`)?
607// (`thread_local` (`(` tls-mode `)`)? )?
608// `@` identifier `(` attribute? `)`
609// attribute-list? `:` type region
610//
611ParseResult AliasOp::parse(OpAsmParser &parser, OperationState &result) {
612 // Call into common parsing between GlobalOp and AliasOp.
614 return failure();
615
616 StringAttr name;
617 if (parser.parseSymbolName(name, getSymNameAttrName(result.name),
618 result.attributes))
619 return failure();
620
622 if (parser.parseOptionalAttrDict(result.attributes) ||
623 parser.parseOptionalColonTypeList(types))
624 return failure();
625
626 if (types.size() > 1)
627 return parser.emitError(parser.getNameLoc(), "expected zero or one type");
628
629 Region &initRegion = *result.addRegion();
630 if (parser.parseRegion(initRegion).failed())
631 return failure();
632
633 result.addAttribute(getAliasTypeAttrName(result.name),
634 TypeAttr::get(types[0]));
635 return success();
636}
637
638LogicalResult AliasOp::verify() {
639 bool validType = isCompatibleOuterType(getType())
640 ? !llvm::isa<LLVMVoidType, TokenType, LLVMMetadataType,
641 LLVMLabelType>(getType())
642 : llvm::isa<PointerElementTypeInterface>(getType());
643 if (!validType)
644 return emitOpError(
645 "expects type to be a valid element type for an LLVM global alias");
646
647 // This matches LLVM IR verification logic, see llvm/lib/IR/Verifier.cpp
648 switch (getLinkage()) {
649 case Linkage::External:
650 case Linkage::Internal:
651 case Linkage::Private:
652 case Linkage::Weak:
653 case Linkage::WeakODR:
654 case Linkage::Linkonce:
655 case Linkage::LinkonceODR:
656 case Linkage::AvailableExternally:
657 break;
658 default:
659 return emitOpError()
660 << "'" << stringifyLinkage(getLinkage())
661 << "' linkage not supported in aliases, available options: private, "
662 "internal, linkonce, weak, linkonce_odr, weak_odr, external or "
663 "available_externally";
664 }
665
666 return success();
667}
668
669LogicalResult AliasOp::verifyRegions() {
670 Block &b = getInitializerBlock();
671 auto ret = cast<ReturnOp>(b.getTerminator());
672 if (ret.getNumOperands() == 0 ||
673 !isa<LLVM::LLVMPointerType>(ret.getOperand(0).getType()))
674 return emitOpError("initializer region must always return a pointer");
675
676 for (Operation &op : b) {
677 auto iface = dyn_cast<MemoryEffectOpInterface>(op);
678 if (!iface || !iface.hasNoEffect())
679 return op.emitError()
680 << "ops with side effects are not allowed in alias initializers";
681 }
682
683 return success();
684}
685
686unsigned AliasOp::getAddrSpace() {
687 Block &initializer = getInitializerBlock();
688 auto ret = cast<ReturnOp>(initializer.getTerminator());
689 auto ptrTy = cast<LLVMPointerType>(ret.getOperand(0).getType());
690 return ptrTy.getAddressSpace();
691}
692
693//===----------------------------------------------------------------------===//
694// IFuncOp
695//===----------------------------------------------------------------------===//
696
697void IFuncOp::build(OpBuilder &builder, OperationState &result, StringRef name,
698 Type iFuncType, StringRef resolverName, Type resolverType,
699 Linkage linkage, LLVM::Visibility visibility) {
700 return build(builder, result, name, iFuncType, resolverName, resolverType,
701 linkage, /*dso_local=*/false, /*address_space=*/0,
702 UnnamedAddr::None, visibility, /*sym_visibility=*/nullptr);
703}
704
705LogicalResult IFuncOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
706 Operation *symbol =
707 symbolTable.lookupSymbolIn(parentLLVMModule(*this), getResolverAttr());
708 // This matches LLVM IR verification logic, see llvm/lib/IR/Verifier.cpp
709 auto resolver = dyn_cast_if_present<LLVMFuncOp>(symbol);
710 auto alias = dyn_cast_if_present<AliasOp>(symbol);
711 while (alias) {
712 Block &initBlock = alias.getInitializerBlock();
713 auto returnOp = cast<ReturnOp>(initBlock.getTerminator());
714 auto addrOp = returnOp.getArg().getDefiningOp<AddressOfOp>();
715 // FIXME: This is a best effort solution. The AliasOp body might be more
716 // complex and in that case we bail out with success. To completely match
717 // the LLVM IR logic it would be necessary to implement proper alias and
718 // cast stripping.
719 if (!addrOp)
720 return success();
721 resolver = addrOp.getFunction(symbolTable);
722 alias = addrOp.getAlias(symbolTable);
723 }
724 if (!resolver)
725 return emitOpError("must have a function resolver");
726 Linkage linkage = resolver.getLinkage();
727 if (resolver.isExternal() || linkage == Linkage::AvailableExternally)
728 return emitOpError("resolver must be a definition");
729 if (!isa<LLVMPointerType>(resolver.getFunctionType().getReturnType()))
730 return emitOpError("resolver must return a pointer");
731 auto resolverPtr = dyn_cast<LLVMPointerType>(getResolverType());
732 if (!resolverPtr || resolverPtr.getAddressSpace() != getAddressSpace())
733 return emitOpError("resolver has incorrect type");
734 return success();
735}
736
737LogicalResult IFuncOp::verify() {
738 switch (getLinkage()) {
739 case Linkage::External:
740 case Linkage::Internal:
741 case Linkage::Private:
742 case Linkage::Weak:
743 case Linkage::WeakODR:
744 case Linkage::Linkonce:
745 case Linkage::LinkonceODR:
746 break;
747 default:
748 return emitOpError() << "'" << stringifyLinkage(getLinkage())
749 << "' linkage not supported in ifuncs, available "
750 "options: private, internal, linkonce, weak, "
751 "linkonce_odr, weak_odr, or external linkage";
752 }
753 return success();
754}
755
756//===----------------------------------------------------------------------===//
757// Implementations for LLVM::LLVMFuncOp.
758//===----------------------------------------------------------------------===//
759
760// Add the entry block to the function.
761Block *LLVMFuncOp::addEntryBlock(OpBuilder &builder) {
762 assert(empty() && "function already has an entry block");
763 OpBuilder::InsertionGuard g(builder);
764 Block *entry = builder.createBlock(&getBody());
765
766 // FIXME: Allow passing in proper locations for the entry arguments.
767 LLVMFunctionType type = getFunctionType();
768 for (unsigned i = 0, e = type.getNumParams(); i < e; ++i)
769 entry->addArgument(type.getParamType(i), getLoc());
770 return entry;
771}
772
773void LLVMFuncOp::build(OpBuilder &builder, OperationState &result,
774 StringRef name, Type type, LLVM::Linkage linkage,
775 bool dsoLocal, CConv cconv, SymbolRefAttr comdat,
778 std::optional<uint64_t> functionEntryCount) {
779 result.addRegion();
780 result.addAttribute(getSymNameAttrName(result.name),
781 builder.getStringAttr(name));
782 result.addAttribute(getFunctionTypeAttrName(result.name),
783 TypeAttr::get(type));
784 result.addAttribute(getLinkageAttrName(result.name),
785 LinkageAttr::get(builder.getContext(), linkage));
786 result.addAttribute(getCConvAttrName(result.name),
787 CConvAttr::get(builder.getContext(), cconv));
788 result.attributes.append(attrs.begin(), attrs.end());
789 if (dsoLocal)
790 result.addAttribute(getDsoLocalAttrName(result.name),
791 builder.getUnitAttr());
792 if (comdat)
793 result.addAttribute(getComdatAttrName(result.name), comdat);
794 if (functionEntryCount)
795 result.addAttribute(getFunctionEntryCountAttrName(result.name),
796 FunctionEntryCountAttr::get(builder.getContext(),
797 *functionEntryCount,
799#ifndef NDEBUG
800 std::optional<NamedAttribute> duplicate = result.attributes.findDuplicate();
801 if (duplicate.has_value()) {
802 llvm::report_fatal_error(
803 Twine("LLVMFuncOp propagated an attribute that is meant "
804 "to be constructed by the builder: ") +
805 duplicate->getName().str());
806 }
807#endif
808 if (argAttrs.empty())
809 return;
810
811 assert(llvm::cast<LLVMFunctionType>(type).getNumParams() == argAttrs.size() &&
812 "expected as many argument attribute lists as arguments");
814 builder, result, argAttrs, /*resultAttrs=*/{},
815 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
816}
817
818// Builds an LLVM function type from the given lists of input and output types.
819// Returns a null type if any of the types provided are non-LLVM types, or if
820// there is more than one output type.
821static Type
823 ArrayRef<Type> outputs,
825 Builder &b = parser.getBuilder();
826 if (outputs.size() > 1) {
827 parser.emitError(loc, "failed to construct function type: expected zero or "
828 "one function result");
829 return {};
830 }
831
832 // Convert inputs to LLVM types, exit early on error.
833 SmallVector<Type, 4> llvmInputs;
834 for (auto t : inputs) {
835 if (!isCompatibleType(t)) {
836 parser.emitError(loc, "failed to construct function type: expected LLVM "
837 "type for function arguments");
838 return {};
839 }
840 llvmInputs.push_back(t);
841 }
842
843 // No output is denoted as "void" in LLVM type system.
844 Type llvmOutput =
845 outputs.empty() ? LLVMVoidType::get(b.getContext()) : outputs.front();
846 if (!isCompatibleType(llvmOutput)) {
847 parser.emitError(loc, "failed to construct function type: expected LLVM "
848 "type for function results")
849 << llvmOutput;
850 return {};
851 }
852 return LLVMFunctionType::get(llvmOutput, llvmInputs,
853 variadicFlag.isVariadic());
854}
855
856// Parses an LLVM function.
857//
858// operation ::= `llvm.func` linkage? cconv? function-signature
859// (`comdat(` symbol-ref-id `)`)?
860// function-attributes?
861// function-body
862//
863ParseResult LLVMFuncOp::parse(OpAsmParser &parser, OperationState &result) {
864 // Default to external linkage if no keyword is provided.
865 result.addAttribute(getLinkageAttrName(result.name),
866 LinkageAttr::get(parser.getContext(),
868 parser, LLVM::Linkage::External)));
869
870 // Parse optional visibility, default to Default.
871 result.addAttribute(getVisibility_AttrName(result.name),
874 parser, LLVM::Visibility::Default)));
875
876 // Parse optional UnnamedAddr, default to None.
877 result.addAttribute(getUnnamedAddrAttrName(result.name),
880 parser, LLVM::UnnamedAddr::None)));
881
882 // Default to C Calling Convention if no keyword is provided.
883 result.addAttribute(
884 getCConvAttrName(result.name),
885 CConvAttr::get(parser.getContext(),
886 parseOptionalLLVMKeyword<CConv>(parser, LLVM::CConv::C)));
887
888 StringAttr nameAttr;
890 SmallVector<DictionaryAttr> resultAttrs;
891 SmallVector<Type> resultTypes;
892 bool isVariadic;
893
894 auto signatureLocation = parser.getCurrentLocation();
895 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(result.name),
896 result.attributes) ||
898 parser, /*allowVariadic=*/true, entryArgs, isVariadic, resultTypes,
899 resultAttrs))
900 return failure();
901
902 SmallVector<Type> argTypes;
903 for (auto &arg : entryArgs)
904 argTypes.push_back(arg.type);
905 auto type =
906 buildLLVMFunctionType(parser, signatureLocation, argTypes, resultTypes,
908 if (!type)
909 return failure();
910 result.addAttribute(getFunctionTypeAttrName(result.name),
911 TypeAttr::get(type));
912
913 if (succeeded(parser.parseOptionalKeyword("vscale_range"))) {
914 int64_t minRange, maxRange;
915 if (parser.parseLParen() || parser.parseInteger(minRange) ||
916 parser.parseComma() || parser.parseInteger(maxRange) ||
917 parser.parseRParen())
918 return failure();
919 auto intTy = IntegerType::get(parser.getContext(), 32);
920 result.addAttribute(
921 getVscaleRangeAttrName(result.name),
922 LLVM::VScaleRangeAttr::get(parser.getContext(),
923 IntegerAttr::get(intTy, minRange),
924 IntegerAttr::get(intTy, maxRange)));
925 }
926 // Parse the optional comdat selector.
927 if (succeeded(parser.parseOptionalKeyword("comdat"))) {
928 SymbolRefAttr comdat;
929 if (parser.parseLParen() || parser.parseAttribute(comdat) ||
930 parser.parseRParen())
931 return failure();
932
933 result.addAttribute(getComdatAttrName(result.name), comdat);
934 }
935
936 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
937 return failure();
939 parser.getBuilder(), result, entryArgs, resultAttrs,
940 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
941
942 auto *body = result.addRegion();
943 OptionalParseResult parseResult =
944 parser.parseOptionalRegion(*body, entryArgs);
945 return failure(parseResult.has_value() && failed(*parseResult));
946}
947
948// Print the LLVMFuncOp. Collects argument and result types and passes them to
949// helper functions. Drops "void" result since it cannot be parsed back. Skips
950// the external linkage since it is the default value.
951void LLVMFuncOp::print(OpAsmPrinter &p) {
952 p << ' ';
953 if (getLinkage() != LLVM::Linkage::External)
954 p << stringifyLinkage(getLinkage()) << ' ';
955 StringRef visibility = stringifyVisibility(getVisibility_());
956 if (!visibility.empty())
957 p << visibility << ' ';
958 if (auto unnamedAddr = getUnnamedAddr()) {
959 StringRef str = stringifyUnnamedAddr(*unnamedAddr);
960 if (!str.empty())
961 p << str << ' ';
962 }
963 if (getCConv() != LLVM::CConv::C)
964 p << stringifyCConv(getCConv()) << ' ';
965
966 p.printSymbolName(getName());
967
968 LLVMFunctionType fnType = getFunctionType();
969 SmallVector<Type, 8> argTypes;
970 SmallVector<Type, 1> resTypes;
971 argTypes.reserve(fnType.getNumParams());
972 for (unsigned i = 0, e = fnType.getNumParams(); i < e; ++i)
973 argTypes.push_back(fnType.getParamType(i));
974
975 Type returnType = fnType.getReturnType();
976 if (!llvm::isa<LLVMVoidType>(returnType))
977 resTypes.push_back(returnType);
978
980 isVarArg(), resTypes);
981
982 // Print vscale range if present
983 if (std::optional<VScaleRangeAttr> vscale = getVscaleRange())
984 p << " vscale_range(" << vscale->getMinRange().getInt() << ", "
985 << vscale->getMaxRange().getInt() << ')';
986
987 // Print the optional comdat selector.
988 if (auto comdat = getComdat())
989 p << " comdat(" << *comdat << ')';
990
992 p, *this,
993 {getFunctionTypeAttrName(), getArgAttrsAttrName(), getResAttrsAttrName(),
994 getLinkageAttrName(), getCConvAttrName(), getVisibility_AttrName(),
995 getComdatAttrName(), getUnnamedAddrAttrName(),
996 getVscaleRangeAttrName()});
997
998 // Print the body if this is not an external function.
999 Region &body = getBody();
1000 if (!body.empty()) {
1001 p << ' ';
1002 p.printRegion(body, /*printEntryBlockArgs=*/false,
1003 /*printBlockTerminators=*/true);
1004 }
1005}
1006
1007LogicalResult LLVMFuncOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1008 return verifyComdat(*this, getComdat(), symbolTable);
1009}
1010
1011// Verifies LLVM- and implementation-specific properties of the LLVM func Op:
1012// - functions don't have 'common' linkage
1013// - external functions have 'external' or 'extern_weak' linkage;
1014// - vararg is (currently) only supported for external functions;
1015LogicalResult LLVMFuncOp::verify() {
1016 if (getLinkage() == LLVM::Linkage::Common)
1017 return emitOpError() << "functions cannot have '"
1018 << stringifyLinkage(LLVM::Linkage::Common)
1019 << "' linkage";
1020
1021 if (isExternal()) {
1022 if (getFunctionEntryCountAttr())
1023 return emitOpError() << "external functions cannot have "
1024 << getFunctionEntryCountAttrName() << " attribute";
1025
1026 if (getLinkage() != LLVM::Linkage::External &&
1027 getLinkage() != LLVM::Linkage::ExternWeak)
1028 return emitOpError() << "external functions must have '"
1029 << stringifyLinkage(LLVM::Linkage::External)
1030 << "' or '"
1031 << stringifyLinkage(LLVM::Linkage::ExternWeak)
1032 << "' linkage";
1033 return success();
1034 }
1035
1036 // In LLVM IR, these attributes are composed by convention, not by design.
1037 if (isNoInline() && isAlwaysInline())
1038 return emitError("no_inline and always_inline attributes are incompatible");
1039
1040 if (isOptimizeNone() && !isNoInline())
1041 return emitOpError("with optimize_none must also be no_inline");
1042
1043 Type landingpadResultTy;
1044 StringRef diagnosticMessage;
1045 bool isLandingpadTypeConsistent =
1046 !walk([&](Operation *op) {
1047 const auto checkType = [&](Type type, StringRef errorMessage) {
1048 if (!landingpadResultTy) {
1049 landingpadResultTy = type;
1050 return WalkResult::advance();
1051 }
1052 if (landingpadResultTy != type) {
1053 diagnosticMessage = errorMessage;
1054 return WalkResult::interrupt();
1055 }
1056 return WalkResult::advance();
1057 };
1059 .Case([&](LandingpadOp landingpad) {
1060 constexpr StringLiteral errorMessage =
1061 "'llvm.landingpad' should have a consistent result type "
1062 "inside a function";
1063 return checkType(landingpad.getType(), errorMessage);
1064 })
1065 .Case([&](ResumeOp resume) {
1066 constexpr StringLiteral errorMessage =
1067 "'llvm.resume' should have a consistent input type inside a "
1068 "function";
1069 return checkType(resume.getValue().getType(), errorMessage);
1070 })
1071 .Default([](auto) { return WalkResult::skip(); });
1072 }).wasInterrupted();
1073 if (!isLandingpadTypeConsistent) {
1074 assert(!diagnosticMessage.empty() &&
1075 "Expecting a non-empty diagnostic message");
1076 return emitError(diagnosticMessage);
1077 }
1078
1079 if (failed(verifyBlockTags(*this)))
1080 return failure();
1081
1082 return success();
1083}
1084
1085/// Verifies LLVM- and implementation-specific properties of the LLVM func Op:
1086/// - entry block arguments are of LLVM types.
1087LogicalResult LLVMFuncOp::verifyRegions() {
1088 if (isExternal())
1089 return success();
1090
1091 unsigned numArguments = getFunctionType().getNumParams();
1092 Block &entryBlock = front();
1093 for (unsigned i = 0; i < numArguments; ++i) {
1094 Type argType = entryBlock.getArgument(i).getType();
1095 if (!isCompatibleType(argType))
1096 return emitOpError("entry block argument #")
1097 << i << " is not of LLVM type";
1098 }
1099
1100 return success();
1101}
1102
1103Region *LLVMFuncOp::getCallableRegion() {
1104 if (isExternal())
1105 return nullptr;
1106 return &getBody();
1107}
1108
1109//===----------------------------------------------------------------------===//
1110// LinkerOptionsOp
1111//===----------------------------------------------------------------------===//
1112
1113LogicalResult LinkerOptionsOp::verify() {
1114 if (mlir::Operation *parentOp = (*this)->getParentOp();
1115 parentOp && !satisfiesLLVMModule(parentOp))
1116 return emitOpError("must appear at the module level");
1117 return success();
1118}
1119
1120//===----------------------------------------------------------------------===//
1121// ModuleFlagsOp
1122//===----------------------------------------------------------------------===//
1123
1124LogicalResult ModuleFlagsOp::verify() {
1125 if (Operation *parentOp = (*this)->getParentOp();
1126 parentOp && !satisfiesLLVMModule(parentOp))
1127 return emitOpError("must appear at the module level");
1128
1129 llvm::DenseSet<StringAttr> seenNonRequireKeys;
1130 for (Attribute flag : getFlags()) {
1131 auto moduleFlag = dyn_cast<ModuleFlagAttrInterface>(flag);
1132 if (!moduleFlag)
1133 return emitOpError("expected a module flag attribute");
1135 moduleFlag.getModuleFlagKey(), moduleFlag.getModuleFlagValue(),
1136 [&] { return emitOpError(); })))
1137 return failure();
1138 if (moduleFlag.getModuleFlagBehavior() == ModFlagBehavior::Require)
1139 continue;
1140 StringAttr key = moduleFlag.getModuleFlagKey();
1141 if (!seenNonRequireKeys.insert(key).second)
1142 return emitOpError("expected module flag key '")
1143 << key.getValue() << "' to be unique for non-require flags";
1144 }
1145 return success();
1146}
1147
1148//===----------------------------------------------------------------------===//
1149// Utility functions.
1150//===----------------------------------------------------------------------===//
1151
1153 StringRef name, StringRef value,
1154 LLVM::Linkage linkage) {
1155 assert(builder.getInsertionBlock() &&
1156 builder.getInsertionBlock()->getParentOp() &&
1157 "expected builder to point to a block constrained in an op");
1158 auto module =
1159 builder.getInsertionBlock()->getParentOp()->getParentOfType<ModuleOp>();
1160 assert(module && "builder points to an op outside of a module");
1161
1162 // Create the global at the entry of the module.
1163 OpBuilder moduleBuilder(module.getBodyRegion(), builder.getListener());
1164 MLIRContext *ctx = builder.getContext();
1165 auto type = LLVM::LLVMArrayType::get(IntegerType::get(ctx, 8), value.size());
1166 auto global = LLVM::GlobalOp::create(
1167 moduleBuilder, loc, type, /*isConstant=*/true, linkage, name,
1168 builder.getStringAttr(value), /*alignment=*/0);
1169
1170 LLVMPointerType ptrType = LLVMPointerType::get(ctx);
1171 // Get the pointer to the first character in the global string.
1172 Value globalPtr =
1173 LLVM::AddressOfOp::create(builder, loc, ptrType, global.getSymNameAttr());
1174 return LLVM::GEPOp::create(builder, loc, ptrType, type, globalPtr,
1175 ArrayRef<GEPArg>{0, 0});
1176}
1177
1182
1184 Operation *module = op->getParentOp();
1185 while (module && !satisfiesLLVMModule(module))
1186 module = module->getParentOp();
1187 assert(module && "unexpected operation outside of a module");
1188 return module;
1189}
1190
1191#define GET_OP_CLASSES
1192#include "mlir/Dialect/LLVMIR/LLVMModuleOps.cpp.inc"
return success()
static LogicalResult checkGlobalXtorData(Operation *op, ArrayAttr data)
static bool isZeroAttribute(Attribute value)
static LogicalResult verifyComdat(Operation *op, std::optional< SymbolRefAttr > attr, SymbolTableCollection &symbolTable)
static LogicalResult verifyBlockTags(LLVMFuncOp funcOp)
static Type buildLLVMFunctionType(OpAsmParser &parser, SMLoc loc, ArrayRef< Type > inputs, ArrayRef< Type > outputs, function_interface_impl::VariadicFlag variadicFlag)
static LogicalResult verifySymbolAttrUse(FlatSymbolRefAttr symbol, Operation *op, SymbolTableCollection &symbolTable)
Verifies symbol's use in op to ensure the symbol is a valid and fully defined llvm....
static ParseResult parseCommonGlobalAndAlias(OpAsmParser &parser, OperationState &result)
Parse common attributes that might show up in the same order in both GlobalOp and AliasOp.
static void printCommonGlobalAndAlias(OpAsmPrinter &p, OpType op)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
static arith::FastMathFlags getFlags(arith::FastMathFlagsAttr fastmath)
Returns the flags held by fastmath, or none if it is null.
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
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 parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColonTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional colon followed by a type list, which if present must have at least one type.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalRParen()=0
Parse a ) token if present.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual void printSymbolName(StringRef symbolRef)
Print the given string as a symbol reference, i.e.
virtual void printAttribute(Attribute attr)
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
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
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
UnitAttr getUnitAttr()
Definition Builders.cpp:106
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
MLIRContext * getContext() const
Definition Builders.h:56
A symbol reference with a reference path containing a single element.
StringRef getValue() const
Returns the name of the held symbol reference.
StringAttr getAttr() const
Returns the name of the held symbol reference as a StringAttr.
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
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
ArrayRef< NamedAttribute > getAttrs() const
Return all of the attributes on this operation.
Attribute set(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
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 OptionalParseResult parseOptionalRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
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
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition Builders.h:323
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition Builders.h:445
This class provides the API for ops that are known to be isolated from above.
A trait used to provide symbol table functionalities to a region operation.
void walkInherentAttrs(Operation *op, InherentAttrVisitor visitor) const
Visit the inherent attributes stored in the properties of op.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
std::optional< Attribute > getInherentAttr(StringRef name)
Access an inherent attribute by name: returns an empty optional if there is no inherent attribute wit...
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
DictionaryAttr getRawDictionaryAttrs()
Return all attributes that are not stored as properties.
Definition Operation.h:563
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & emplaceBlock()
Definition Region.h:46
iterator_range< OpIterator > getOps()
Definition Region.h:180
bool empty()
Definition Region.h:60
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,...
virtual Operation * lookupSymbolIn(Operation *symbolTableOp, StringAttr symbol)
Look up a symbol with the specified name within the specified symbol table operation,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
A named class for passing around the variadic flag.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
LogicalResult verifyModuleFlagValue(StringAttr key, Attribute value, function_ref< InFlightDiagnostic()> emitError)
Verifies that a module flag value can be exported to LLVM IR.
Value createGlobalString(Location loc, OpBuilder &builder, StringRef name, StringRef value, Linkage linkage)
Create an LLVM global containing the string "value" at the module containing surrounding the insertio...
Operation * parentLLVMModule(Operation *op)
Lookup parent Module satisfying LLVM conditions on the Module Operation.
NamedAttrList getAttrsForPrinting(Operation *op)
Returns the attributes of op to print: its discardable attributes and all its inherent attributes.
void printLLVMLinkage(mlir::OpAsmPrinter &p, mlir::Operation *, mlir::LLVM::LinkageAttr val)
bool isCompatibleOuterType(Type type)
Returns true if the given outer type is compatible with the LLVM dialect without checking its potenti...
RetTy parseOptionalLLVMKeyword(OpAsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
Definition LLVMOps.h:155
bool satisfiesLLVMModule(Operation *op)
LLVM requires some operations to be inside of a Module operation.
bool isCompatibleType(Type type)
Returns true if the given type is compatible with the LLVM dialect.
mlir::ParseResult parseLLVMLinkage(mlir::OpAsmParser &p, mlir::LLVM::LinkageAttr &val)
int parseOptionalKeywordAlternative(OpAsmParser &parser, ArrayRef< StringRef > keywords)
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 walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
Definition Visitors.h:102
ParseResult parseFunctionSignatureWithArguments(OpAsmParser &parser, bool allowVariadic, SmallVectorImpl< OpAsmParser::Argument > &arguments, bool &isVariadic, SmallVectorImpl< Type > &resultTypes, SmallVectorImpl< DictionaryAttr > &resultAttrs)
Parses a function signature using parser.
void printFunctionAttributes(OpAsmPrinter &p, Operation *op, ArrayRef< StringRef > elided={})
Prints the list of function prefixed with the "attributes" keyword.
void printFunctionSignature(OpAsmPrinter &p, FunctionOpInterface op, ArrayRef< Type > argTypes, bool isVariadic, ArrayRef< Type > resultTypes)
Prints the signature of the function-like operation op.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
This represents an operation in an abstracted form, suitable for use with the builder APIs.