MLIR 24.0.0git
LLVMAttrs.cpp
Go to the documentation of this file.
1//===- LLVMAttrs.cpp - LLVM Attributes registration -----------------------===//
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 attribute details for the LLVM IR dialect in MLIR.
10//
11//===----------------------------------------------------------------------===//
12
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/BinaryFormat/Dwarf.h"
20#include "llvm/IR/DebugInfoMetadata.h"
21#include "llvm/IR/LLVMContext.h"
22#include "llvm/Support/ErrorHandling.h"
23
24using namespace mlir;
25using namespace mlir::LLVM;
26
27/// Parses DWARF expression arguments with respect to the DWARF operation
28/// opcode. Some DWARF expression operations have a specific number of operands
29/// and may appear in a textual form.
30static ParseResult parseExpressionArg(AsmParser &parser, uint64_t opcode,
32
33/// Prints DWARF expression arguments with respect to the specific DWARF
34/// operation. Some operands are printed in their textual form.
35static void printExpressionArg(AsmPrinter &printer, uint64_t opcode,
37
38/// Parses a source language from either the historical inline `DW_LANG_*`
39/// syntax or a nested `DISourceLanguageNameAttr`.
40static ParseResult parseSourceLanguage(AsmParser &parser,
41 DISourceLanguageNameAttr &language);
42
43/// Prints an unversioned source language without a dialect using the
44/// historical inline `DW_LANG_*` syntax. All other source languages are
45/// printed as a nested `DISourceLanguageNameAttr`.
46static void printSourceLanguage(AsmPrinter &printer,
47 DISourceLanguageNameAttr language);
48
49#include "mlir/Dialect/LLVMIR/LLVMAttrInterfaces.cpp.inc"
50#include "mlir/Dialect/LLVMIR/LLVMOpsEnums.cpp.inc"
51#define GET_ATTRDEF_CLASSES
52#include "mlir/Dialect/LLVMIR/LLVMOpsAttrDefs.cpp.inc"
53
54//===----------------------------------------------------------------------===//
55// AddressSpaceAttr
56//===----------------------------------------------------------------------===//
57
58/// Checks whether the given type is an LLVM type that can be loaded or stored.
60 Type type, ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
61 const ::mlir::DataLayout *dataLayout,
63 if (!isLoadableType(type)) {
64 if (emitError)
65 emitError() << "type must be LLVM type with size, but got " << type;
66 return false;
67 }
68 if (ordering == ptr::AtomicOrdering::not_atomic)
69 return true;
70
71 // To check atomic validity we need a datalayout.
72 if (!dataLayout) {
73 if (emitError)
74 emitError() << "expected a valid data layout";
75 return false;
76 }
77 if (!isTypeCompatibleWithAtomicOp(type, *dataLayout)) {
78 if (emitError)
79 emitError() << "unsupported type " << type << " for atomic access";
80 return false;
81 }
82 return true;
83}
84
85bool AddressSpaceAttr::isValidLoad(
86 Type type, ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
87 const ::mlir::DataLayout *dataLayout,
89 return detail::isValidLoadStoreImpl(type, ordering, alignment, dataLayout,
90 emitError);
91}
92
93bool AddressSpaceAttr::isValidStore(
94 Type type, ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
95 const ::mlir::DataLayout *dataLayout,
97 return detail::isValidLoadStoreImpl(type, ordering, alignment, dataLayout,
98 emitError);
99}
100
101bool AddressSpaceAttr::isValidAtomicOp(
102 ptr::AtomicBinOp op, Type type, ptr::AtomicOrdering ordering,
103 std::optional<int64_t> alignment, const ::mlir::DataLayout *dataLayout,
105 // TODO: update this method once `ptr.atomic_rmw` is implemented.
106 assert(false && "unimplemented, see TODO in the source.");
107 return false;
108}
109
110bool AddressSpaceAttr::isValidAtomicXchg(
111 Type type, ptr::AtomicOrdering successOrdering,
112 ptr::AtomicOrdering failureOrdering, std::optional<int64_t> alignment,
113 const ::mlir::DataLayout *dataLayout,
115 // TODO: update this method once `ptr.atomic_cmpxchg` is implemented.
116 assert(false && "unimplemented, see TODO in the source.");
117 return false;
118}
119
120bool AddressSpaceAttr::isValidAddrSpaceCast(
122 // TODO: update this method once the `ptr.addrspace_cast` op is added to the
123 // dialect.
124 assert(false && "unimplemented, see TODO in the source.");
125 return false;
126}
127
128bool AddressSpaceAttr::isValidPtrIntCast(
129 Type intLikeTy, Type ptrLikeTy,
131 // TODO: update this method once the int-cast ops are added to the `ptr`
132 // dialect.
133 assert(false && "unimplemented, see TODO in the source.");
134 return false;
135}
136
137//===----------------------------------------------------------------------===//
138// FunctionMetadataAttr
139//===----------------------------------------------------------------------===//
140
141static constexpr unsigned kReservedFunctionMetadataKinds[] = {
142 llvm::LLVMContext::MD_dbg, llvm::LLVMContext::MD_prof};
143
144static StringRef getFixedMetadataKindName(unsigned kind) {
145 switch (kind) {
146#define LLVM_FIXED_MD_KIND(EnumID, Name, Value) \
147 case llvm::LLVMContext::EnumID: \
148 return Name;
149#include "llvm/IR/FixedMetadataKinds.def"
150#undef LLVM_FIXED_MD_KIND
151 }
152 llvm_unreachable("unknown fixed metadata kind");
153}
154
155LogicalResult
156FunctionMetadataAttr::verify(function_ref<InFlightDiagnostic()> emitError,
157 StringAttr metadataName, MDNodeAttr node) {
158 (void)node;
159 StringRef name = metadataName.getValue();
160 if (name.empty())
161 return emitError() << "function_metadata entry name must not be empty";
162 if (llvm::any_of(kReservedFunctionMetadataKinds, [&](unsigned kind) {
163 return name == getFixedMetadataKindName(kind);
164 })) {
165 return emitError() << "reserved function_metadata entry '" << name
166 << "' is not supported by the generic carrier";
167 }
168 return success();
169}
170
171//===----------------------------------------------------------------------===//
172// AliasScopeAttr
173//===----------------------------------------------------------------------===//
174
175LogicalResult
176AliasScopeAttr::verify(function_ref<InFlightDiagnostic()> emitError,
177 Attribute id, AliasScopeDomainAttr domain,
178 StringAttr description) {
179 (void)domain;
180 (void)description;
181 if (!llvm::isa<StringAttr, DistinctAttr>(id))
182 return emitError()
183 << "id of an alias scope must be a StringAttr or a DistrinctAttr";
184
185 return success();
186}
187
188//===----------------------------------------------------------------------===//
189// DINodeAttr
190//===----------------------------------------------------------------------===//
191
193 return llvm::isa<DIBasicTypeAttr, DICommonBlockAttr, DICompileUnitAttr,
194 DICompositeTypeAttr, DIDerivedTypeAttr, DIEnumeratorAttr,
195 DIFileAttr, DIGenericSubrangeAttr, DIGlobalVariableAttr,
196 DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr,
197 DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr,
198 DINamespaceAttr, DINullTypeAttr, DIAnnotationAttr,
199 DIStringTypeAttr, DISubprogramAttr, DISubrangeAttr,
200 DISubroutineTypeAttr>(attr);
201}
202
203//===----------------------------------------------------------------------===//
204// DIScopeAttr
205//===----------------------------------------------------------------------===//
206
208 return llvm::isa<DICommonBlockAttr, DICompileUnitAttr, DICompositeTypeAttr,
209 DIDerivedTypeAttr, DIFileAttr, DILocalScopeAttr,
210 DIModuleAttr, DINamespaceAttr>(attr);
211}
212
213//===----------------------------------------------------------------------===//
214// DILocalScopeAttr
215//===----------------------------------------------------------------------===//
216
218 return llvm::isa<DILexicalBlockAttr, DILexicalBlockFileAttr,
219 DISubprogramAttr>(attr);
220}
221
222//===----------------------------------------------------------------------===//
223// DIVariableAttr
224//===----------------------------------------------------------------------===//
225
227 return llvm::isa<DILocalVariableAttr, DIGlobalVariableAttr>(attr);
228}
229
230//===----------------------------------------------------------------------===//
231// DITypeAttr
232//===----------------------------------------------------------------------===//
233
235 return llvm::isa<DINullTypeAttr, DIBasicTypeAttr, DICompositeTypeAttr,
236 DIDerivedTypeAttr, DIStringTypeAttr, DISubroutineTypeAttr>(
237 attr);
238}
239
240//===----------------------------------------------------------------------===//
241// DIDerivedTypeAttr
242//===----------------------------------------------------------------------===//
243
244LogicalResult DIDerivedTypeAttr::verify(
245 function_ref<InFlightDiagnostic()> emitError, unsigned tag, StringAttr name,
246 DIFileAttr file, uint32_t line, DIScopeAttr scope, DITypeAttr baseType,
247 uint64_t sizeInBits, uint32_t alignInBits, uint64_t offsetInBits,
248 std::optional<unsigned> dwarfAddressSpace, DIFlags flags,
249 Attribute extraData) {
250 if (extraData && !llvm::isa<DINodeAttr, IntegerAttr>(extraData))
251 return emitError() << "extraData must be a DINodeAttr or an IntegerAttr";
252 return success();
253}
254
255//===----------------------------------------------------------------------===//
256// TBAANodeAttr
257//===----------------------------------------------------------------------===//
258
260 return llvm::isa<TBAATypeDescriptorAttr, TBAARootAttr>(attr);
261}
262
263//===----------------------------------------------------------------------===//
264// MemProfMIBAttr
265//===----------------------------------------------------------------------===//
266
267LogicalResult
268MemProfMIBAttr::verify(function_ref<InFlightDiagnostic()> emitError,
269 DenseI64ArrayAttr callStack, StringAttr,
271 // The call stack feeds `Verifier::visitCallStackMetadata`, which needs at
272 // least one frame hash. The other parameters are typed, so an empty stack
273 // is the only bad shape that can get here.
274 if (callStack.empty())
275 return emitError() << "call stack of a memprof MemInfoBlock must not be "
276 "empty";
277 return success();
278}
279
280//===----------------------------------------------------------------------===//
281// MemoryEffectsAttr
282//===----------------------------------------------------------------------===//
283
284MemoryEffectsAttr MemoryEffectsAttr::get(MLIRContext *context,
285 ArrayRef<ModRefInfo> memInfoArgs) {
286 if (memInfoArgs.empty())
287 return MemoryEffectsAttr::get(context, /*other=*/ModRefInfo::ModRef,
288 /*argMem=*/ModRefInfo::ModRef,
289 /*inaccessibleMem=*/ModRefInfo::ModRef,
290 /*errnoMem=*/ModRefInfo::ModRef,
291 /*targetMem0=*/ModRefInfo::ModRef,
292 /*targetMem1=*/ModRefInfo::ModRef);
293 if (memInfoArgs.size() == 6)
294 return MemoryEffectsAttr::get(context, memInfoArgs[0], memInfoArgs[1],
295 memInfoArgs[2], memInfoArgs[3],
296 memInfoArgs[4], memInfoArgs[5]);
297 return {};
298}
299
300bool MemoryEffectsAttr::isReadWrite() {
301 if (this->getArgMem() != ModRefInfo::ModRef)
302 return false;
303 if (this->getInaccessibleMem() != ModRefInfo::ModRef)
304 return false;
305 if (this->getOther() != ModRefInfo::ModRef)
306 return false;
307 if (this->getErrnoMem() != ModRefInfo::ModRef)
308 return false;
309 if (this->getTargetMem0() != ModRefInfo::ModRef)
310 return false;
311 if (this->getTargetMem1() != ModRefInfo::ModRef)
312 return false;
313 return true;
314}
315
316//===----------------------------------------------------------------------===//
317// DIExpression
318//===----------------------------------------------------------------------===//
319
320DIExpressionAttr DIExpressionAttr::get(MLIRContext *context) {
321 return get(context, ArrayRef<DIExpressionElemAttr>({}));
322}
323
324ParseResult parseExpressionArg(AsmParser &parser, uint64_t opcode,
325 SmallVector<uint64_t> &args) {
326 auto operandParser = [&]() -> LogicalResult {
327 uint64_t operand = 0;
328 if (!args.empty() && opcode == llvm::dwarf::DW_OP_LLVM_convert) {
329 // Attempt to parse a keyword.
330 StringRef keyword;
331 if (succeeded(parser.parseOptionalKeyword(&keyword))) {
332 operand = llvm::dwarf::getAttributeEncoding(keyword);
333 if (operand == 0) {
334 // The keyword is invalid.
335 return parser.emitError(parser.getCurrentLocation())
336 << "encountered unknown attribute encoding \"" << keyword
337 << "\"";
338 }
339 }
340 }
341
342 // operand should be non-zero if a keyword was parsed. Otherwise, the
343 // operand MUST be an integer.
344 if (operand == 0) {
345 // Parse the next operand as an integer.
346 if (parser.parseInteger(operand)) {
347 return parser.emitError(parser.getCurrentLocation())
348 << "expected integer operand";
349 }
350 }
351
352 args.push_back(operand);
353 return success();
354 };
355
356 // Parse operands as a comma-separated list.
357 return parser.parseCommaSeparatedList(operandParser);
358}
359
360void printExpressionArg(AsmPrinter &printer, uint64_t opcode,
361 ArrayRef<uint64_t> args) {
362 size_t i = 0;
363 llvm::interleaveComma(args, printer, [&](uint64_t operand) {
364 if (i > 0 && opcode == llvm::dwarf::DW_OP_LLVM_convert) {
365 if (const StringRef keyword =
366 llvm::dwarf::AttributeEncodingString(operand);
367 !keyword.empty()) {
368 printer << keyword;
369 return;
370 }
371 }
372 // All operands are expected to be printed as integers.
373 printer << operand;
374 i++;
375 });
376}
377
378//===----------------------------------------------------------------------===//
379// DICompositeTypeAttr
380//===----------------------------------------------------------------------===//
381
382DIRecursiveTypeAttrInterface
383DICompositeTypeAttr::withRecId(DistinctAttr recId) {
384 return DICompositeTypeAttr::get(
385 getContext(), recId, getIsRecSelf(), getTag(), getName(), getFile(),
386 getLine(), getScope(), getBaseType(), getFlags(), getSizeInBits(),
387 getAlignInBits(), getDataLocation(), getRank(), getAllocated(),
388 getAssociated(), getIdentifier(), getDiscriminator(), getElements());
389}
390
391DIRecursiveTypeAttrInterface
392DICompositeTypeAttr::getRecSelf(DistinctAttr recId) {
393 return DICompositeTypeAttr::get(recId.getContext(), recId, /*isRecSelf=*/true,
394 0, {}, {}, 0, {}, {}, DIFlags(), 0, 0, {}, {},
395 {}, {}, {}, {}, {});
396}
397
398//===----------------------------------------------------------------------===//
399// DISourceLanguageNameAttr
400//===----------------------------------------------------------------------===//
401
402static ParseResult parseSourceLanguage(AsmParser &parser,
403 DISourceLanguageNameAttr &language) {
404 DISourceLanguageNameAttr nestedLanguage;
405 OptionalParseResult nestedResult =
406 parser.parseOptionalAttribute(nestedLanguage);
407 if (nestedResult.has_value()) {
408 if (failed(*nestedResult))
409 return failure();
410 language = nestedLanguage;
411 return success();
412 }
413
414 // If we cannot parse the full attr, try to just parse a DWARF language.
415 SMLoc loc = parser.getCurrentLocation();
416 StringRef spelling;
417 if (parser.parseKeyword(&spelling))
418 return failure();
419 if (unsigned value = llvm::dwarf::getLanguage(spelling)) {
420 language = DISourceLanguageNameAttr::get(
421 parser.getContext(), value, /*name=*/0, /*version=*/std::nullopt,
422 /*dialect=*/0);
423 return success();
424 }
425 return parser.emitError(loc)
426 << "invalid debug info source language: " << spelling;
427}
428
429static void printSourceLanguage(AsmPrinter &printer,
430 DISourceLanguageNameAttr language) {
431 // Print only the DWARF language if the other fields are not set.
432 if (language.getLanguage() && !language.getName() && !language.getVersion() &&
433 !language.getDialect()) {
434 printer << llvm::dwarf::LanguageString(language.getLanguage());
435 return;
436 }
437 printer.printAttribute(language);
438}
439
440LogicalResult DISourceLanguageNameAttr::verify(
441 function_ref<InFlightDiagnostic()> emitError, unsigned language,
442 unsigned name, std::optional<uint32_t> version, unsigned /*dialect*/) {
443 if (static_cast<bool>(language) == static_cast<bool>(name))
444 return emitError() << "expected exactly one of language or name";
445 if (name && !version)
446 return emitError() << "DW_LNAME requires a version";
447 if (language && version)
448 return emitError() << "DW_LANG cannot have a version";
449 return success();
450}
451
452//===----------------------------------------------------------------------===//
453// DICompileUnitAttr
454//===----------------------------------------------------------------------===//
455
456DIRecursiveTypeAttrInterface DICompileUnitAttr::withRecId(DistinctAttr recId) {
457 return DICompileUnitAttr::get(
458 getContext(), recId, getIsRecSelf(), getId(), getSourceLanguage(),
459 getFile(), getProducer(), getIsOptimized(), getEmissionKind(),
460 getIsDebugInfoForProfiling(), getNameTableKind(), getSplitDebugFilename(),
461 getImportedEntities());
462}
463
464DIRecursiveTypeAttrInterface DICompileUnitAttr::getRecSelf(DistinctAttr recId) {
465
466 return DICompileUnitAttr::get(
467 recId.getContext(), recId, /*isRecSelf=*/true, /*id=*/{},
468 /*sourceLanguage=*/{},
469 /*file=*/{}, /*producer=*/{}, /*isOptimized=*/false, DIEmissionKind::None,
470 /*isDebugInfoForProfiling=*/false, DINameTableKind::Default,
471 /*splitDebugFilename=*/{}, /*importedEntities=*/{});
472}
473
474LogicalResult DICompileUnitAttr::verify(
475 function_ref<InFlightDiagnostic()> emitError, DistinctAttr recId,
476 bool isRecSelf, DistinctAttr id, DISourceLanguageNameAttr sourceLanguage,
477 DIFileAttr file, StringAttr producer, bool isOptimized,
478 DIEmissionKind emissionKind, bool isDebugInfoForProfiling,
479 DINameTableKind nameTableKind, StringAttr splitDebugFilename,
480 ArrayRef<DINodeAttr> importedEntities) {
481 if (isRecSelf)
482 return success();
483 if (!sourceLanguage)
484 return emitError() << "sourceLanguage must be set";
485 return success();
486}
487
488//===----------------------------------------------------------------------===//
489// DISubprogramAttr
490//===----------------------------------------------------------------------===//
491
492DIRecursiveTypeAttrInterface DISubprogramAttr::withRecId(DistinctAttr recId) {
493 return DISubprogramAttr::get(getContext(), recId, getIsRecSelf(), getId(),
494 getCompileUnit(), getScope(), getName(),
495 getLinkageName(), getFile(), getLine(),
496 getScopeLine(), getSubprogramFlags(), getType(),
497 getRetainedNodes(), getAnnotations());
498}
499
500DIRecursiveTypeAttrInterface DISubprogramAttr::getRecSelf(DistinctAttr recId) {
501 return DISubprogramAttr::get(recId.getContext(), recId, /*isRecSelf=*/true,
502 {}, {}, {}, {}, {}, {}, 0, 0, {}, {}, {}, {});
503}
504
505//===----------------------------------------------------------------------===//
506// ConstantRangeAttr
507//===----------------------------------------------------------------------===//
508
509Attribute ConstantRangeAttr::parse(AsmParser &parser, Type odsType) {
510 llvm::SMLoc loc = parser.getCurrentLocation();
511 IntegerType widthType;
512 if (parser.parseLess() || parser.parseType(widthType) ||
513 parser.parseComma()) {
514 return Attribute{};
515 }
516 unsigned bitWidth = widthType.getWidth();
517 APInt lower(bitWidth, 0);
518 APInt upper(bitWidth, 0);
519 if (parser.parseInteger(lower) || parser.parseComma() ||
520 parser.parseInteger(upper) || parser.parseGreater())
521 return Attribute{};
522 // Non-positive numbers may use more bits than `bitWidth`
523 lower = lower.sextOrTrunc(bitWidth);
524 upper = upper.sextOrTrunc(bitWidth);
525 return parser.getChecked<ConstantRangeAttr>(loc, parser.getContext(), lower,
526 upper);
527}
528
529void ConstantRangeAttr::print(AsmPrinter &printer) const {
530 printer << "<i" << getLower().getBitWidth() << ", " << getLower() << ", "
531 << getUpper() << ">";
532}
533
534LogicalResult
535ConstantRangeAttr::verify(llvm::function_ref<InFlightDiagnostic()> emitError,
536 APInt lower, APInt upper) {
537 if (lower.getBitWidth() != upper.getBitWidth())
538 return emitError()
539 << "expected lower and upper to have matching bitwidths but got "
540 << lower.getBitWidth() << " vs. " << upper.getBitWidth();
541 return success();
542}
543
544//===----------------------------------------------------------------------===//
545// TargetFeaturesAttr
546//===----------------------------------------------------------------------===//
547
548TargetFeaturesAttr TargetFeaturesAttr::get(MLIRContext *context,
549 llvm::ArrayRef<StringRef> features) {
550 return Base::get(context,
551 llvm::map_to_vector(features, [&](StringRef feature) {
552 return StringAttr::get(context, feature);
553 }));
554}
555
556TargetFeaturesAttr
557TargetFeaturesAttr::getChecked(function_ref<InFlightDiagnostic()> emitError,
558 MLIRContext *context,
559 llvm::ArrayRef<StringRef> features) {
560 return Base::getChecked(emitError, context,
561 llvm::map_to_vector(features, [&](StringRef feature) {
562 return StringAttr::get(context, feature);
563 }));
564}
565
566TargetFeaturesAttr TargetFeaturesAttr::get(MLIRContext *context,
567 StringRef targetFeatures) {
568 SmallVector<StringRef> features;
569 targetFeatures.split(features, ',', /*MaxSplit=*/-1,
570 /*KeepEmpty=*/false);
571 return get(context, features);
572}
573
574TargetFeaturesAttr
575TargetFeaturesAttr::getChecked(function_ref<InFlightDiagnostic()> emitError,
576 MLIRContext *context, StringRef targetFeatures) {
577 SmallVector<StringRef> features;
578 targetFeatures.split(features, ',', /*MaxSplit=*/-1,
579 /*KeepEmpty=*/false);
580 ArrayRef featuresRef(features);
581 return getChecked(emitError, context, featuresRef);
582}
583
584LogicalResult
585TargetFeaturesAttr::verify(function_ref<InFlightDiagnostic()> emitError,
586 llvm::ArrayRef<StringAttr> features) {
587 for (StringAttr featureAttr : features) {
588 if (!featureAttr || featureAttr.empty())
589 return emitError() << "target features can not be null or empty";
590 auto feature = featureAttr.strref();
591 if (feature[0] != '+' && feature[0] != '-')
592 return emitError() << "target features must start with '+' or '-'";
593 if (feature.contains(','))
594 return emitError() << "target features can not contain ','";
595 }
596 return success();
597}
598
599bool TargetFeaturesAttr::contains(StringAttr feature) const {
600 if (nullOrEmpty())
601 return false;
602 // Note: Using StringAttr does pointer comparisons.
603 return llvm::is_contained(getFeatures(), feature);
604}
605
606bool TargetFeaturesAttr::contains(StringRef feature) const {
607 if (nullOrEmpty())
608 return false;
609 return llvm::is_contained(getFeatures(), feature);
610}
611
612std::string TargetFeaturesAttr::getFeaturesString() const {
613 std::string featuresString;
614 llvm::raw_string_ostream ss(featuresString);
615 llvm::interleave(
616 getFeatures(), ss, [&](auto &feature) { ss << feature.strref(); }, ",");
617 return featuresString;
618}
619
620TargetFeaturesAttr TargetFeaturesAttr::featuresAt(Operation *op) {
621 auto parentFunction = op->getParentOfType<FunctionOpInterface>();
622 if (!parentFunction)
623 return {};
624 Operation *parentOp = parentFunction.getOperation();
625 if (auto llvmFunc = dyn_cast<LLVMFuncOp>(parentOp))
626 return llvmFunc.getTargetFeaturesAttr();
627
628 // Dynamic operation definitions do not support direct inherent attribute
629 // lookup. Use the safe walker for other FunctionOpInterface implementations.
630 TargetFeaturesAttr targetFeatures;
631 parentOp->getName().walkInherentAttrs(
632 parentOp, [&](StringRef name, Attribute &attr) {
633 if (name == getAttributeName())
634 targetFeatures = dyn_cast<TargetFeaturesAttr>(attr);
635 });
636 if (targetFeatures)
637 return targetFeatures;
638 return parentOp->getDiscardableAttrOfType<TargetFeaturesAttr>(
639 getAttributeName());
640}
641
642FailureOr<Attribute> TargetFeaturesAttr::query(DataLayoutEntryKey key) {
643 auto stringKey = dyn_cast<StringAttr>(key);
644 if (!stringKey)
645 return failure();
646
647 if (contains(stringKey))
648 return UnitAttr::get(getContext());
649
650 if (contains((std::string("+") + stringKey.strref()).str()))
651 return BoolAttr::get(getContext(), true);
652
653 if (contains((std::string("-") + stringKey.strref()).str()))
654 return BoolAttr::get(getContext(), false);
655
656 return failure();
657}
658
659//===----------------------------------------------------------------------===//
660// TargetAttr
661//===----------------------------------------------------------------------===//
662
663FailureOr<::mlir::Attribute> TargetAttr::query(DataLayoutEntryKey key) {
664 if (auto stringAttrKey = dyn_cast<StringAttr>(key)) {
665 if (stringAttrKey.getValue() == "triple")
666 return getTriple();
667 if (stringAttrKey.getValue() == "chip")
668 return getChip();
669 if (stringAttrKey.getValue() == "features" && getFeatures())
670 return getFeatures();
671 }
672 return failure();
673}
674
675//===----------------------------------------------------------------------===//
676// ModuleFlagAttr
677//===----------------------------------------------------------------------===//
678
680 StringAttr key, Attribute value,
682 if (key == LLVMDialect::getModuleFlagKeyCGProfileName()) {
683 auto arrayAttr = dyn_cast<ArrayAttr>(value);
684 if ((!arrayAttr) || (!llvm::all_of(arrayAttr, [](Attribute attr) {
685 return isa<ModuleFlagCGProfileEntryAttr>(attr);
686 })))
687 return emitError()
688 << "'CG Profile' key expects an array of '#llvm.cgprofile_entry'";
689 return success();
690 }
691
692 if (key == LLVMDialect::getModuleFlagKeyProfileSummaryName()) {
693 if (!isa<ModuleFlagProfileSummaryAttr>(value))
694 return emitError() << "'ProfileSummary' key expects a "
695 "'#llvm.profile_summary' attribute";
696 return success();
697 }
698
699 if (isa<IntegerAttr, StringAttr, IntrinsicIntegerAttrInterface>(value))
700 return success();
701
702 // Allow non-empty ArrayAttr of StringAttrs to represent MDTuples of
703 // MDStrings (e.g. the "riscv-isa" module flag). Integer values within
704 // MDTuples are not handled here because integer module flags are encoded as
705 // ConstantAsMetadata at the top level (not as MDTuples), so no known use
706 // case requires an array-of-integers representation.
707 if (auto arrayAttr = dyn_cast<ArrayAttr>(value))
708 if (!arrayAttr.empty() &&
709 llvm::all_of(arrayAttr, [](Attribute a) { return isa<StringAttr>(a); }))
710 return success();
711
712 return emitError()
713 << "only integer, integer-like dialect attributes, string, "
714 "and string-array values are currently supported for "
715 "unknown key '"
716 << key << "'";
717}
718
719LogicalResult
720ModuleFlagAttr::verify(function_ref<InFlightDiagnostic()> emitError,
721 LLVM::ModFlagBehavior flagBehavior, StringAttr key,
722 Attribute value) {
724}
725
726ModFlagBehavior ModuleFlagAttr::getModuleFlagBehavior() const {
727 return getBehavior();
728}
729
730StringAttr ModuleFlagAttr::getModuleFlagKey() const { return getKey(); }
731
732Attribute ModuleFlagAttr::getModuleFlagValue() const { return getValue(); }
733
734//===----------------------------------------------------------------------===//
735// MDAddrSpaceCastAttr
736//===----------------------------------------------------------------------===//
737
738LogicalResult
739MDAddrSpaceCastAttr::verify(function_ref<InFlightDiagnostic()> emitError,
740 Attribute arg, unsigned addressSpace) {
741 // `addrspacecast` operates on pointers, so the operand must be a metadata
742 // attribute that models a pointer-typed constant.
743 if (!isa<MDGlobalValueAttr, MDNullAttr, MDAddrSpaceCastAttr>(arg))
744 return emitError() << "expected #llvm.md_global_value, #llvm.md_null, or "
745 "#llvm.md_addrspacecast operand, but got "
746 << arg;
747 return success();
748}
749
750//===----------------------------------------------------------------------===//
751// DIEnumeratorAttr
752//===----------------------------------------------------------------------===//
753
754LogicalResult
755DIEnumeratorAttr::verify(function_ref<InFlightDiagnostic()> emitError,
756 StringAttr name, IntegerAttr value, bool isUnsigned) {
757 if (!value.getType().isSignlessInteger())
758 return emitError() << "expected signless integer type for 'value'";
759 return success();
760}
return success()
static llvm::DISourceLanguageName getSourceLanguage(DICompileUnitAttr attr)
static StringRef getFixedMetadataKindName(unsigned kind)
static void printExpressionArg(AsmPrinter &printer, uint64_t opcode, ArrayRef< uint64_t > args)
Prints DWARF expression arguments with respect to the specific DWARF operation.
static ParseResult parseExpressionArg(AsmParser &parser, uint64_t opcode, SmallVector< uint64_t > &args)
Parses DWARF expression arguments with respect to the DWARF operation opcode.
static ParseResult parseSourceLanguage(AsmParser &parser, DISourceLanguageNameAttr &language)
Parses a source language from either the historical inline DW_LANG_* syntax or a nested DISourceLangu...
static constexpr unsigned kReservedFunctionMetadataKinds[]
static void printSourceLanguage(AsmPrinter &printer, DISourceLanguageNameAttr language)
Prints an unversioned source language without a dialect using the historical inline DW_LANG_* syntax.
b getContext())
static bool contains(SMRange range, SMLoc loc)
Returns true if the given range contains the given source location.
static arith::FastMathFlags getFlags(arith::FastMathFlagsAttr fastmath)
Returns the flags held by fastmath, or none if it is null.
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
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.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseLess()=0
Parse a '<' token.
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 ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printAttribute(Attribute attr)
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
static BoolAttr get(MLIRContext *context, bool value)
This class represents a diagnostic that is inflight and set to be reported.
This class represents a LLVM attribute that describes a local debug info scope.
Definition LLVMAttrs.h:48
static bool classof(Attribute attr)
Support LLVM type casting.
constexpr Attribute()=default
static bool classof(Attribute attr)
This class represents a LLVM attribute that describes a debug info scope.
Definition LLVMAttrs.h:38
static bool classof(Attribute attr)
Support LLVM type casting.
This class represents a LLVM attribute that describes a debug info type.
Definition LLVMAttrs.h:57
static bool classof(Attribute attr)
Support LLVM type casting.
static bool classof(Attribute attr)
Support LLVM type casting.
static bool classof(Attribute attr)
Support LLVM type casting.
constexpr Attribute()=default
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void walkInherentAttrs(Operation *op, InherentAttrVisitor visitor) const
Visit the inherent attributes stored in the properties of op.
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
Definition Operation.h:495
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
LogicalResult verifyModuleFlagValue(StringAttr key, Attribute value, function_ref< InFlightDiagnostic()> emitError)
Verifies that a module flag value can be exported to LLVM IR.
bool isValidLoadStoreImpl(Type type, ptr::AtomicOrdering ordering, std::optional< int64_t > alignment, const ::mlir::DataLayout *dataLayout, function_ref< InFlightDiagnostic()> emitError)
Checks whether the given type is an LLVM type that can be loaded or stored.
Definition LLVMAttrs.cpp:59
bool isLoadableType(Type type)
Returns true if the given type is a loadable type compatible with the LLVM dialect.
bool isTypeCompatibleWithAtomicOp(Type type, const DataLayout &dataLayout)
Returns true if the given type is supported by atomic operations.
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
llvm::PointerUnion< Type, StringAttr > DataLayoutEntryKey
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.
auto getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Ts &&...params)
Helper method analogous to get, but uses getChecked when available to allow graceful failure on inval...
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155