MLIR 24.0.0git
LLVMTerminatorOps.cpp
Go to the documentation of this file.
1//===- LLVMTerminatorOps.cpp - LLVM dialect terminator 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 `Terminator` of the LLVM dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "IR/LLVMOps.h"
19#include "mlir/IR/Builders.h"
22#include "llvm/ADT/STLExtras.h"
23
24#include <optional>
25
26using namespace mlir;
27using namespace mlir::LLVM;
28
29//===----------------------------------------------------------------------===//
30// LLVM::BrOp
31//===----------------------------------------------------------------------===//
32
33LogicalResult BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
34 // Merge a branch to a block that has a single predecessor, the same
35 // transform as cf::BranchOp; the successor block is inlined into the
36 // branch block and the branch is erased.
37 Block *succ = op.getDest();
38 Block *opParent = op->getBlock();
39 if (succ == opParent || !llvm::hasSingleElement(succ->getPredecessors()))
40 return failure();
41
42 // If any branch operand is itself a block argument of the successor,
43 // merging would replace uses of that argument with itself and leave
44 // dangling uses after the successor block is erased.
45 for (Value operand : op.getDestOperands())
46 if (auto arg = dyn_cast<BlockArgument>(operand))
47 if (arg.getOwner() == succ)
48 return failure();
49
50 // The successor must be mergeable. A landing pad must stay the first
51 // operation of its block, a block tag means the block address is taken,
52 // and merging would silently drop a loop annotation on the branch.
53 if (!succ->empty()) {
54 if (isa<LandingpadOp>(succ->front()))
55 return failure();
56 if (llvm::any_of(succ->without_terminator(),
57 [](Operation &inner) { return isa<BlockTagOp>(inner); }))
58 return failure();
59 }
60 if (op.getLoopAnnotationAttr())
61 return failure();
62
63 SmallVector<Value> brOperands(op.getDestOperands());
64 rewriter.eraseOp(op);
65 rewriter.mergeBlocks(succ, opParent, brOperands);
66 return success();
67}
68
69SuccessorOperands BrOp::getSuccessorOperands(unsigned index) {
70 assert(index == 0 && "invalid successor index");
71 return SuccessorOperands(getDestOperandsMutable());
72}
73
74//===----------------------------------------------------------------------===//
75// LLVM::CondBrOp
76//===----------------------------------------------------------------------===//
77
78SuccessorOperands CondBrOp::getSuccessorOperands(unsigned index) {
79 assert(index < getNumSuccessors() && "invalid successor index");
80 return SuccessorOperands(index == 0 ? getTrueDestOperandsMutable()
81 : getFalseDestOperandsMutable());
82}
83
84void CondBrOp::build(OpBuilder &builder, OperationState &result,
85 Value condition, Block *trueDest, ValueRange trueOperands,
86 Block *falseDest, ValueRange falseOperands,
87 std::optional<std::pair<uint32_t, uint32_t>> weights) {
88 DenseI32ArrayAttr weightsAttr;
89 if (weights)
90 weightsAttr =
91 builder.getDenseI32ArrayAttr({static_cast<int32_t>(weights->first),
92 static_cast<int32_t>(weights->second)});
93
94 build(builder, result, condition, trueOperands, falseOperands, weightsAttr,
95 /*loop_annotation=*/{}, trueDest, falseDest);
96}
97
98//===----------------------------------------------------------------------===//
99// LLVM::SwitchOp
100//===----------------------------------------------------------------------===//
101
102void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value,
103 Block *defaultDestination, ValueRange defaultOperands,
104 DenseIntElementsAttr caseValues,
105 BlockRange caseDestinations,
106 ArrayRef<ValueRange> caseOperands,
107 ArrayRef<int32_t> branchWeights) {
108 DenseI32ArrayAttr weightsAttr;
109 if (!branchWeights.empty())
110 weightsAttr = builder.getDenseI32ArrayAttr(branchWeights);
111
112 build(builder, result, value, defaultOperands, caseOperands, caseValues,
113 weightsAttr, defaultDestination, caseDestinations);
114}
115
116void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value,
117 Block *defaultDestination, ValueRange defaultOperands,
118 ArrayRef<APInt> caseValues, BlockRange caseDestinations,
119 ArrayRef<ValueRange> caseOperands,
120 ArrayRef<int32_t> branchWeights) {
121 DenseIntElementsAttr caseValuesAttr;
122 if (!caseValues.empty()) {
123 ShapedType caseValueType = VectorType::get(
124 static_cast<int64_t>(caseValues.size()), value.getType());
125 caseValuesAttr = DenseIntElementsAttr::get(caseValueType, caseValues);
126 }
127
128 build(builder, result, value, defaultDestination, defaultOperands,
129 caseValuesAttr, caseDestinations, caseOperands, branchWeights);
130}
131
132void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value,
133 Block *defaultDestination, ValueRange defaultOperands,
134 ArrayRef<int32_t> caseValues, BlockRange caseDestinations,
135 ArrayRef<ValueRange> caseOperands,
136 ArrayRef<int32_t> branchWeights) {
137 DenseIntElementsAttr caseValuesAttr;
138 if (!caseValues.empty()) {
139 ShapedType caseValueType = VectorType::get(
140 static_cast<int64_t>(caseValues.size()), value.getType());
141 caseValuesAttr = DenseIntElementsAttr::get(caseValueType, caseValues);
142 }
143
144 build(builder, result, value, defaultDestination, defaultOperands,
145 caseValuesAttr, caseDestinations, caseOperands, branchWeights);
146}
147
148/// <cases> ::= `[` (case (`,` case )* )? `]`
149/// <case> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
151 OpAsmParser &parser, Type flagType, DenseIntElementsAttr &caseValues,
152 SmallVectorImpl<Block *> &caseDestinations,
154 SmallVectorImpl<SmallVector<Type>> &caseOperandTypes) {
155 if (failed(parser.parseLSquare()))
156 return failure();
157 if (succeeded(parser.parseOptionalRSquare()))
158 return success();
159 SmallVector<APInt> values;
160 unsigned bitWidth = flagType.getIntOrFloatBitWidth();
161 auto parseCase = [&]() {
162 int64_t value = 0;
163 if (failed(parser.parseInteger(value)))
164 return failure();
165 values.push_back(APInt(bitWidth, value, /*isSigned=*/true));
166
167 Block *destination;
169 SmallVector<Type> operandTypes;
170 if (parser.parseColon() || parser.parseSuccessor(destination))
171 return failure();
172 if (!parser.parseOptionalLParen()) {
173 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None) ||
174 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
175 return failure();
176 }
177 caseDestinations.push_back(destination);
178 caseOperands.emplace_back(operands);
179 caseOperandTypes.emplace_back(operandTypes);
180 return success();
181 };
182 if (failed(parser.parseCommaSeparatedList(parseCase)))
183 return failure();
184
185 ShapedType caseValueType =
186 VectorType::get(static_cast<int64_t>(values.size()), flagType);
187 caseValues = DenseIntElementsAttr::get(caseValueType, values);
188 return parser.parseRSquare();
189}
190
191void mlir::LLVM::printSwitchOpCases(OpAsmPrinter &p, SwitchOp op, Type flagType,
192 DenseIntElementsAttr caseValues,
193 SuccessorRange caseDestinations,
194 OperandRangeRange caseOperands,
195 const TypeRangeRange &caseOperandTypes) {
196 p << '[';
197 p.printNewline();
198 if (!caseValues) {
199 p << ']';
200 return;
201 }
202
203 size_t index = 0;
204 llvm::interleave(
205 llvm::zip(caseValues, caseDestinations),
206 [&](auto i) {
207 p << " ";
208 p << std::get<0>(i);
209 p << ": ";
210 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
211 },
212 [&] {
213 p << ',';
214 p.printNewline();
215 });
216 p.printNewline();
217 p << ']';
218}
219
220LogicalResult SwitchOp::verify() {
221 if ((!getCaseValues() && !getCaseDestinations().empty()) ||
222 (getCaseValues() &&
223 getCaseValues()->size() !=
224 static_cast<int64_t>(getCaseDestinations().size())))
225 return emitOpError("expects number of case values to match number of "
226 "case destinations");
227 if (getCaseValues() &&
228 getValue().getType() != getCaseValues()->getElementType())
229 return emitError("expects case value type to match condition value type");
230
231 // LLVM IR rejects a switch with a repeated case value.
232 if (getCaseValues()) {
233 llvm::SmallDenseMap<APInt, unsigned> firstCase;
234 for (auto [index, value] :
235 llvm::enumerate(getCaseValues()->getValues<APInt>())) {
236 auto [it, inserted] = firstCase.try_emplace(value, index);
237 if (inserted)
238 continue;
239 // Diagnostics cannot stream APInt directly, so print it into a buffer.
240 SmallString<32> valueStr;
241 llvm::raw_svector_ostream os(valueStr);
242 value.print(os, /*isSigned=*/true);
243 if (value.isNegative()) {
244 os << " (unsigned ";
245 value.print(os, /*isSigned=*/false);
246 os << ")";
247 }
248 return emitOpError() << "case value " << valueStr
249 << " is repeated (cases " << it->second << " and "
250 << index << ")";
251 }
252 }
253 return success();
254}
255
256SuccessorOperands SwitchOp::getSuccessorOperands(unsigned index) {
257 assert(index < getNumSuccessors() && "invalid successor index");
258 return SuccessorOperands(index == 0 ? getDefaultOperandsMutable()
259 : getCaseOperandsMutable(index - 1));
260}
261
262//===----------------------------------------------------------------------===//
263// ReturnOp
264//===----------------------------------------------------------------------===//
265
266LogicalResult ReturnOp::verify() {
267 auto parent = (*this)->getParentOfType<LLVMFuncOp>();
268 if (!parent)
269 return success();
270
271 Type expectedType = parent.getFunctionType().getReturnType();
272 if (llvm::isa<LLVMVoidType>(expectedType)) {
273 if (!getArg())
274 return success();
275 InFlightDiagnostic diag = emitOpError("expected no operands");
276 diag.attachNote(parent->getLoc()) << "when returning from function";
277 return diag;
278 }
279 if (!getArg()) {
280 if (llvm::isa<LLVMVoidType>(expectedType))
281 return success();
282 InFlightDiagnostic diag = emitOpError("expected 1 operand");
283 diag.attachNote(parent->getLoc()) << "when returning from function";
284 return diag;
285 }
286 if (expectedType != getArg().getType()) {
287 InFlightDiagnostic diag = emitOpError("mismatching result types");
288 diag.attachNote(parent->getLoc()) << "when returning from function";
289 return diag;
290 }
291 return success();
292}
293
294//===----------------------------------------------------------------------===//
295// LLVM::IndirectBrOp
296//===----------------------------------------------------------------------===//
297
298SuccessorOperands IndirectBrOp::getSuccessorOperands(unsigned index) {
299 assert(index < getNumSuccessors() && "invalid successor index");
300 return SuccessorOperands(getSuccOperandsMutable()[index]);
301}
302
303void IndirectBrOp::build(OpBuilder &odsBuilder, OperationState &odsState,
304 Value addr, ArrayRef<ValueRange> succOperands,
305 BlockRange successors) {
306 odsState.addOperands(addr);
307 for (ValueRange range : succOperands)
308 odsState.addOperands(range);
309 SmallVector<int32_t> rangeSegments;
310 for (ValueRange range : succOperands)
311 rangeSegments.push_back(range.size());
312 odsState.getOrAddProperties<Properties>().indbr_operand_segments =
313 odsBuilder.getDenseI32ArrayAttr(rangeSegments);
314 odsState.addSuccessors(successors);
315}
316
318 OpAsmParser &parser, Type &flagType,
319 SmallVectorImpl<Block *> &succOperandBlocks,
321 SmallVectorImpl<SmallVector<Type>> &succOperandsTypes) {
322 if (failed(parser.parseCommaSeparatedList(
324 [&]() {
325 Block *destination = nullptr;
326 SmallVector<OpAsmParser::UnresolvedOperand> operands;
327 SmallVector<Type> operandTypes;
328
329 if (parser.parseSuccessor(destination).failed())
330 return failure();
331
332 if (succeeded(parser.parseOptionalLParen())) {
333 if (failed(parser.parseOperandList(
334 operands, OpAsmParser::Delimiter::None)) ||
335 failed(parser.parseColonTypeList(operandTypes)) ||
336 failed(parser.parseRParen()))
337 return failure();
338 }
339 succOperandBlocks.push_back(destination);
340 succOperands.emplace_back(operands);
341 succOperandsTypes.emplace_back(operandTypes);
342 return success();
343 },
344 "successor blocks")))
345 return failure();
346 return success();
347}
348
350 OpAsmPrinter &p, IndirectBrOp op, Type flagType, SuccessorRange succs,
351 OperandRangeRange succOperands, const TypeRangeRange &succOperandsTypes) {
352 p << "[";
353 llvm::interleave(
354 llvm::zip(succs, succOperands),
355 [&](auto i) {
356 p.printNewline();
357 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
358 },
359 [&] { p << ','; });
360 if (!succOperands.empty())
361 p.printNewline();
362 p << "]";
363}
364
365#define GET_OP_CLASSES
366#include "mlir/Dialect/LLVMIR/LLVMTerminatorOps.cpp.inc"
return success()
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
@ None
Zero or more operands with no delimiters.
@ Square
Square brackets surrounding zero or more operands.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
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 parseRParen()=0
Parse a ) token.
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseColon()=0
Parse a : token.
virtual ParseResult parseOptionalRSquare()=0
Parse a ] token if present.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
virtual void printNewline()
Print a newline and indent the printer to the start of the current operation/attribute/type.
This class provides an abstraction over the different types of ranges over Blocks.
Block represents an ordered list of Operations.
Definition Block.h:34
bool empty()
Definition Block.h:173
iterator_range< pred_iterator > getPredecessors()
Definition Block.h:250
Operation & front()
Definition Block.h:178
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Definition Block.h:222
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
An attribute that represents a reference to a dense integer vector or tensor object.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
This class represents a diagnostic that is inflight and set to be reported.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseSuccessor(Block *&dest)=0
Parse a single operation successor.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printSuccessorAndUseList(Block *successor, ValueRange succOperands)=0
Print the successor and its operands.
This class helps build Operations.
Definition Builders.h:210
This class represents a contiguous range of operand ranges, e.g.
Definition ValueRange.h:85
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
This class models how operands are forwarded to block arguments in control flow.
This class implements the successor iterators for Block.
This class provides an abstraction for a range of TypeRange.
Definition TypeRange.h:107
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
void print(raw_ostream &os) const
Type getType() const
Return the type of this value.
Definition Value.h:105
void printSwitchOpCases(mlir::OpAsmPrinter &p, mlir::LLVM::SwitchOp op, mlir::Type flagType, mlir::DenseIntElementsAttr caseValues, mlir::SuccessorRange caseDestinations, mlir::OperandRangeRange caseOperands, const mlir::TypeRangeRange &caseOperandTypes)
void printIndirectBrOpSucessors(mlir::OpAsmPrinter &p, mlir::LLVM::IndirectBrOp op, mlir::Type flagType, mlir::SuccessorRange succs, mlir::OperandRangeRange succOperands, const mlir::TypeRangeRange &succOperandsTypes)
mlir::ParseResult parseIndirectBrOpSucessors(mlir::OpAsmParser &parser, mlir::Type &flagType, mlir::SmallVectorImpl< mlir::Block * > &succOperandBlocks, mlir::SmallVectorImpl< mlir::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &succOperands, mlir::SmallVectorImpl< mlir::SmallVector< mlir::Type > > &succOperandsTypes)
mlir::ParseResult parseSwitchOpCases(mlir::OpAsmParser &parser, mlir::Type flagType, mlir::DenseIntElementsAttr &caseValues, mlir::SmallVectorImpl< mlir::Block * > &caseDestinations, mlir::SmallVectorImpl< mlir::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &caseOperands, mlir::SmallVectorImpl< mlir::SmallVector< mlir::Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
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.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) the properties of the provided type to be set on the operation on creation.
void addOperands(ValueRange newOperands)
void addSuccessors(Block *successor)
Adds a successor to the operation sate. successor must not be null.