MLIR 24.0.0git
LLVMDialect.cpp
Go to the documentation of this file.
1//===- LLVMDialect.cpp - LLVM IR dialect 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 LLVM IR dialect in MLIR and registers it. The ops are
10// defined by the source file of their op partition, e.g. LLVMArithOps.cpp.
11//
12//===----------------------------------------------------------------------===//
13
15
16#include "LLVMDialectBytecode.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/Support/Error.h"
24
25using namespace mlir;
26using namespace mlir::LLVM;
27
28#include "mlir/Dialect/LLVMIR/LLVMOpsDialect.cpp.inc"
29
30//===----------------------------------------------------------------------===//
31// LLVMDialect initialization, type parsing, and registration.
32//===----------------------------------------------------------------------===//
33
34namespace {
35struct LLVMSCFToControlFlowInterface : SCFToControlFlowDialectInterface {
36 using SCFToControlFlowDialectInterface::SCFToControlFlowDialectInterface;
37
38 bool shouldPropagateLoopAttribute(NamedAttribute attr) const override {
39 return isa<LoopAnnotationAttr>(attr.getValue());
40 }
41};
42} // namespace
43
44void LLVMDialect::initialize() {
45 addInterfaces<LLVMSCFToControlFlowInterface>();
46
47 // clang-format off
48 addTypes<LLVMVoidType,
49 LLVMLabelType,
50 LLVMMetadataType>();
51 // clang-format on
52
53 // Support unknown operations because not all LLVM operations are registered.
54 allowUnknownOperations();
55 declarePromisedInterface<DialectInlinerInterface, LLVMDialect>();
57}
58
59LogicalResult LLVMDialect::verifyDataLayoutString(
60 StringRef descr, llvm::function_ref<void(const Twine &)> reportError) {
61 llvm::Expected<llvm::DataLayout> maybeDataLayout =
62 llvm::DataLayout::parse(descr);
63 if (maybeDataLayout)
64 return success();
65
66 std::string message;
67 llvm::raw_string_ostream messageStream(message);
68 llvm::logAllUnhandledErrors(maybeDataLayout.takeError(), messageStream);
69 reportError("invalid data layout descriptor: " + message);
70 return failure();
71}
72
73/// Verify LLVM dialect attributes.
74LogicalResult LLVMDialect::verifyOperationAttribute(Operation *op,
75 NamedAttribute attr) {
76 // If the data layout attribute is present, it must use the LLVM data layout
77 // syntax. Try parsing it and report errors in case of failure. Users of this
78 // attribute may assume it is well-formed and can pass it to the (asserting)
79 // llvm::DataLayout constructor.
80 if (attr.getName() != LLVM::LLVMDialect::getDataLayoutAttrName())
81 return success();
82 if (auto stringAttr = llvm::dyn_cast<StringAttr>(attr.getValue()))
83 return verifyDataLayoutString(
84 stringAttr.getValue(),
85 [op](const Twine &message) { op->emitOpError() << message.str(); });
86
87 return op->emitOpError() << "expected '"
88 << LLVM::LLVMDialect::getDataLayoutAttrName()
89 << "' to be a string attributes";
90}
91
92LogicalResult LLVMDialect::verifyParameterAttribute(Operation *op,
93 Type paramType,
94 NamedAttribute paramAttr) {
95 // LLVM attribute may be attached to a result of operation that has not been
96 // converted to LLVM dialect yet, so the result may have a type with unknown
97 // representation in LLVM dialect type space. In this case we cannot verify
98 // whether the attribute may be
99 bool verifyValueType = isCompatibleType(paramType);
100 StringAttr name = paramAttr.getName();
101
102 auto checkUnitAttrType = [&]() -> LogicalResult {
103 if (!llvm::isa<UnitAttr>(paramAttr.getValue()))
104 return op->emitError() << name << " should be a unit attribute";
105 return success();
106 };
107 auto checkTypeAttrType = [&]() -> LogicalResult {
108 if (!llvm::isa<TypeAttr>(paramAttr.getValue()))
109 return op->emitError() << name << " should be a type attribute";
110 return success();
111 };
112 auto checkIntegerAttrType = [&]() -> LogicalResult {
113 if (!llvm::isa<IntegerAttr>(paramAttr.getValue()))
114 return op->emitError() << name << " should be an integer attribute";
115 return success();
116 };
117 auto checkPointerType = [&]() -> LogicalResult {
118 if (!llvm::isa<LLVMPointerType>(paramType))
119 return op->emitError()
120 << name << " attribute attached to non-pointer LLVM type";
121 return success();
122 };
123 auto checkIntegerType = [&]() -> LogicalResult {
124 if (!llvm::isa<IntegerType>(paramType))
125 return op->emitError()
126 << name << " attribute attached to non-integer LLVM type";
127 return success();
128 };
129 auto checkPointerTypeMatches = [&]() -> LogicalResult {
130 if (failed(checkPointerType()))
131 return failure();
132
133 return success();
134 };
135
136 // Check a unit attribute that is attached to a pointer value.
137 if (name == LLVMDialect::getNoAliasAttrName() ||
138 name == LLVMDialect::getReadonlyAttrName() ||
139 name == LLVMDialect::getReadnoneAttrName() ||
140 name == LLVMDialect::getWriteOnlyAttrName() ||
141 name == LLVMDialect::getNestAttrName() ||
142 name == LLVMDialect::getNoCaptureAttrName() ||
143 name == LLVMDialect::getNoFreeAttrName() ||
144 name == LLVMDialect::getNoFreeObjAttrName() ||
145 name == LLVMDialect::getNonNullAttrName()) {
146 if (failed(checkUnitAttrType()))
147 return failure();
148 if (verifyValueType && failed(checkPointerType()))
149 return failure();
150 return success();
151 }
152
153 // Check a type attribute that is attached to a pointer value.
154 if (name == LLVMDialect::getStructRetAttrName() ||
155 name == LLVMDialect::getByValAttrName() ||
156 name == LLVMDialect::getByRefAttrName() ||
157 name == LLVMDialect::getElementTypeAttrName() ||
158 name == LLVMDialect::getInAllocaAttrName() ||
159 name == LLVMDialect::getPreallocatedAttrName()) {
160 if (failed(checkTypeAttrType()))
161 return failure();
162 if (verifyValueType && failed(checkPointerTypeMatches()))
163 return failure();
164 return success();
165 }
166
167 // Check a unit attribute that is attached to an integer value.
168 if (name == LLVMDialect::getSExtAttrName() ||
169 name == LLVMDialect::getZExtAttrName() ||
170 name == LLVMDialect::getNoExtAttrName()) {
171 if (failed(checkUnitAttrType()))
172 return failure();
173 if (verifyValueType && failed(checkIntegerType()))
174 return failure();
175 return success();
176 }
177
178 // Check an integer attribute that is attached to a pointer value.
179 if (name == LLVMDialect::getAlignAttrName() ||
180 name == LLVMDialect::getDereferenceableAttrName() ||
181 name == LLVMDialect::getDereferenceableOrNullAttrName()) {
182 if (failed(checkIntegerAttrType()))
183 return failure();
184 if (verifyValueType && failed(checkPointerType()))
185 return failure();
186 return success();
187 }
188
189 // Check an integer attribute that is attached to a pointer value.
190 if (name == LLVMDialect::getStackAlignmentAttrName()) {
191 if (failed(checkIntegerAttrType()))
192 return failure();
193 return success();
194 }
195
196 // Check a unit attribute that can be attached to arbitrary types.
197 if (name == LLVMDialect::getNoUndefAttrName() ||
198 name == LLVMDialect::getInRegAttrName() ||
199 name == LLVMDialect::getReturnedAttrName())
200 return checkUnitAttrType();
201
202 return success();
203}
204
205/// Verify LLVMIR function argument attributes.
206LogicalResult LLVMDialect::verifyRegionArgAttribute(Operation *op,
207 unsigned regionIdx,
208 unsigned argIdx,
209 NamedAttribute argAttr) {
210 auto funcOp = dyn_cast<FunctionOpInterface>(op);
211 if (!funcOp)
212 return success();
213 Type argType = funcOp.getArgumentTypes()[argIdx];
214
215 return verifyParameterAttribute(op, argType, argAttr);
216}
217
218LogicalResult LLVMDialect::verifyRegionResultAttribute(Operation *op,
219 unsigned regionIdx,
220 unsigned resIdx,
221 NamedAttribute resAttr) {
222 auto funcOp = dyn_cast<FunctionOpInterface>(op);
223 if (!funcOp)
224 return success();
225 Type resType = funcOp.getResultTypes()[resIdx];
226
227 // Check to see if this function has a void return with a result attribute
228 // to it. It isn't clear what semantics we would assign to that.
229 if (llvm::isa<LLVMVoidType>(resType))
230 return op->emitError() << "cannot attach result attributes to functions "
231 "with a void return";
232
233 // Check to see if this attribute is allowed as a result attribute. Only
234 // explicitly forbidden LLVM attributes will cause an error.
235 auto name = resAttr.getName();
236 if (name == LLVMDialect::getAllocAlignAttrName() ||
237 name == LLVMDialect::getAllocatedPointerAttrName() ||
238 name == LLVMDialect::getByValAttrName() ||
239 name == LLVMDialect::getByRefAttrName() ||
240 name == LLVMDialect::getInAllocaAttrName() ||
241 name == LLVMDialect::getNestAttrName() ||
242 name == LLVMDialect::getNoCaptureAttrName() ||
243 name == LLVMDialect::getNoFreeAttrName() ||
244 name == LLVMDialect::getPreallocatedAttrName() ||
245 name == LLVMDialect::getReadnoneAttrName() ||
246 name == LLVMDialect::getReadonlyAttrName() ||
247 name == LLVMDialect::getReturnedAttrName() ||
248 name == LLVMDialect::getStackAlignmentAttrName() ||
249 name == LLVMDialect::getStructRetAttrName() ||
250 name == LLVMDialect::getWriteOnlyAttrName())
251 return op->emitError() << name << " is not a valid result attribute";
252 return verifyParameterAttribute(op, resType, resAttr);
253}
254
255Operation *LLVMDialect::materializeConstant(OpBuilder &builder, Attribute value,
256 Type type, Location loc) {
257 // If this was folded from an operation other than llvm.mlir.constant, it
258 // should be materialized as such. Note that an llvm.mlir.zero may fold into
259 // a builtin zero attribute and thus will materialize as a llvm.mlir.constant.
260 if (auto symbol = dyn_cast<FlatSymbolRefAttr>(value))
261 if (isa<LLVM::LLVMPointerType>(type))
262 return LLVM::AddressOfOp::create(builder, loc, type, symbol);
263 if (isa<LLVM::UndefAttr>(value))
264 return LLVM::UndefOp::create(builder, loc, type);
265 if (isa<LLVM::PoisonAttr>(value))
266 return LLVM::PoisonOp::create(builder, loc, type);
267 if (isa<LLVM::ZeroAttr>(value))
268 return LLVM::ZeroOp::create(builder, loc, type);
269 if (isa<LLVM::MDStringAttr, LLVM::MDConstantAttr, LLVM::MDGlobalValueAttr,
270 LLVM::MDNodeAttr>(value))
271 if (isa<LLVM::LLVMMetadataType>(type))
272 return LLVM::MetadataAsValueOp::create(builder, loc, type, value);
273 // Otherwise try materializing it as a regular llvm.mlir.constant op.
274 return LLVM::ConstantOp::materialize(builder, value, type, loc);
275}
return success()
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
void addBytecodeInterface(LLVMDialect *dialect)
Add the interfaces necessary for encoding the LLVM dialect components in bytecode.
bool isCompatibleType(Type type)
Returns true if the given type is compatible with the LLVM dialect.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.