1 //===- LLVMDialect.cpp - LLVM IR Ops and 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 types and operation details for the LLVM IR dialect in
10 // MLIR, and the LLVM IR dialect.  It also registers the dialect.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
14 #include "TypeDetail.h"
15 #include "mlir/Dialect/LLVMIR/LLVMTypes.h"
16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/BuiltinOps.h"
18 #include "mlir/IR/BuiltinTypes.h"
19 #include "mlir/IR/DialectImplementation.h"
20 #include "mlir/IR/FunctionImplementation.h"
21 #include "mlir/IR/MLIRContext.h"
22 
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/TypeSwitch.h"
25 #include "llvm/AsmParser/Parser.h"
26 #include "llvm/Bitcode/BitcodeReader.h"
27 #include "llvm/Bitcode/BitcodeWriter.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Mutex.h"
32 #include "llvm/Support/SourceMgr.h"
33 
34 #include <iostream>
35 
36 using namespace mlir;
37 using namespace mlir::LLVM;
38 
39 static constexpr const char kVolatileAttrName[] = "volatile_";
40 static constexpr const char kNonTemporalAttrName[] = "nontemporal";
41 
42 #include "mlir/Dialect/LLVMIR/LLVMOpsEnums.cpp.inc"
43 #include "mlir/Dialect/LLVMIR/LLVMOpsInterfaces.cpp.inc"
44 #define GET_ATTRDEF_CLASSES
45 #include "mlir/Dialect/LLVMIR/LLVMOpsAttrDefs.cpp.inc"
46 
47 static auto processFMFAttr(ArrayRef<NamedAttribute> attrs) {
48   SmallVector<NamedAttribute, 8> filteredAttrs(
49       llvm::make_filter_range(attrs, [&](NamedAttribute attr) {
50         if (attr.first == "fastmathFlags") {
51           auto defAttr = FMFAttr::get(attr.second.getContext(), {});
52           return defAttr != attr.second;
53         }
54         return true;
55       }));
56   return filteredAttrs;
57 }
58 
59 static ParseResult parseLLVMOpAttrs(OpAsmParser &parser,
60                                     NamedAttrList &result) {
61   return parser.parseOptionalAttrDict(result);
62 }
63 
64 static void printLLVMOpAttrs(OpAsmPrinter &printer, Operation *op,
65                              DictionaryAttr attrs) {
66   printer.printOptionalAttrDict(processFMFAttr(attrs.getValue()));
67 }
68 
69 //===----------------------------------------------------------------------===//
70 // Printing/parsing for LLVM::CmpOp.
71 //===----------------------------------------------------------------------===//
72 static void printICmpOp(OpAsmPrinter &p, ICmpOp &op) {
73   p << op.getOperationName() << " \"" << stringifyICmpPredicate(op.predicate())
74     << "\" " << op.getOperand(0) << ", " << op.getOperand(1);
75   p.printOptionalAttrDict(op->getAttrs(), {"predicate"});
76   p << " : " << op.lhs().getType();
77 }
78 
79 static void printFCmpOp(OpAsmPrinter &p, FCmpOp &op) {
80   p << op.getOperationName() << " \"" << stringifyFCmpPredicate(op.predicate())
81     << "\" " << op.getOperand(0) << ", " << op.getOperand(1);
82   p.printOptionalAttrDict(processFMFAttr(op->getAttrs()), {"predicate"});
83   p << " : " << op.lhs().getType();
84 }
85 
86 // <operation> ::= `llvm.icmp` string-literal ssa-use `,` ssa-use
87 //                 attribute-dict? `:` type
88 // <operation> ::= `llvm.fcmp` string-literal ssa-use `,` ssa-use
89 //                 attribute-dict? `:` type
90 template <typename CmpPredicateType>
91 static ParseResult parseCmpOp(OpAsmParser &parser, OperationState &result) {
92   Builder &builder = parser.getBuilder();
93 
94   StringAttr predicateAttr;
95   OpAsmParser::OperandType lhs, rhs;
96   Type type;
97   llvm::SMLoc predicateLoc, trailingTypeLoc;
98   if (parser.getCurrentLocation(&predicateLoc) ||
99       parser.parseAttribute(predicateAttr, "predicate", result.attributes) ||
100       parser.parseOperand(lhs) || parser.parseComma() ||
101       parser.parseOperand(rhs) ||
102       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
103       parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type) ||
104       parser.resolveOperand(lhs, type, result.operands) ||
105       parser.resolveOperand(rhs, type, result.operands))
106     return failure();
107 
108   // Replace the string attribute `predicate` with an integer attribute.
109   int64_t predicateValue = 0;
110   if (std::is_same<CmpPredicateType, ICmpPredicate>()) {
111     Optional<ICmpPredicate> predicate =
112         symbolizeICmpPredicate(predicateAttr.getValue());
113     if (!predicate)
114       return parser.emitError(predicateLoc)
115              << "'" << predicateAttr.getValue()
116              << "' is an incorrect value of the 'predicate' attribute";
117     predicateValue = static_cast<int64_t>(predicate.getValue());
118   } else {
119     Optional<FCmpPredicate> predicate =
120         symbolizeFCmpPredicate(predicateAttr.getValue());
121     if (!predicate)
122       return parser.emitError(predicateLoc)
123              << "'" << predicateAttr.getValue()
124              << "' is an incorrect value of the 'predicate' attribute";
125     predicateValue = static_cast<int64_t>(predicate.getValue());
126   }
127 
128   result.attributes.set("predicate",
129                         parser.getBuilder().getI64IntegerAttr(predicateValue));
130 
131   // The result type is either i1 or a vector type <? x i1> if the inputs are
132   // vectors.
133   Type resultType = IntegerType::get(builder.getContext(), 1);
134   if (!isCompatibleType(type))
135     return parser.emitError(trailingTypeLoc,
136                             "expected LLVM dialect-compatible type");
137   if (LLVM::isCompatibleVectorType(type))
138     resultType = LLVM::getFixedVectorType(
139         resultType, LLVM::getVectorNumElements(type).getFixedValue());
140   assert(!type.isa<LLVM::LLVMScalableVectorType>() &&
141          "unhandled scalable vector");
142 
143   result.addTypes({resultType});
144   return success();
145 }
146 
147 //===----------------------------------------------------------------------===//
148 // Printing/parsing for LLVM::AllocaOp.
149 //===----------------------------------------------------------------------===//
150 
151 static void printAllocaOp(OpAsmPrinter &p, AllocaOp &op) {
152   auto elemTy = op.getType().cast<LLVM::LLVMPointerType>().getElementType();
153 
154   auto funcTy = FunctionType::get(op.getContext(), {op.arraySize().getType()},
155                                   {op.getType()});
156 
157   p << op.getOperationName() << ' ' << op.arraySize() << " x " << elemTy;
158   if (op.alignment().hasValue() && *op.alignment() != 0)
159     p.printOptionalAttrDict(op->getAttrs());
160   else
161     p.printOptionalAttrDict(op->getAttrs(), {"alignment"});
162   p << " : " << funcTy;
163 }
164 
165 // <operation> ::= `llvm.alloca` ssa-use `x` type attribute-dict?
166 //                 `:` type `,` type
167 static ParseResult parseAllocaOp(OpAsmParser &parser, OperationState &result) {
168   OpAsmParser::OperandType arraySize;
169   Type type, elemType;
170   llvm::SMLoc trailingTypeLoc;
171   if (parser.parseOperand(arraySize) || parser.parseKeyword("x") ||
172       parser.parseType(elemType) ||
173       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
174       parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type))
175     return failure();
176 
177   Optional<NamedAttribute> alignmentAttr =
178       result.attributes.getNamed("alignment");
179   if (alignmentAttr.hasValue()) {
180     auto alignmentInt = alignmentAttr.getValue().second.dyn_cast<IntegerAttr>();
181     if (!alignmentInt)
182       return parser.emitError(parser.getNameLoc(),
183                               "expected integer alignment");
184     if (alignmentInt.getValue().isNullValue())
185       result.attributes.erase("alignment");
186   }
187 
188   // Extract the result type from the trailing function type.
189   auto funcType = type.dyn_cast<FunctionType>();
190   if (!funcType || funcType.getNumInputs() != 1 ||
191       funcType.getNumResults() != 1)
192     return parser.emitError(
193         trailingTypeLoc,
194         "expected trailing function type with one argument and one result");
195 
196   if (parser.resolveOperand(arraySize, funcType.getInput(0), result.operands))
197     return failure();
198 
199   result.addTypes({funcType.getResult(0)});
200   return success();
201 }
202 
203 //===----------------------------------------------------------------------===//
204 // LLVM::BrOp
205 //===----------------------------------------------------------------------===//
206 
207 Optional<MutableOperandRange>
208 BrOp::getMutableSuccessorOperands(unsigned index) {
209   assert(index == 0 && "invalid successor index");
210   return destOperandsMutable();
211 }
212 
213 //===----------------------------------------------------------------------===//
214 // LLVM::CondBrOp
215 //===----------------------------------------------------------------------===//
216 
217 Optional<MutableOperandRange>
218 CondBrOp::getMutableSuccessorOperands(unsigned index) {
219   assert(index < getNumSuccessors() && "invalid successor index");
220   return index == 0 ? trueDestOperandsMutable() : falseDestOperandsMutable();
221 }
222 
223 //===----------------------------------------------------------------------===//
224 // LLVM::SwitchOp
225 //===----------------------------------------------------------------------===//
226 
227 void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value,
228                      Block *defaultDestination, ValueRange defaultOperands,
229                      ArrayRef<int32_t> caseValues, BlockRange caseDestinations,
230                      ArrayRef<ValueRange> caseOperands,
231                      ArrayRef<int32_t> branchWeights) {
232   SmallVector<Value> flattenedCaseOperands;
233   SmallVector<int32_t> caseOperandOffsets;
234   int32_t offset = 0;
235   for (ValueRange operands : caseOperands) {
236     flattenedCaseOperands.append(operands.begin(), operands.end());
237     caseOperandOffsets.push_back(offset);
238     offset += operands.size();
239   }
240   ElementsAttr caseValuesAttr;
241   if (!caseValues.empty())
242     caseValuesAttr = builder.getI32VectorAttr(caseValues);
243   ElementsAttr caseOperandOffsetsAttr;
244   if (!caseOperandOffsets.empty())
245     caseOperandOffsetsAttr = builder.getI32VectorAttr(caseOperandOffsets);
246 
247   ElementsAttr weightsAttr;
248   if (!branchWeights.empty())
249     weightsAttr = builder.getI32VectorAttr(llvm::to_vector<4>(branchWeights));
250 
251   build(builder, result, value, defaultOperands, flattenedCaseOperands,
252         caseValuesAttr, caseOperandOffsetsAttr, weightsAttr, defaultDestination,
253         caseDestinations);
254 }
255 
256 /// <cases> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
257 ///             ( `,` integer `:` bb-id (`(` ssa-use-and-type-list `)`)? )?
258 static ParseResult
259 parseSwitchOpCases(OpAsmParser &parser, ElementsAttr &caseValues,
260                    SmallVectorImpl<Block *> &caseDestinations,
261                    SmallVectorImpl<OpAsmParser::OperandType> &caseOperands,
262                    SmallVectorImpl<Type> &caseOperandTypes,
263                    ElementsAttr &caseOperandOffsets) {
264   SmallVector<int32_t> values;
265   SmallVector<int32_t> offsets;
266   int32_t value, offset = 0;
267   do {
268     OptionalParseResult integerParseResult = parser.parseOptionalInteger(value);
269     if (values.empty() && !integerParseResult.hasValue())
270       return success();
271 
272     if (!integerParseResult.hasValue() || integerParseResult.getValue())
273       return failure();
274     values.push_back(value);
275 
276     Block *destination;
277     SmallVector<OpAsmParser::OperandType> operands;
278     if (parser.parseColon() || parser.parseSuccessor(destination))
279       return failure();
280     if (!parser.parseOptionalLParen()) {
281       if (parser.parseRegionArgumentList(operands) ||
282           parser.parseColonTypeList(caseOperandTypes) || parser.parseRParen())
283         return failure();
284     }
285     caseDestinations.push_back(destination);
286     caseOperands.append(operands.begin(), operands.end());
287     offsets.push_back(offset);
288     offset += operands.size();
289   } while (!parser.parseOptionalComma());
290 
291   Builder &builder = parser.getBuilder();
292   caseValues = builder.getI32VectorAttr(values);
293   caseOperandOffsets = builder.getI32VectorAttr(offsets);
294 
295   return success();
296 }
297 
298 static void printSwitchOpCases(OpAsmPrinter &p, SwitchOp op,
299                                ElementsAttr caseValues,
300                                SuccessorRange caseDestinations,
301                                OperandRange caseOperands,
302                                TypeRange caseOperandTypes,
303                                ElementsAttr caseOperandOffsets) {
304   if (!caseValues)
305     return;
306 
307   size_t index = 0;
308   llvm::interleave(
309       llvm::zip(caseValues.cast<DenseIntElementsAttr>(), caseDestinations),
310       [&](auto i) {
311         p << "  ";
312         p << std::get<0>(i).getLimitedValue();
313         p << ": ";
314         p.printSuccessorAndUseList(std::get<1>(i), op.getCaseOperands(index++));
315       },
316       [&] {
317         p << ',';
318         p.printNewline();
319       });
320   p.printNewline();
321 }
322 
323 static LogicalResult verify(SwitchOp op) {
324   if ((!op.case_values() && !op.caseDestinations().empty()) ||
325       (op.case_values() &&
326        op.case_values()->size() !=
327            static_cast<int64_t>(op.caseDestinations().size())))
328     return op.emitOpError("expects number of case values to match number of "
329                           "case destinations");
330   if (op.branch_weights() &&
331       op.branch_weights()->size() != op.getNumSuccessors())
332     return op.emitError("expects number of branch weights to match number of "
333                         "successors: ")
334            << op.branch_weights()->size() << " vs " << op.getNumSuccessors();
335   return success();
336 }
337 
338 OperandRange SwitchOp::getCaseOperands(unsigned index) {
339   return getCaseOperandsMutable(index);
340 }
341 
342 MutableOperandRange SwitchOp::getCaseOperandsMutable(unsigned index) {
343   MutableOperandRange caseOperands = caseOperandsMutable();
344   if (!case_operand_offsets()) {
345     assert(caseOperands.size() == 0 &&
346            "non-empty case operands must have offsets");
347     return caseOperands;
348   }
349 
350   ElementsAttr offsets = case_operand_offsets().getValue();
351   assert(index < offsets.size() && "invalid case operand offset index");
352 
353   int64_t begin = offsets.getValue(index).cast<IntegerAttr>().getInt();
354   int64_t end = index + 1 == offsets.size()
355                     ? caseOperands.size()
356                     : offsets.getValue(index + 1).cast<IntegerAttr>().getInt();
357   return caseOperandsMutable().slice(begin, end - begin);
358 }
359 
360 Optional<MutableOperandRange>
361 SwitchOp::getMutableSuccessorOperands(unsigned index) {
362   assert(index < getNumSuccessors() && "invalid successor index");
363   return index == 0 ? defaultOperandsMutable()
364                     : getCaseOperandsMutable(index - 1);
365 }
366 
367 //===----------------------------------------------------------------------===//
368 // Builder, printer and parser for for LLVM::LoadOp.
369 //===----------------------------------------------------------------------===//
370 
371 static LogicalResult verifyAccessGroups(Operation *op) {
372   if (Attribute attribute =
373           op->getAttr(LLVMDialect::getAccessGroupsAttrName())) {
374     // The attribute is already verified to be a symbol ref array attribute via
375     // a constraint in the operation definition.
376     for (SymbolRefAttr accessGroupRef :
377          attribute.cast<ArrayAttr>().getAsRange<SymbolRefAttr>()) {
378       StringRef metadataName = accessGroupRef.getRootReference();
379       auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
380           op->getParentOp(), metadataName);
381       if (!metadataOp)
382         return op->emitOpError() << "expected '" << accessGroupRef
383                                  << "' to reference a metadata op";
384       StringRef accessGroupName = accessGroupRef.getLeafReference();
385       Operation *accessGroupOp =
386           SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
387       if (!accessGroupOp)
388         return op->emitOpError() << "expected '" << accessGroupRef
389                                  << "' to reference an access_group op";
390     }
391   }
392   return success();
393 }
394 
395 static LogicalResult verify(LoadOp op) {
396   return verifyAccessGroups(op.getOperation());
397 }
398 
399 void LoadOp::build(OpBuilder &builder, OperationState &result, Type t,
400                    Value addr, unsigned alignment, bool isVolatile,
401                    bool isNonTemporal) {
402   result.addOperands(addr);
403   result.addTypes(t);
404   if (isVolatile)
405     result.addAttribute(kVolatileAttrName, builder.getUnitAttr());
406   if (isNonTemporal)
407     result.addAttribute(kNonTemporalAttrName, builder.getUnitAttr());
408   if (alignment != 0)
409     result.addAttribute("alignment", builder.getI64IntegerAttr(alignment));
410 }
411 
412 static void printLoadOp(OpAsmPrinter &p, LoadOp &op) {
413   p << op.getOperationName() << ' ';
414   if (op.volatile_())
415     p << "volatile ";
416   p << op.addr();
417   p.printOptionalAttrDict(op->getAttrs(), {kVolatileAttrName});
418   p << " : " << op.addr().getType();
419 }
420 
421 // Extract the pointee type from the LLVM pointer type wrapped in MLIR.  Return
422 // the resulting type wrapped in MLIR, or nullptr on error.
423 static Type getLoadStoreElementType(OpAsmParser &parser, Type type,
424                                     llvm::SMLoc trailingTypeLoc) {
425   auto llvmTy = type.dyn_cast<LLVM::LLVMPointerType>();
426   if (!llvmTy)
427     return parser.emitError(trailingTypeLoc, "expected LLVM pointer type"),
428            nullptr;
429   return llvmTy.getElementType();
430 }
431 
432 // <operation> ::= `llvm.load` `volatile` ssa-use attribute-dict? `:` type
433 static ParseResult parseLoadOp(OpAsmParser &parser, OperationState &result) {
434   OpAsmParser::OperandType addr;
435   Type type;
436   llvm::SMLoc trailingTypeLoc;
437 
438   if (succeeded(parser.parseOptionalKeyword("volatile")))
439     result.addAttribute(kVolatileAttrName, parser.getBuilder().getUnitAttr());
440 
441   if (parser.parseOperand(addr) ||
442       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
443       parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type) ||
444       parser.resolveOperand(addr, type, result.operands))
445     return failure();
446 
447   Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc);
448 
449   result.addTypes(elemTy);
450   return success();
451 }
452 
453 //===----------------------------------------------------------------------===//
454 // Builder, printer and parser for LLVM::StoreOp.
455 //===----------------------------------------------------------------------===//
456 
457 static LogicalResult verify(StoreOp op) {
458   return verifyAccessGroups(op.getOperation());
459 }
460 
461 void StoreOp::build(OpBuilder &builder, OperationState &result, Value value,
462                     Value addr, unsigned alignment, bool isVolatile,
463                     bool isNonTemporal) {
464   result.addOperands({value, addr});
465   result.addTypes({});
466   if (isVolatile)
467     result.addAttribute(kVolatileAttrName, builder.getUnitAttr());
468   if (isNonTemporal)
469     result.addAttribute(kNonTemporalAttrName, builder.getUnitAttr());
470   if (alignment != 0)
471     result.addAttribute("alignment", builder.getI64IntegerAttr(alignment));
472 }
473 
474 static void printStoreOp(OpAsmPrinter &p, StoreOp &op) {
475   p << op.getOperationName() << ' ';
476   if (op.volatile_())
477     p << "volatile ";
478   p << op.value() << ", " << op.addr();
479   p.printOptionalAttrDict(op->getAttrs(), {kVolatileAttrName});
480   p << " : " << op.addr().getType();
481 }
482 
483 // <operation> ::= `llvm.store` `volatile` ssa-use `,` ssa-use
484 //                 attribute-dict? `:` type
485 static ParseResult parseStoreOp(OpAsmParser &parser, OperationState &result) {
486   OpAsmParser::OperandType addr, value;
487   Type type;
488   llvm::SMLoc trailingTypeLoc;
489 
490   if (succeeded(parser.parseOptionalKeyword("volatile")))
491     result.addAttribute(kVolatileAttrName, parser.getBuilder().getUnitAttr());
492 
493   if (parser.parseOperand(value) || parser.parseComma() ||
494       parser.parseOperand(addr) ||
495       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
496       parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type))
497     return failure();
498 
499   Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc);
500   if (!elemTy)
501     return failure();
502 
503   if (parser.resolveOperand(value, elemTy, result.operands) ||
504       parser.resolveOperand(addr, type, result.operands))
505     return failure();
506 
507   return success();
508 }
509 
510 ///===---------------------------------------------------------------------===//
511 /// LLVM::InvokeOp
512 ///===---------------------------------------------------------------------===//
513 
514 Optional<MutableOperandRange>
515 InvokeOp::getMutableSuccessorOperands(unsigned index) {
516   assert(index < getNumSuccessors() && "invalid successor index");
517   return index == 0 ? normalDestOperandsMutable() : unwindDestOperandsMutable();
518 }
519 
520 static LogicalResult verify(InvokeOp op) {
521   if (op.getNumResults() > 1)
522     return op.emitOpError("must have 0 or 1 result");
523 
524   Block *unwindDest = op.unwindDest();
525   if (unwindDest->empty())
526     return op.emitError(
527         "must have at least one operation in unwind destination");
528 
529   // In unwind destination, first operation must be LandingpadOp
530   if (!isa<LandingpadOp>(unwindDest->front()))
531     return op.emitError("first operation in unwind destination should be a "
532                         "llvm.landingpad operation");
533 
534   return success();
535 }
536 
537 static void printInvokeOp(OpAsmPrinter &p, InvokeOp op) {
538   auto callee = op.callee();
539   bool isDirect = callee.hasValue();
540 
541   p << op.getOperationName() << ' ';
542 
543   // Either function name or pointer
544   if (isDirect)
545     p.printSymbolName(callee.getValue());
546   else
547     p << op.getOperand(0);
548 
549   p << '(' << op.getOperands().drop_front(isDirect ? 0 : 1) << ')';
550   p << " to ";
551   p.printSuccessorAndUseList(op.normalDest(), op.normalDestOperands());
552   p << " unwind ";
553   p.printSuccessorAndUseList(op.unwindDest(), op.unwindDestOperands());
554 
555   p.printOptionalAttrDict(op->getAttrs(),
556                           {InvokeOp::getOperandSegmentSizeAttr(), "callee"});
557   p << " : ";
558   p.printFunctionalType(
559       llvm::drop_begin(op.getOperandTypes(), isDirect ? 0 : 1),
560       op.getResultTypes());
561 }
562 
563 /// <operation> ::= `llvm.invoke` (function-id | ssa-use) `(` ssa-use-list `)`
564 ///                  `to` bb-id (`[` ssa-use-and-type-list `]`)?
565 ///                  `unwind` bb-id (`[` ssa-use-and-type-list `]`)?
566 ///                  attribute-dict? `:` function-type
567 static ParseResult parseInvokeOp(OpAsmParser &parser, OperationState &result) {
568   SmallVector<OpAsmParser::OperandType, 8> operands;
569   FunctionType funcType;
570   SymbolRefAttr funcAttr;
571   llvm::SMLoc trailingTypeLoc;
572   Block *normalDest, *unwindDest;
573   SmallVector<Value, 4> normalOperands, unwindOperands;
574   Builder &builder = parser.getBuilder();
575 
576   // Parse an operand list that will, in practice, contain 0 or 1 operand.  In
577   // case of an indirect call, there will be 1 operand before `(`.  In case of a
578   // direct call, there will be no operands and the parser will stop at the
579   // function identifier without complaining.
580   if (parser.parseOperandList(operands))
581     return failure();
582   bool isDirect = operands.empty();
583 
584   // Optionally parse a function identifier.
585   if (isDirect && parser.parseAttribute(funcAttr, "callee", result.attributes))
586     return failure();
587 
588   if (parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) ||
589       parser.parseKeyword("to") ||
590       parser.parseSuccessorAndUseList(normalDest, normalOperands) ||
591       parser.parseKeyword("unwind") ||
592       parser.parseSuccessorAndUseList(unwindDest, unwindOperands) ||
593       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
594       parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(funcType))
595     return failure();
596 
597   if (isDirect) {
598     // Make sure types match.
599     if (parser.resolveOperands(operands, funcType.getInputs(),
600                                parser.getNameLoc(), result.operands))
601       return failure();
602     result.addTypes(funcType.getResults());
603   } else {
604     // Construct the LLVM IR Dialect function type that the first operand
605     // should match.
606     if (funcType.getNumResults() > 1)
607       return parser.emitError(trailingTypeLoc,
608                               "expected function with 0 or 1 result");
609 
610     Type llvmResultType;
611     if (funcType.getNumResults() == 0) {
612       llvmResultType = LLVM::LLVMVoidType::get(builder.getContext());
613     } else {
614       llvmResultType = funcType.getResult(0);
615       if (!isCompatibleType(llvmResultType))
616         return parser.emitError(trailingTypeLoc,
617                                 "expected result to have LLVM type");
618     }
619 
620     SmallVector<Type, 8> argTypes;
621     argTypes.reserve(funcType.getNumInputs());
622     for (Type ty : funcType.getInputs()) {
623       if (isCompatibleType(ty))
624         argTypes.push_back(ty);
625       else
626         return parser.emitError(trailingTypeLoc,
627                                 "expected LLVM types as inputs");
628     }
629 
630     auto llvmFuncType = LLVM::LLVMFunctionType::get(llvmResultType, argTypes);
631     auto wrappedFuncType = LLVM::LLVMPointerType::get(llvmFuncType);
632 
633     auto funcArguments = llvm::makeArrayRef(operands).drop_front();
634 
635     // Make sure that the first operand (indirect callee) matches the wrapped
636     // LLVM IR function type, and that the types of the other call operands
637     // match the types of the function arguments.
638     if (parser.resolveOperand(operands[0], wrappedFuncType, result.operands) ||
639         parser.resolveOperands(funcArguments, funcType.getInputs(),
640                                parser.getNameLoc(), result.operands))
641       return failure();
642 
643     result.addTypes(llvmResultType);
644   }
645   result.addSuccessors({normalDest, unwindDest});
646   result.addOperands(normalOperands);
647   result.addOperands(unwindOperands);
648 
649   result.addAttribute(
650       InvokeOp::getOperandSegmentSizeAttr(),
651       builder.getI32VectorAttr({static_cast<int32_t>(operands.size()),
652                                 static_cast<int32_t>(normalOperands.size()),
653                                 static_cast<int32_t>(unwindOperands.size())}));
654   return success();
655 }
656 
657 ///===----------------------------------------------------------------------===//
658 /// Verifying/Printing/Parsing for LLVM::LandingpadOp.
659 ///===----------------------------------------------------------------------===//
660 
661 static LogicalResult verify(LandingpadOp op) {
662   Value value;
663   if (LLVMFuncOp func = op->getParentOfType<LLVMFuncOp>()) {
664     if (!func.personality().hasValue())
665       return op.emitError(
666           "llvm.landingpad needs to be in a function with a personality");
667   }
668 
669   if (!op.cleanup() && op.getOperands().empty())
670     return op.emitError("landingpad instruction expects at least one clause or "
671                         "cleanup attribute");
672 
673   for (unsigned idx = 0, ie = op.getNumOperands(); idx < ie; idx++) {
674     value = op.getOperand(idx);
675     bool isFilter = value.getType().isa<LLVMArrayType>();
676     if (isFilter) {
677       // FIXME: Verify filter clauses when arrays are appropriately handled
678     } else {
679       // catch - global addresses only.
680       // Bitcast ops should have global addresses as their args.
681       if (auto bcOp = value.getDefiningOp<BitcastOp>()) {
682         if (auto addrOp = bcOp.arg().getDefiningOp<AddressOfOp>())
683           continue;
684         return op.emitError("constant clauses expected")
685                    .attachNote(bcOp.getLoc())
686                << "global addresses expected as operand to "
687                   "bitcast used in clauses for landingpad";
688       }
689       // NullOp and AddressOfOp allowed
690       if (value.getDefiningOp<NullOp>())
691         continue;
692       if (value.getDefiningOp<AddressOfOp>())
693         continue;
694       return op.emitError("clause #")
695              << idx << " is not a known constant - null, addressof, bitcast";
696     }
697   }
698   return success();
699 }
700 
701 static void printLandingpadOp(OpAsmPrinter &p, LandingpadOp &op) {
702   p << op.getOperationName() << (op.cleanup() ? " cleanup " : " ");
703 
704   // Clauses
705   for (auto value : op.getOperands()) {
706     // Similar to llvm - if clause is an array type then it is filter
707     // clause else catch clause
708     bool isArrayTy = value.getType().isa<LLVMArrayType>();
709     p << '(' << (isArrayTy ? "filter " : "catch ") << value << " : "
710       << value.getType() << ") ";
711   }
712 
713   p.printOptionalAttrDict(op->getAttrs(), {"cleanup"});
714 
715   p << ": " << op.getType();
716 }
717 
718 /// <operation> ::= `llvm.landingpad` `cleanup`?
719 ///                 ((`catch` | `filter`) operand-type ssa-use)* attribute-dict?
720 static ParseResult parseLandingpadOp(OpAsmParser &parser,
721                                      OperationState &result) {
722   // Check for cleanup
723   if (succeeded(parser.parseOptionalKeyword("cleanup")))
724     result.addAttribute("cleanup", parser.getBuilder().getUnitAttr());
725 
726   // Parse clauses with types
727   while (succeeded(parser.parseOptionalLParen()) &&
728          (succeeded(parser.parseOptionalKeyword("filter")) ||
729           succeeded(parser.parseOptionalKeyword("catch")))) {
730     OpAsmParser::OperandType operand;
731     Type ty;
732     if (parser.parseOperand(operand) || parser.parseColon() ||
733         parser.parseType(ty) ||
734         parser.resolveOperand(operand, ty, result.operands) ||
735         parser.parseRParen())
736       return failure();
737   }
738 
739   Type type;
740   if (parser.parseColon() || parser.parseType(type))
741     return failure();
742 
743   result.addTypes(type);
744   return success();
745 }
746 
747 //===----------------------------------------------------------------------===//
748 // Verifying/Printing/parsing for LLVM::CallOp.
749 //===----------------------------------------------------------------------===//
750 
751 static LogicalResult verify(CallOp &op) {
752   if (op.getNumResults() > 1)
753     return op.emitOpError("must have 0 or 1 result");
754 
755   // Type for the callee, we'll get it differently depending if it is a direct
756   // or indirect call.
757   Type fnType;
758 
759   bool isIndirect = false;
760 
761   // If this is an indirect call, the callee attribute is missing.
762   Optional<StringRef> calleeName = op.callee();
763   if (!calleeName) {
764     isIndirect = true;
765     if (!op.getNumOperands())
766       return op.emitOpError(
767           "must have either a `callee` attribute or at least an operand");
768     auto ptrType = op.getOperand(0).getType().dyn_cast<LLVMPointerType>();
769     if (!ptrType)
770       return op.emitOpError("indirect call expects a pointer as callee: ")
771              << ptrType;
772     fnType = ptrType.getElementType();
773   } else {
774     Operation *callee = SymbolTable::lookupNearestSymbolFrom(op, *calleeName);
775     if (!callee)
776       return op.emitOpError()
777              << "'" << *calleeName
778              << "' does not reference a symbol in the current scope";
779     auto fn = dyn_cast<LLVMFuncOp>(callee);
780     if (!fn)
781       return op.emitOpError() << "'" << *calleeName
782                               << "' does not reference a valid LLVM function";
783 
784     fnType = fn.getType();
785   }
786 
787   LLVMFunctionType funcType = fnType.dyn_cast<LLVMFunctionType>();
788   if (!funcType)
789     return op.emitOpError("callee does not have a functional type: ") << fnType;
790 
791   // Verify that the operand and result types match the callee.
792 
793   if (!funcType.isVarArg() &&
794       funcType.getNumParams() != (op.getNumOperands() - isIndirect))
795     return op.emitOpError()
796            << "incorrect number of operands ("
797            << (op.getNumOperands() - isIndirect)
798            << ") for callee (expecting: " << funcType.getNumParams() << ")";
799 
800   if (funcType.getNumParams() > (op.getNumOperands() - isIndirect))
801     return op.emitOpError() << "incorrect number of operands ("
802                             << (op.getNumOperands() - isIndirect)
803                             << ") for varargs callee (expecting at least: "
804                             << funcType.getNumParams() << ")";
805 
806   for (unsigned i = 0, e = funcType.getNumParams(); i != e; ++i)
807     if (op.getOperand(i + isIndirect).getType() != funcType.getParamType(i))
808       return op.emitOpError() << "operand type mismatch for operand " << i
809                               << ": " << op.getOperand(i + isIndirect).getType()
810                               << " != " << funcType.getParamType(i);
811 
812   if (op.getNumResults() &&
813       op.getResult(0).getType() != funcType.getReturnType())
814     return op.emitOpError()
815            << "result type mismatch: " << op.getResult(0).getType()
816            << " != " << funcType.getReturnType();
817 
818   return success();
819 }
820 
821 static void printCallOp(OpAsmPrinter &p, CallOp &op) {
822   auto callee = op.callee();
823   bool isDirect = callee.hasValue();
824 
825   // Print the direct callee if present as a function attribute, or an indirect
826   // callee (first operand) otherwise.
827   p << op.getOperationName() << ' ';
828   if (isDirect)
829     p.printSymbolName(callee.getValue());
830   else
831     p << op.getOperand(0);
832 
833   auto args = op.getOperands().drop_front(isDirect ? 0 : 1);
834   p << '(' << args << ')';
835   p.printOptionalAttrDict(processFMFAttr(op->getAttrs()), {"callee"});
836 
837   // Reconstruct the function MLIR function type from operand and result types.
838   p << " : "
839     << FunctionType::get(op.getContext(), args.getTypes(), op.getResultTypes());
840 }
841 
842 // <operation> ::= `llvm.call` (function-id | ssa-use) `(` ssa-use-list `)`
843 //                 attribute-dict? `:` function-type
844 static ParseResult parseCallOp(OpAsmParser &parser, OperationState &result) {
845   SmallVector<OpAsmParser::OperandType, 8> operands;
846   Type type;
847   SymbolRefAttr funcAttr;
848   llvm::SMLoc trailingTypeLoc;
849 
850   // Parse an operand list that will, in practice, contain 0 or 1 operand.  In
851   // case of an indirect call, there will be 1 operand before `(`.  In case of a
852   // direct call, there will be no operands and the parser will stop at the
853   // function identifier without complaining.
854   if (parser.parseOperandList(operands))
855     return failure();
856   bool isDirect = operands.empty();
857 
858   // Optionally parse a function identifier.
859   if (isDirect)
860     if (parser.parseAttribute(funcAttr, "callee", result.attributes))
861       return failure();
862 
863   if (parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) ||
864       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
865       parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type))
866     return failure();
867 
868   auto funcType = type.dyn_cast<FunctionType>();
869   if (!funcType)
870     return parser.emitError(trailingTypeLoc, "expected function type");
871   if (isDirect) {
872     // Make sure types match.
873     if (parser.resolveOperands(operands, funcType.getInputs(),
874                                parser.getNameLoc(), result.operands))
875       return failure();
876     result.addTypes(funcType.getResults());
877   } else {
878     // Construct the LLVM IR Dialect function type that the first operand
879     // should match.
880     if (funcType.getNumResults() > 1)
881       return parser.emitError(trailingTypeLoc,
882                               "expected function with 0 or 1 result");
883 
884     Builder &builder = parser.getBuilder();
885     Type llvmResultType;
886     if (funcType.getNumResults() == 0) {
887       llvmResultType = LLVM::LLVMVoidType::get(builder.getContext());
888     } else {
889       llvmResultType = funcType.getResult(0);
890       if (!isCompatibleType(llvmResultType))
891         return parser.emitError(trailingTypeLoc,
892                                 "expected result to have LLVM type");
893     }
894 
895     SmallVector<Type, 8> argTypes;
896     argTypes.reserve(funcType.getNumInputs());
897     for (int i = 0, e = funcType.getNumInputs(); i < e; ++i) {
898       auto argType = funcType.getInput(i);
899       if (!isCompatibleType(argType))
900         return parser.emitError(trailingTypeLoc,
901                                 "expected LLVM types as inputs");
902       argTypes.push_back(argType);
903     }
904     auto llvmFuncType = LLVM::LLVMFunctionType::get(llvmResultType, argTypes);
905     auto wrappedFuncType = LLVM::LLVMPointerType::get(llvmFuncType);
906 
907     auto funcArguments =
908         ArrayRef<OpAsmParser::OperandType>(operands).drop_front();
909 
910     // Make sure that the first operand (indirect callee) matches the wrapped
911     // LLVM IR function type, and that the types of the other call operands
912     // match the types of the function arguments.
913     if (parser.resolveOperand(operands[0], wrappedFuncType, result.operands) ||
914         parser.resolveOperands(funcArguments, funcType.getInputs(),
915                                parser.getNameLoc(), result.operands))
916       return failure();
917 
918     result.addTypes(llvmResultType);
919   }
920 
921   return success();
922 }
923 
924 //===----------------------------------------------------------------------===//
925 // Printing/parsing for LLVM::ExtractElementOp.
926 //===----------------------------------------------------------------------===//
927 // Expects vector to be of wrapped LLVM vector type and position to be of
928 // wrapped LLVM i32 type.
929 void LLVM::ExtractElementOp::build(OpBuilder &b, OperationState &result,
930                                    Value vector, Value position,
931                                    ArrayRef<NamedAttribute> attrs) {
932   auto vectorType = vector.getType();
933   auto llvmType = LLVM::getVectorElementType(vectorType);
934   build(b, result, llvmType, vector, position);
935   result.addAttributes(attrs);
936 }
937 
938 static void printExtractElementOp(OpAsmPrinter &p, ExtractElementOp &op) {
939   p << op.getOperationName() << ' ' << op.vector() << "[" << op.position()
940     << " : " << op.position().getType() << "]";
941   p.printOptionalAttrDict(op->getAttrs());
942   p << " : " << op.vector().getType();
943 }
944 
945 // <operation> ::= `llvm.extractelement` ssa-use `, ` ssa-use
946 //                 attribute-dict? `:` type
947 static ParseResult parseExtractElementOp(OpAsmParser &parser,
948                                          OperationState &result) {
949   llvm::SMLoc loc;
950   OpAsmParser::OperandType vector, position;
951   Type type, positionType;
952   if (parser.getCurrentLocation(&loc) || parser.parseOperand(vector) ||
953       parser.parseLSquare() || parser.parseOperand(position) ||
954       parser.parseColonType(positionType) || parser.parseRSquare() ||
955       parser.parseOptionalAttrDict(result.attributes) ||
956       parser.parseColonType(type) ||
957       parser.resolveOperand(vector, type, result.operands) ||
958       parser.resolveOperand(position, positionType, result.operands))
959     return failure();
960   if (!LLVM::isCompatibleVectorType(type))
961     return parser.emitError(
962         loc, "expected LLVM dialect-compatible vector type for operand #1");
963   result.addTypes(LLVM::getVectorElementType(type));
964   return success();
965 }
966 
967 //===----------------------------------------------------------------------===//
968 // Printing/parsing for LLVM::ExtractValueOp.
969 //===----------------------------------------------------------------------===//
970 
971 static void printExtractValueOp(OpAsmPrinter &p, ExtractValueOp &op) {
972   p << op.getOperationName() << ' ' << op.container() << op.position();
973   p.printOptionalAttrDict(op->getAttrs(), {"position"});
974   p << " : " << op.container().getType();
975 }
976 
977 // Extract the type at `position` in the wrapped LLVM IR aggregate type
978 // `containerType`.  Position is an integer array attribute where each value
979 // is a zero-based position of the element in the aggregate type.  Return the
980 // resulting type wrapped in MLIR, or nullptr on error.
981 static Type getInsertExtractValueElementType(OpAsmParser &parser,
982                                              Type containerType,
983                                              ArrayAttr positionAttr,
984                                              llvm::SMLoc attributeLoc,
985                                              llvm::SMLoc typeLoc) {
986   Type llvmType = containerType;
987   if (!isCompatibleType(containerType))
988     return parser.emitError(typeLoc, "expected LLVM IR Dialect type"), nullptr;
989 
990   // Infer the element type from the structure type: iteratively step inside the
991   // type by taking the element type, indexed by the position attribute for
992   // structures.  Check the position index before accessing, it is supposed to
993   // be in bounds.
994   for (Attribute subAttr : positionAttr) {
995     auto positionElementAttr = subAttr.dyn_cast<IntegerAttr>();
996     if (!positionElementAttr)
997       return parser.emitError(attributeLoc,
998                               "expected an array of integer literals"),
999              nullptr;
1000     int position = positionElementAttr.getInt();
1001     if (auto arrayType = llvmType.dyn_cast<LLVMArrayType>()) {
1002       if (position < 0 ||
1003           static_cast<unsigned>(position) >= arrayType.getNumElements())
1004         return parser.emitError(attributeLoc, "position out of bounds"),
1005                nullptr;
1006       llvmType = arrayType.getElementType();
1007     } else if (auto structType = llvmType.dyn_cast<LLVMStructType>()) {
1008       if (position < 0 ||
1009           static_cast<unsigned>(position) >= structType.getBody().size())
1010         return parser.emitError(attributeLoc, "position out of bounds"),
1011                nullptr;
1012       llvmType = structType.getBody()[position];
1013     } else {
1014       return parser.emitError(typeLoc, "expected LLVM IR structure/array type"),
1015              nullptr;
1016     }
1017   }
1018   return llvmType;
1019 }
1020 
1021 // <operation> ::= `llvm.extractvalue` ssa-use
1022 //                 `[` integer-literal (`,` integer-literal)* `]`
1023 //                 attribute-dict? `:` type
1024 static ParseResult parseExtractValueOp(OpAsmParser &parser,
1025                                        OperationState &result) {
1026   OpAsmParser::OperandType container;
1027   Type containerType;
1028   ArrayAttr positionAttr;
1029   llvm::SMLoc attributeLoc, trailingTypeLoc;
1030 
1031   if (parser.parseOperand(container) ||
1032       parser.getCurrentLocation(&attributeLoc) ||
1033       parser.parseAttribute(positionAttr, "position", result.attributes) ||
1034       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
1035       parser.getCurrentLocation(&trailingTypeLoc) ||
1036       parser.parseType(containerType) ||
1037       parser.resolveOperand(container, containerType, result.operands))
1038     return failure();
1039 
1040   auto elementType = getInsertExtractValueElementType(
1041       parser, containerType, positionAttr, attributeLoc, trailingTypeLoc);
1042   if (!elementType)
1043     return failure();
1044 
1045   result.addTypes(elementType);
1046   return success();
1047 }
1048 
1049 //===----------------------------------------------------------------------===//
1050 // Printing/parsing for LLVM::InsertElementOp.
1051 //===----------------------------------------------------------------------===//
1052 
1053 static void printInsertElementOp(OpAsmPrinter &p, InsertElementOp &op) {
1054   p << op.getOperationName() << ' ' << op.value() << ", " << op.vector() << "["
1055     << op.position() << " : " << op.position().getType() << "]";
1056   p.printOptionalAttrDict(op->getAttrs());
1057   p << " : " << op.vector().getType();
1058 }
1059 
1060 // <operation> ::= `llvm.insertelement` ssa-use `,` ssa-use `,` ssa-use
1061 //                 attribute-dict? `:` type
1062 static ParseResult parseInsertElementOp(OpAsmParser &parser,
1063                                         OperationState &result) {
1064   llvm::SMLoc loc;
1065   OpAsmParser::OperandType vector, value, position;
1066   Type vectorType, positionType;
1067   if (parser.getCurrentLocation(&loc) || parser.parseOperand(value) ||
1068       parser.parseComma() || parser.parseOperand(vector) ||
1069       parser.parseLSquare() || parser.parseOperand(position) ||
1070       parser.parseColonType(positionType) || parser.parseRSquare() ||
1071       parser.parseOptionalAttrDict(result.attributes) ||
1072       parser.parseColonType(vectorType))
1073     return failure();
1074 
1075   if (!LLVM::isCompatibleVectorType(vectorType))
1076     return parser.emitError(
1077         loc, "expected LLVM dialect-compatible vector type for operand #1");
1078   Type valueType = LLVM::getVectorElementType(vectorType);
1079   if (!valueType)
1080     return failure();
1081 
1082   if (parser.resolveOperand(vector, vectorType, result.operands) ||
1083       parser.resolveOperand(value, valueType, result.operands) ||
1084       parser.resolveOperand(position, positionType, result.operands))
1085     return failure();
1086 
1087   result.addTypes(vectorType);
1088   return success();
1089 }
1090 
1091 //===----------------------------------------------------------------------===//
1092 // Printing/parsing for LLVM::InsertValueOp.
1093 //===----------------------------------------------------------------------===//
1094 
1095 static void printInsertValueOp(OpAsmPrinter &p, InsertValueOp &op) {
1096   p << op.getOperationName() << ' ' << op.value() << ", " << op.container()
1097     << op.position();
1098   p.printOptionalAttrDict(op->getAttrs(), {"position"});
1099   p << " : " << op.container().getType();
1100 }
1101 
1102 // <operation> ::= `llvm.insertvaluevalue` ssa-use `,` ssa-use
1103 //                 `[` integer-literal (`,` integer-literal)* `]`
1104 //                 attribute-dict? `:` type
1105 static ParseResult parseInsertValueOp(OpAsmParser &parser,
1106                                       OperationState &result) {
1107   OpAsmParser::OperandType container, value;
1108   Type containerType;
1109   ArrayAttr positionAttr;
1110   llvm::SMLoc attributeLoc, trailingTypeLoc;
1111 
1112   if (parser.parseOperand(value) || parser.parseComma() ||
1113       parser.parseOperand(container) ||
1114       parser.getCurrentLocation(&attributeLoc) ||
1115       parser.parseAttribute(positionAttr, "position", result.attributes) ||
1116       parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
1117       parser.getCurrentLocation(&trailingTypeLoc) ||
1118       parser.parseType(containerType))
1119     return failure();
1120 
1121   auto valueType = getInsertExtractValueElementType(
1122       parser, containerType, positionAttr, attributeLoc, trailingTypeLoc);
1123   if (!valueType)
1124     return failure();
1125 
1126   if (parser.resolveOperand(container, containerType, result.operands) ||
1127       parser.resolveOperand(value, valueType, result.operands))
1128     return failure();
1129 
1130   result.addTypes(containerType);
1131   return success();
1132 }
1133 
1134 //===----------------------------------------------------------------------===//
1135 // Printing, parsing and verification for LLVM::ReturnOp.
1136 //===----------------------------------------------------------------------===//
1137 
1138 static void printReturnOp(OpAsmPrinter &p, ReturnOp op) {
1139   p << op.getOperationName();
1140   p.printOptionalAttrDict(op->getAttrs());
1141   assert(op.getNumOperands() <= 1);
1142 
1143   if (op.getNumOperands() == 0)
1144     return;
1145 
1146   p << ' ' << op.getOperand(0) << " : " << op.getOperand(0).getType();
1147 }
1148 
1149 // <operation> ::= `llvm.return` ssa-use-list attribute-dict? `:`
1150 //                 type-list-no-parens
1151 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) {
1152   SmallVector<OpAsmParser::OperandType, 1> operands;
1153   Type type;
1154 
1155   if (parser.parseOperandList(operands) ||
1156       parser.parseOptionalAttrDict(result.attributes))
1157     return failure();
1158   if (operands.empty())
1159     return success();
1160 
1161   if (parser.parseColonType(type) ||
1162       parser.resolveOperand(operands[0], type, result.operands))
1163     return failure();
1164   return success();
1165 }
1166 
1167 static LogicalResult verify(ReturnOp op) {
1168   if (op->getNumOperands() > 1)
1169     return op->emitOpError("expected at most 1 operand");
1170 
1171   if (auto parent = op->getParentOfType<LLVMFuncOp>()) {
1172     Type expectedType = parent.getType().getReturnType();
1173     if (expectedType.isa<LLVMVoidType>()) {
1174       if (op->getNumOperands() == 0)
1175         return success();
1176       InFlightDiagnostic diag = op->emitOpError("expected no operands");
1177       diag.attachNote(parent->getLoc()) << "when returning from function";
1178       return diag;
1179     }
1180     if (op->getNumOperands() == 0) {
1181       if (expectedType.isa<LLVMVoidType>())
1182         return success();
1183       InFlightDiagnostic diag = op->emitOpError("expected 1 operand");
1184       diag.attachNote(parent->getLoc()) << "when returning from function";
1185       return diag;
1186     }
1187     if (expectedType != op->getOperand(0).getType()) {
1188       InFlightDiagnostic diag = op->emitOpError("mismatching result types");
1189       diag.attachNote(parent->getLoc()) << "when returning from function";
1190       return diag;
1191     }
1192   }
1193   return success();
1194 }
1195 
1196 //===----------------------------------------------------------------------===//
1197 // Verifier for LLVM::AddressOfOp.
1198 //===----------------------------------------------------------------------===//
1199 
1200 template <typename OpTy>
1201 static OpTy lookupSymbolInModule(Operation *parent, StringRef name) {
1202   Operation *module = parent;
1203   while (module && !satisfiesLLVMModule(module))
1204     module = module->getParentOp();
1205   assert(module && "unexpected operation outside of a module");
1206   return dyn_cast_or_null<OpTy>(
1207       mlir::SymbolTable::lookupSymbolIn(module, name));
1208 }
1209 
1210 GlobalOp AddressOfOp::getGlobal() {
1211   return lookupSymbolInModule<LLVM::GlobalOp>((*this)->getParentOp(),
1212                                               global_name());
1213 }
1214 
1215 LLVMFuncOp AddressOfOp::getFunction() {
1216   return lookupSymbolInModule<LLVM::LLVMFuncOp>((*this)->getParentOp(),
1217                                                 global_name());
1218 }
1219 
1220 static LogicalResult verify(AddressOfOp op) {
1221   auto global = op.getGlobal();
1222   auto function = op.getFunction();
1223   if (!global && !function)
1224     return op.emitOpError(
1225         "must reference a global defined by 'llvm.mlir.global' or 'llvm.func'");
1226 
1227   if (global &&
1228       LLVM::LLVMPointerType::get(global.getType(), global.addr_space()) !=
1229           op.getResult().getType())
1230     return op.emitOpError(
1231         "the type must be a pointer to the type of the referenced global");
1232 
1233   if (function && LLVM::LLVMPointerType::get(function.getType()) !=
1234                       op.getResult().getType())
1235     return op.emitOpError(
1236         "the type must be a pointer to the type of the referenced function");
1237 
1238   return success();
1239 }
1240 
1241 //===----------------------------------------------------------------------===//
1242 // Builder, printer and verifier for LLVM::GlobalOp.
1243 //===----------------------------------------------------------------------===//
1244 
1245 /// Returns the name used for the linkage attribute. This *must* correspond to
1246 /// the name of the attribute in ODS.
1247 static StringRef getLinkageAttrName() { return "linkage"; }
1248 
1249 /// Returns the name used for the unnamed_addr attribute. This *must* correspond
1250 /// to the name of the attribute in ODS.
1251 static StringRef getUnnamedAddrAttrName() { return "unnamed_addr"; }
1252 
1253 void GlobalOp::build(OpBuilder &builder, OperationState &result, Type type,
1254                      bool isConstant, Linkage linkage, StringRef name,
1255                      Attribute value, uint64_t alignment, unsigned addrSpace,
1256                      ArrayRef<NamedAttribute> attrs) {
1257   result.addAttribute(SymbolTable::getSymbolAttrName(),
1258                       builder.getStringAttr(name));
1259   result.addAttribute("type", TypeAttr::get(type));
1260   if (isConstant)
1261     result.addAttribute("constant", builder.getUnitAttr());
1262   if (value)
1263     result.addAttribute("value", value);
1264 
1265   // Only add an alignment attribute if the "alignment" input
1266   // is different from 0. The value must also be a power of two, but
1267   // this is tested in GlobalOp::verify, not here.
1268   if (alignment != 0)
1269     result.addAttribute("alignment", builder.getI64IntegerAttr(alignment));
1270 
1271   result.addAttribute(getLinkageAttrName(),
1272                       builder.getI64IntegerAttr(static_cast<int64_t>(linkage)));
1273   if (addrSpace != 0)
1274     result.addAttribute("addr_space", builder.getI32IntegerAttr(addrSpace));
1275   result.attributes.append(attrs.begin(), attrs.end());
1276   result.addRegion();
1277 }
1278 
1279 static void printGlobalOp(OpAsmPrinter &p, GlobalOp op) {
1280   p << op.getOperationName() << ' ' << stringifyLinkage(op.linkage()) << ' ';
1281   if (op.unnamed_addr())
1282     p << stringifyUnnamedAddr(*op.unnamed_addr()) << ' ';
1283   if (op.constant())
1284     p << "constant ";
1285   p.printSymbolName(op.sym_name());
1286   p << '(';
1287   if (auto value = op.getValueOrNull())
1288     p.printAttribute(value);
1289   p << ')';
1290   // Note that the alignment attribute is printed using the
1291   // default syntax here, even though it is an inherent attribute
1292   // (as defined in https://mlir.llvm.org/docs/LangRef/#attributes)
1293   p.printOptionalAttrDict(op->getAttrs(),
1294                           {SymbolTable::getSymbolAttrName(), "type", "constant",
1295                            "value", getLinkageAttrName(),
1296                            getUnnamedAddrAttrName()});
1297 
1298   // Print the trailing type unless it's a string global.
1299   if (op.getValueOrNull().dyn_cast_or_null<StringAttr>())
1300     return;
1301   p << " : " << op.type();
1302 
1303   Region &initializer = op.getInitializerRegion();
1304   if (!initializer.empty())
1305     p.printRegion(initializer, /*printEntryBlockArgs=*/false);
1306 }
1307 
1308 //===----------------------------------------------------------------------===//
1309 // Verifier for LLVM::DialectCastOp.
1310 //===----------------------------------------------------------------------===//
1311 
1312 /// Checks if `llvmType` is dialect cast-compatible with `index` type. Does not
1313 /// report the error, the user is expected to produce an appropriate message.
1314 // TODO: make the size depend on data layout rather than on the conversion
1315 // pass option, and pull that information here.
1316 static LogicalResult verifyCastWithIndex(Type llvmType) {
1317   return success(llvmType.isa<IntegerType>());
1318 }
1319 
1320 /// Checks if `llvmType` is dialect cast-compatible with built-in `type` and
1321 /// reports errors to the location of `op`. `isElement` indicates whether the
1322 /// verification is performed for types that are element types inside a
1323 /// container; we don't want casts from X to X at the top level, but c1<X> to
1324 /// c2<X> may be fine.
1325 static LogicalResult verifyCast(DialectCastOp op, Type llvmType, Type type,
1326                                 bool isElement = false) {
1327   // Equal element types are directly compatible.
1328   if (isElement && llvmType == type)
1329     return success();
1330 
1331   // Index is compatible with any integer.
1332   if (type.isIndex()) {
1333     if (succeeded(verifyCastWithIndex(llvmType)))
1334       return success();
1335 
1336     return op.emitOpError("invalid cast between index and non-integer type");
1337   }
1338 
1339   if (type.isa<IntegerType>()) {
1340     auto llvmIntegerType = llvmType.dyn_cast<IntegerType>();
1341     if (!llvmIntegerType)
1342       return op->emitOpError("invalid cast between integer and non-integer");
1343     if (llvmIntegerType.getWidth() != type.getIntOrFloatBitWidth())
1344       return op.emitOpError("invalid cast changing integer width");
1345     return success();
1346   }
1347 
1348   // Vectors are compatible if they are 1D non-scalable, and their element types
1349   // are compatible. nD vectors are compatible with (n-1)D arrays containing 1D
1350   // vector.
1351   if (auto vectorType = type.dyn_cast<VectorType>()) {
1352     if (vectorType == llvmType && !isElement)
1353       return op.emitOpError("vector types should not be casted");
1354 
1355     if (vectorType.getRank() == 1) {
1356       auto llvmVectorType = llvmType.dyn_cast<VectorType>();
1357       if (!llvmVectorType || llvmVectorType.getRank() != 1)
1358         return op.emitOpError("invalid cast for vector types");
1359 
1360       return verifyCast(op, llvmVectorType.getElementType(),
1361                         vectorType.getElementType(), /*isElement=*/true);
1362     }
1363 
1364     auto arrayType = llvmType.dyn_cast<LLVM::LLVMArrayType>();
1365     if (!arrayType ||
1366         arrayType.getNumElements() != vectorType.getShape().front())
1367       return op.emitOpError("invalid cast for vector, expected array");
1368     return verifyCast(op, arrayType.getElementType(),
1369                       VectorType::get(vectorType.getShape().drop_front(),
1370                                       vectorType.getElementType()),
1371                       /*isElement=*/true);
1372   }
1373 
1374   if (auto memrefType = type.dyn_cast<MemRefType>()) {
1375     // Bare pointer convention: statically-shaped memref is compatible with an
1376     // LLVM pointer to the element type.
1377     if (auto ptrType = llvmType.dyn_cast<LLVMPointerType>()) {
1378       if (!memrefType.hasStaticShape())
1379         return op->emitOpError(
1380             "unexpected bare pointer for dynamically shaped memref");
1381       if (memrefType.getMemorySpaceAsInt() != ptrType.getAddressSpace())
1382         return op->emitError("invalid conversion between memref and pointer in "
1383                              "different memory spaces");
1384 
1385       return verifyCast(op, ptrType.getElementType(),
1386                         memrefType.getElementType(), /*isElement=*/true);
1387     }
1388 
1389     // Otherwise, memrefs are convertible to a descriptor, which is a structure
1390     // type.
1391     auto structType = llvmType.dyn_cast<LLVMStructType>();
1392     if (!structType)
1393       return op->emitOpError("invalid cast between a memref and a type other "
1394                              "than pointer or memref descriptor");
1395 
1396     unsigned expectedNumElements = memrefType.getRank() == 0 ? 3 : 5;
1397     if (structType.getBody().size() != expectedNumElements) {
1398       return op->emitOpError() << "expected memref descriptor with "
1399                                << expectedNumElements << " elements";
1400     }
1401 
1402     // The first two elements are pointers to the element type.
1403     auto allocatedPtr = structType.getBody()[0].dyn_cast<LLVMPointerType>();
1404     if (!allocatedPtr ||
1405         allocatedPtr.getAddressSpace() != memrefType.getMemorySpaceAsInt())
1406       return op->emitOpError("expected first element of a memref descriptor to "
1407                              "be a pointer in the address space of the memref");
1408     if (failed(verifyCast(op, allocatedPtr.getElementType(),
1409                           memrefType.getElementType(), /*isElement=*/true)))
1410       return failure();
1411 
1412     auto alignedPtr = structType.getBody()[1].dyn_cast<LLVMPointerType>();
1413     if (!alignedPtr ||
1414         alignedPtr.getAddressSpace() != memrefType.getMemorySpaceAsInt())
1415       return op->emitOpError(
1416           "expected second element of a memref descriptor to "
1417           "be a pointer in the address space of the memref");
1418     if (failed(verifyCast(op, alignedPtr.getElementType(),
1419                           memrefType.getElementType(), /*isElement=*/true)))
1420       return failure();
1421 
1422     // The second element (offset) is an equivalent of index.
1423     if (failed(verifyCastWithIndex(structType.getBody()[2])))
1424       return op->emitOpError("expected third element of a memref descriptor to "
1425                              "be index-compatible integers");
1426 
1427     // 0D memrefs don't have sizes/strides.
1428     if (memrefType.getRank() == 0)
1429       return success();
1430 
1431     // Sizes and strides are rank-sized arrays of `index` equivalents.
1432     auto sizes = structType.getBody()[3].dyn_cast<LLVMArrayType>();
1433     if (!sizes || failed(verifyCastWithIndex(sizes.getElementType())) ||
1434         sizes.getNumElements() != memrefType.getRank())
1435       return op->emitOpError(
1436           "expected fourth element of a memref descriptor "
1437           "to be an array of <rank> index-compatible integers");
1438 
1439     auto strides = structType.getBody()[4].dyn_cast<LLVMArrayType>();
1440     if (!strides || failed(verifyCastWithIndex(strides.getElementType())) ||
1441         strides.getNumElements() != memrefType.getRank())
1442       return op->emitOpError(
1443           "expected fifth element of a memref descriptor "
1444           "to be an array of <rank> index-compatible integers");
1445 
1446     return success();
1447   }
1448 
1449   // Unranked memrefs are compatible with their descriptors.
1450   if (auto unrankedMemrefType = type.dyn_cast<UnrankedMemRefType>()) {
1451     auto structType = llvmType.dyn_cast<LLVMStructType>();
1452     if (!structType || structType.getBody().size() != 2)
1453       return op->emitOpError(
1454           "expected descriptor to be a struct with two elements");
1455 
1456     if (failed(verifyCastWithIndex(structType.getBody()[0])))
1457       return op->emitOpError("expected first element of a memref descriptor to "
1458                              "be an index-compatible integer");
1459 
1460     auto ptrType = structType.getBody()[1].dyn_cast<LLVMPointerType>();
1461     auto ptrElementType =
1462         ptrType ? ptrType.getElementType().dyn_cast<IntegerType>() : nullptr;
1463     if (!ptrElementType || ptrElementType.getWidth() != 8)
1464       return op->emitOpError("expected second element of a memref descriptor "
1465                              "to be an !llvm.ptr<i8>");
1466 
1467     return success();
1468   }
1469 
1470   // Complex types are compatible with the two-element structs.
1471   if (auto complexType = type.dyn_cast<ComplexType>()) {
1472     auto structType = llvmType.dyn_cast<LLVMStructType>();
1473     if (!structType || structType.getBody().size() != 2 ||
1474         structType.getBody()[0] != structType.getBody()[1] ||
1475         structType.getBody()[0] != complexType.getElementType())
1476       return op->emitOpError("expected 'complex' to map to two-element struct "
1477                              "with identical element types");
1478     return success();
1479   }
1480 
1481   // Everything else is not supported.
1482   return op->emitError("unsupported cast");
1483 }
1484 
1485 static LogicalResult verify(DialectCastOp op) {
1486   if (isCompatibleType(op.getType()))
1487     return verifyCast(op, op.getType(), op.in().getType());
1488 
1489   if (!isCompatibleType(op.in().getType()))
1490     return op->emitOpError("expected one LLVM type and one built-in type");
1491 
1492   return verifyCast(op, op.in().getType(), op.getType());
1493 }
1494 
1495 // Parses one of the keywords provided in the list `keywords` and returns the
1496 // position of the parsed keyword in the list. If none of the keywords from the
1497 // list is parsed, returns -1.
1498 static int parseOptionalKeywordAlternative(OpAsmParser &parser,
1499                                            ArrayRef<StringRef> keywords) {
1500   for (auto en : llvm::enumerate(keywords)) {
1501     if (succeeded(parser.parseOptionalKeyword(en.value())))
1502       return en.index();
1503   }
1504   return -1;
1505 }
1506 
1507 namespace {
1508 template <typename Ty>
1509 struct EnumTraits {};
1510 
1511 #define REGISTER_ENUM_TYPE(Ty)                                                 \
1512   template <>                                                                  \
1513   struct EnumTraits<Ty> {                                                      \
1514     static StringRef stringify(Ty value) { return stringify##Ty(value); }      \
1515     static unsigned getMaxEnumVal() { return getMaxEnumValFor##Ty(); }         \
1516   }
1517 
1518 REGISTER_ENUM_TYPE(Linkage);
1519 REGISTER_ENUM_TYPE(UnnamedAddr);
1520 } // end namespace
1521 
1522 template <typename EnumTy>
1523 static ParseResult parseOptionalLLVMKeyword(OpAsmParser &parser,
1524                                             OperationState &result,
1525                                             StringRef name) {
1526   SmallVector<StringRef, 10> names;
1527   for (unsigned i = 0, e = getMaxEnumValForLinkage(); i <= e; ++i)
1528     names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
1529 
1530   int index = parseOptionalKeywordAlternative(parser, names);
1531   if (index == -1)
1532     return failure();
1533   result.addAttribute(name, parser.getBuilder().getI64IntegerAttr(index));
1534   return success();
1535 }
1536 
1537 // operation ::= `llvm.mlir.global` linkage? `constant`? `@` identifier
1538 //               `(` attribute? `)` align? attribute-list? (`:` type)? region?
1539 // align     ::= `align` `=` UINT64
1540 //
1541 // The type can be omitted for string attributes, in which case it will be
1542 // inferred from the value of the string as [strlen(value) x i8].
1543 static ParseResult parseGlobalOp(OpAsmParser &parser, OperationState &result) {
1544   if (failed(parseOptionalLLVMKeyword<Linkage>(parser, result,
1545                                                getLinkageAttrName())))
1546     result.addAttribute(getLinkageAttrName(),
1547                         parser.getBuilder().getI64IntegerAttr(
1548                             static_cast<int64_t>(LLVM::Linkage::External)));
1549 
1550   if (failed(parseOptionalLLVMKeyword<UnnamedAddr>(parser, result,
1551                                                    getUnnamedAddrAttrName())))
1552     result.addAttribute(getUnnamedAddrAttrName(),
1553                         parser.getBuilder().getI64IntegerAttr(
1554                             static_cast<int64_t>(LLVM::UnnamedAddr::None)));
1555 
1556   if (succeeded(parser.parseOptionalKeyword("constant")))
1557     result.addAttribute("constant", parser.getBuilder().getUnitAttr());
1558 
1559   StringAttr name;
1560   if (parser.parseSymbolName(name, SymbolTable::getSymbolAttrName(),
1561                              result.attributes) ||
1562       parser.parseLParen())
1563     return failure();
1564 
1565   Attribute value;
1566   if (parser.parseOptionalRParen()) {
1567     if (parser.parseAttribute(value, "value", result.attributes) ||
1568         parser.parseRParen())
1569       return failure();
1570   }
1571 
1572   SmallVector<Type, 1> types;
1573   if (parser.parseOptionalAttrDict(result.attributes) ||
1574       parser.parseOptionalColonTypeList(types))
1575     return failure();
1576 
1577   if (types.size() > 1)
1578     return parser.emitError(parser.getNameLoc(), "expected zero or one type");
1579 
1580   Region &initRegion = *result.addRegion();
1581   if (types.empty()) {
1582     if (auto strAttr = value.dyn_cast_or_null<StringAttr>()) {
1583       MLIRContext *context = parser.getBuilder().getContext();
1584       auto arrayType = LLVM::LLVMArrayType::get(IntegerType::get(context, 8),
1585                                                 strAttr.getValue().size());
1586       types.push_back(arrayType);
1587     } else {
1588       return parser.emitError(parser.getNameLoc(),
1589                               "type can only be omitted for string globals");
1590     }
1591   } else {
1592     OptionalParseResult parseResult =
1593         parser.parseOptionalRegion(initRegion, /*arguments=*/{},
1594                                    /*argTypes=*/{});
1595     if (parseResult.hasValue() && failed(*parseResult))
1596       return failure();
1597   }
1598 
1599   result.addAttribute("type", TypeAttr::get(types[0]));
1600   return success();
1601 }
1602 
1603 static bool isZeroAttribute(Attribute value) {
1604   if (auto intValue = value.dyn_cast<IntegerAttr>())
1605     return intValue.getValue().isNullValue();
1606   if (auto fpValue = value.dyn_cast<FloatAttr>())
1607     return fpValue.getValue().isZero();
1608   if (auto splatValue = value.dyn_cast<SplatElementsAttr>())
1609     return isZeroAttribute(splatValue.getSplatValue());
1610   if (auto elementsValue = value.dyn_cast<ElementsAttr>())
1611     return llvm::all_of(elementsValue.getValues<Attribute>(), isZeroAttribute);
1612   if (auto arrayValue = value.dyn_cast<ArrayAttr>())
1613     return llvm::all_of(arrayValue.getValue(), isZeroAttribute);
1614   return false;
1615 }
1616 
1617 static LogicalResult verify(GlobalOp op) {
1618   if (!LLVMPointerType::isValidElementType(op.getType()))
1619     return op.emitOpError(
1620         "expects type to be a valid element type for an LLVM pointer");
1621   if (op->getParentOp() && !satisfiesLLVMModule(op->getParentOp()))
1622     return op.emitOpError("must appear at the module level");
1623 
1624   if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
1625     auto type = op.getType().dyn_cast<LLVMArrayType>();
1626     IntegerType elementType =
1627         type ? type.getElementType().dyn_cast<IntegerType>() : nullptr;
1628     if (!elementType || elementType.getWidth() != 8 ||
1629         type.getNumElements() != strAttr.getValue().size())
1630       return op.emitOpError(
1631           "requires an i8 array type of the length equal to that of the string "
1632           "attribute");
1633   }
1634 
1635   if (Block *b = op.getInitializerBlock()) {
1636     ReturnOp ret = cast<ReturnOp>(b->getTerminator());
1637     if (ret.operand_type_begin() == ret.operand_type_end())
1638       return op.emitOpError("initializer region cannot return void");
1639     if (*ret.operand_type_begin() != op.getType())
1640       return op.emitOpError("initializer region type ")
1641              << *ret.operand_type_begin() << " does not match global type "
1642              << op.getType();
1643 
1644     if (op.getValueOrNull())
1645       return op.emitOpError("cannot have both initializer value and region");
1646   }
1647 
1648   if (op.linkage() == Linkage::Common) {
1649     if (Attribute value = op.getValueOrNull()) {
1650       if (!isZeroAttribute(value)) {
1651         return op.emitOpError()
1652                << "expected zero value for '"
1653                << stringifyLinkage(Linkage::Common) << "' linkage";
1654       }
1655     }
1656   }
1657 
1658   if (op.linkage() == Linkage::Appending) {
1659     if (!op.getType().isa<LLVMArrayType>()) {
1660       return op.emitOpError()
1661              << "expected array type for '"
1662              << stringifyLinkage(Linkage::Appending) << "' linkage";
1663     }
1664   }
1665 
1666   Optional<uint64_t> alignAttr = op.alignment();
1667   if (alignAttr.hasValue()) {
1668     uint64_t value = alignAttr.getValue();
1669     if (!llvm::isPowerOf2_64(value))
1670       return op->emitError() << "alignment attribute is not a power of 2";
1671   }
1672 
1673   return success();
1674 }
1675 
1676 //===----------------------------------------------------------------------===//
1677 // Printing/parsing for LLVM::ShuffleVectorOp.
1678 //===----------------------------------------------------------------------===//
1679 // Expects vector to be of wrapped LLVM vector type and position to be of
1680 // wrapped LLVM i32 type.
1681 void LLVM::ShuffleVectorOp::build(OpBuilder &b, OperationState &result,
1682                                   Value v1, Value v2, ArrayAttr mask,
1683                                   ArrayRef<NamedAttribute> attrs) {
1684   auto containerType = v1.getType();
1685   auto vType = LLVM::getFixedVectorType(
1686       LLVM::getVectorElementType(containerType), mask.size());
1687   build(b, result, vType, v1, v2, mask);
1688   result.addAttributes(attrs);
1689 }
1690 
1691 static void printShuffleVectorOp(OpAsmPrinter &p, ShuffleVectorOp &op) {
1692   p << op.getOperationName() << ' ' << op.v1() << ", " << op.v2() << " "
1693     << op.mask();
1694   p.printOptionalAttrDict(op->getAttrs(), {"mask"});
1695   p << " : " << op.v1().getType() << ", " << op.v2().getType();
1696 }
1697 
1698 // <operation> ::= `llvm.shufflevector` ssa-use `, ` ssa-use
1699 //                 `[` integer-literal (`,` integer-literal)* `]`
1700 //                 attribute-dict? `:` type
1701 static ParseResult parseShuffleVectorOp(OpAsmParser &parser,
1702                                         OperationState &result) {
1703   llvm::SMLoc loc;
1704   OpAsmParser::OperandType v1, v2;
1705   ArrayAttr maskAttr;
1706   Type typeV1, typeV2;
1707   if (parser.getCurrentLocation(&loc) || parser.parseOperand(v1) ||
1708       parser.parseComma() || parser.parseOperand(v2) ||
1709       parser.parseAttribute(maskAttr, "mask", result.attributes) ||
1710       parser.parseOptionalAttrDict(result.attributes) ||
1711       parser.parseColonType(typeV1) || parser.parseComma() ||
1712       parser.parseType(typeV2) ||
1713       parser.resolveOperand(v1, typeV1, result.operands) ||
1714       parser.resolveOperand(v2, typeV2, result.operands))
1715     return failure();
1716   if (!LLVM::isCompatibleVectorType(typeV1))
1717     return parser.emitError(
1718         loc, "expected LLVM IR dialect vector type for operand #1");
1719   auto vType = LLVM::getFixedVectorType(LLVM::getVectorElementType(typeV1),
1720                                         maskAttr.size());
1721   result.addTypes(vType);
1722   return success();
1723 }
1724 
1725 //===----------------------------------------------------------------------===//
1726 // Implementations for LLVM::LLVMFuncOp.
1727 //===----------------------------------------------------------------------===//
1728 
1729 // Add the entry block to the function.
1730 Block *LLVMFuncOp::addEntryBlock() {
1731   assert(empty() && "function already has an entry block");
1732   assert(!isVarArg() && "unimplemented: non-external variadic functions");
1733 
1734   auto *entry = new Block;
1735   push_back(entry);
1736 
1737   LLVMFunctionType type = getType();
1738   for (unsigned i = 0, e = type.getNumParams(); i < e; ++i)
1739     entry->addArgument(type.getParamType(i));
1740   return entry;
1741 }
1742 
1743 void LLVMFuncOp::build(OpBuilder &builder, OperationState &result,
1744                        StringRef name, Type type, LLVM::Linkage linkage,
1745                        ArrayRef<NamedAttribute> attrs,
1746                        ArrayRef<DictionaryAttr> argAttrs) {
1747   result.addRegion();
1748   result.addAttribute(SymbolTable::getSymbolAttrName(),
1749                       builder.getStringAttr(name));
1750   result.addAttribute("type", TypeAttr::get(type));
1751   result.addAttribute(getLinkageAttrName(),
1752                       builder.getI64IntegerAttr(static_cast<int64_t>(linkage)));
1753   result.attributes.append(attrs.begin(), attrs.end());
1754   if (argAttrs.empty())
1755     return;
1756 
1757   assert(type.cast<LLVMFunctionType>().getNumParams() == argAttrs.size() &&
1758          "expected as many argument attribute lists as arguments");
1759   function_like_impl::addArgAndResultAttrs(builder, result, argAttrs,
1760                                            /*resultAttrs=*/llvm::None);
1761 }
1762 
1763 // Builds an LLVM function type from the given lists of input and output types.
1764 // Returns a null type if any of the types provided are non-LLVM types, or if
1765 // there is more than one output type.
1766 static Type
1767 buildLLVMFunctionType(OpAsmParser &parser, llvm::SMLoc loc,
1768                       ArrayRef<Type> inputs, ArrayRef<Type> outputs,
1769                       function_like_impl::VariadicFlag variadicFlag) {
1770   Builder &b = parser.getBuilder();
1771   if (outputs.size() > 1) {
1772     parser.emitError(loc, "failed to construct function type: expected zero or "
1773                           "one function result");
1774     return {};
1775   }
1776 
1777   // Convert inputs to LLVM types, exit early on error.
1778   SmallVector<Type, 4> llvmInputs;
1779   for (auto t : inputs) {
1780     if (!isCompatibleType(t)) {
1781       parser.emitError(loc, "failed to construct function type: expected LLVM "
1782                             "type for function arguments");
1783       return {};
1784     }
1785     llvmInputs.push_back(t);
1786   }
1787 
1788   // No output is denoted as "void" in LLVM type system.
1789   Type llvmOutput =
1790       outputs.empty() ? LLVMVoidType::get(b.getContext()) : outputs.front();
1791   if (!isCompatibleType(llvmOutput)) {
1792     parser.emitError(loc, "failed to construct function type: expected LLVM "
1793                           "type for function results")
1794         << llvmOutput;
1795     return {};
1796   }
1797   return LLVMFunctionType::get(llvmOutput, llvmInputs,
1798                                variadicFlag.isVariadic());
1799 }
1800 
1801 // Parses an LLVM function.
1802 //
1803 // operation ::= `llvm.func` linkage? function-signature function-attributes?
1804 //               function-body
1805 //
1806 static ParseResult parseLLVMFuncOp(OpAsmParser &parser,
1807                                    OperationState &result) {
1808   // Default to external linkage if no keyword is provided.
1809   if (failed(parseOptionalLLVMKeyword<Linkage>(parser, result,
1810                                                getLinkageAttrName())))
1811     result.addAttribute(getLinkageAttrName(),
1812                         parser.getBuilder().getI64IntegerAttr(
1813                             static_cast<int64_t>(LLVM::Linkage::External)));
1814 
1815   StringAttr nameAttr;
1816   SmallVector<OpAsmParser::OperandType, 8> entryArgs;
1817   SmallVector<NamedAttrList, 1> argAttrs;
1818   SmallVector<NamedAttrList, 1> resultAttrs;
1819   SmallVector<Type, 8> argTypes;
1820   SmallVector<Type, 4> resultTypes;
1821   bool isVariadic;
1822 
1823   auto signatureLocation = parser.getCurrentLocation();
1824   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1825                              result.attributes) ||
1826       function_like_impl::parseFunctionSignature(
1827           parser, /*allowVariadic=*/true, entryArgs, argTypes, argAttrs,
1828           isVariadic, resultTypes, resultAttrs))
1829     return failure();
1830 
1831   auto type =
1832       buildLLVMFunctionType(parser, signatureLocation, argTypes, resultTypes,
1833                             function_like_impl::VariadicFlag(isVariadic));
1834   if (!type)
1835     return failure();
1836   result.addAttribute(function_like_impl::getTypeAttrName(),
1837                       TypeAttr::get(type));
1838 
1839   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
1840     return failure();
1841   function_like_impl::addArgAndResultAttrs(parser.getBuilder(), result,
1842                                            argAttrs, resultAttrs);
1843 
1844   auto *body = result.addRegion();
1845   OptionalParseResult parseResult = parser.parseOptionalRegion(
1846       *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes);
1847   return failure(parseResult.hasValue() && failed(*parseResult));
1848 }
1849 
1850 // Print the LLVMFuncOp. Collects argument and result types and passes them to
1851 // helper functions. Drops "void" result since it cannot be parsed back. Skips
1852 // the external linkage since it is the default value.
1853 static void printLLVMFuncOp(OpAsmPrinter &p, LLVMFuncOp op) {
1854   p << op.getOperationName() << ' ';
1855   if (op.linkage() != LLVM::Linkage::External)
1856     p << stringifyLinkage(op.linkage()) << ' ';
1857   p.printSymbolName(op.getName());
1858 
1859   LLVMFunctionType fnType = op.getType();
1860   SmallVector<Type, 8> argTypes;
1861   SmallVector<Type, 1> resTypes;
1862   argTypes.reserve(fnType.getNumParams());
1863   for (unsigned i = 0, e = fnType.getNumParams(); i < e; ++i)
1864     argTypes.push_back(fnType.getParamType(i));
1865 
1866   Type returnType = fnType.getReturnType();
1867   if (!returnType.isa<LLVMVoidType>())
1868     resTypes.push_back(returnType);
1869 
1870   function_like_impl::printFunctionSignature(p, op, argTypes, op.isVarArg(),
1871                                              resTypes);
1872   function_like_impl::printFunctionAttributes(
1873       p, op, argTypes.size(), resTypes.size(), {getLinkageAttrName()});
1874 
1875   // Print the body if this is not an external function.
1876   Region &body = op.body();
1877   if (!body.empty())
1878     p.printRegion(body, /*printEntryBlockArgs=*/false,
1879                   /*printBlockTerminators=*/true);
1880 }
1881 
1882 // Hook for OpTrait::FunctionLike, called after verifying that the 'type'
1883 // attribute is present.  This can check for preconditions of the
1884 // getNumArguments hook not failing.
1885 LogicalResult LLVMFuncOp::verifyType() {
1886   auto llvmType = getTypeAttr().getValue().dyn_cast_or_null<LLVMFunctionType>();
1887   if (!llvmType)
1888     return emitOpError("requires '" + getTypeAttrName() +
1889                        "' attribute of wrapped LLVM function type");
1890 
1891   return success();
1892 }
1893 
1894 // Hook for OpTrait::FunctionLike, returns the number of function arguments.
1895 // Depends on the type attribute being correct as checked by verifyType
1896 unsigned LLVMFuncOp::getNumFuncArguments() { return getType().getNumParams(); }
1897 
1898 // Hook for OpTrait::FunctionLike, returns the number of function results.
1899 // Depends on the type attribute being correct as checked by verifyType
1900 unsigned LLVMFuncOp::getNumFuncResults() {
1901   // We model LLVM functions that return void as having zero results,
1902   // and all others as having one result.
1903   // If we modeled a void return as one result, then it would be possible to
1904   // attach an MLIR result attribute to it, and it isn't clear what semantics we
1905   // would assign to that.
1906   if (getType().getReturnType().isa<LLVMVoidType>())
1907     return 0;
1908   return 1;
1909 }
1910 
1911 // Verifies LLVM- and implementation-specific properties of the LLVM func Op:
1912 // - functions don't have 'common' linkage
1913 // - external functions have 'external' or 'extern_weak' linkage;
1914 // - vararg is (currently) only supported for external functions;
1915 // - entry block arguments are of LLVM types and match the function signature.
1916 static LogicalResult verify(LLVMFuncOp op) {
1917   if (op.linkage() == LLVM::Linkage::Common)
1918     return op.emitOpError()
1919            << "functions cannot have '"
1920            << stringifyLinkage(LLVM::Linkage::Common) << "' linkage";
1921 
1922   if (op.isExternal()) {
1923     if (op.linkage() != LLVM::Linkage::External &&
1924         op.linkage() != LLVM::Linkage::ExternWeak)
1925       return op.emitOpError()
1926              << "external functions must have '"
1927              << stringifyLinkage(LLVM::Linkage::External) << "' or '"
1928              << stringifyLinkage(LLVM::Linkage::ExternWeak) << "' linkage";
1929     return success();
1930   }
1931 
1932   if (op.isVarArg())
1933     return op.emitOpError("only external functions can be variadic");
1934 
1935   unsigned numArguments = op.getType().getNumParams();
1936   Block &entryBlock = op.front();
1937   for (unsigned i = 0; i < numArguments; ++i) {
1938     Type argType = entryBlock.getArgument(i).getType();
1939     if (!isCompatibleType(argType))
1940       return op.emitOpError("entry block argument #")
1941              << i << " is not of LLVM type";
1942     if (op.getType().getParamType(i) != argType)
1943       return op.emitOpError("the type of entry block argument #")
1944              << i << " does not match the function signature";
1945   }
1946 
1947   return success();
1948 }
1949 
1950 //===----------------------------------------------------------------------===//
1951 // Verification for LLVM::ConstantOp.
1952 //===----------------------------------------------------------------------===//
1953 
1954 static LogicalResult verify(LLVM::ConstantOp op) {
1955   if (StringAttr sAttr = op.value().dyn_cast<StringAttr>()) {
1956     auto arrayType = op.getType().dyn_cast<LLVMArrayType>();
1957     if (!arrayType || arrayType.getNumElements() != sAttr.getValue().size() ||
1958         !arrayType.getElementType().isInteger(8)) {
1959       return op->emitOpError()
1960              << "expected array type of " << sAttr.getValue().size()
1961              << " i8 elements for the string constant";
1962     }
1963     return success();
1964   }
1965   if (!op.value().isa<IntegerAttr, FloatAttr, ElementsAttr>())
1966     return op.emitOpError()
1967            << "only supports integer, float, string or elements attributes";
1968   return success();
1969 }
1970 
1971 //===----------------------------------------------------------------------===//
1972 // Utility functions for parsing atomic ops
1973 //===----------------------------------------------------------------------===//
1974 
1975 // Helper function to parse a keyword into the specified attribute named by
1976 // `attrName`. The keyword must match one of the string values defined by the
1977 // AtomicBinOp enum. The resulting I64 attribute is added to the `result`
1978 // state.
1979 static ParseResult parseAtomicBinOp(OpAsmParser &parser, OperationState &result,
1980                                     StringRef attrName) {
1981   llvm::SMLoc loc;
1982   StringRef keyword;
1983   if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&keyword))
1984     return failure();
1985 
1986   // Replace the keyword `keyword` with an integer attribute.
1987   auto kind = symbolizeAtomicBinOp(keyword);
1988   if (!kind) {
1989     return parser.emitError(loc)
1990            << "'" << keyword << "' is an incorrect value of the '" << attrName
1991            << "' attribute";
1992   }
1993 
1994   auto value = static_cast<int64_t>(kind.getValue());
1995   auto attr = parser.getBuilder().getI64IntegerAttr(value);
1996   result.addAttribute(attrName, attr);
1997 
1998   return success();
1999 }
2000 
2001 // Helper function to parse a keyword into the specified attribute named by
2002 // `attrName`. The keyword must match one of the string values defined by the
2003 // AtomicOrdering enum. The resulting I64 attribute is added to the `result`
2004 // state.
2005 static ParseResult parseAtomicOrdering(OpAsmParser &parser,
2006                                        OperationState &result,
2007                                        StringRef attrName) {
2008   llvm::SMLoc loc;
2009   StringRef ordering;
2010   if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&ordering))
2011     return failure();
2012 
2013   // Replace the keyword `ordering` with an integer attribute.
2014   auto kind = symbolizeAtomicOrdering(ordering);
2015   if (!kind) {
2016     return parser.emitError(loc)
2017            << "'" << ordering << "' is an incorrect value of the '" << attrName
2018            << "' attribute";
2019   }
2020 
2021   auto value = static_cast<int64_t>(kind.getValue());
2022   auto attr = parser.getBuilder().getI64IntegerAttr(value);
2023   result.addAttribute(attrName, attr);
2024 
2025   return success();
2026 }
2027 
2028 //===----------------------------------------------------------------------===//
2029 // Printer, parser and verifier for LLVM::AtomicRMWOp.
2030 //===----------------------------------------------------------------------===//
2031 
2032 static void printAtomicRMWOp(OpAsmPrinter &p, AtomicRMWOp &op) {
2033   p << op.getOperationName() << ' ' << stringifyAtomicBinOp(op.bin_op()) << ' '
2034     << op.ptr() << ", " << op.val() << ' '
2035     << stringifyAtomicOrdering(op.ordering()) << ' ';
2036   p.printOptionalAttrDict(op->getAttrs(), {"bin_op", "ordering"});
2037   p << " : " << op.res().getType();
2038 }
2039 
2040 // <operation> ::= `llvm.atomicrmw` keyword ssa-use `,` ssa-use keyword
2041 //                 attribute-dict? `:` type
2042 static ParseResult parseAtomicRMWOp(OpAsmParser &parser,
2043                                     OperationState &result) {
2044   Type type;
2045   OpAsmParser::OperandType ptr, val;
2046   if (parseAtomicBinOp(parser, result, "bin_op") || parser.parseOperand(ptr) ||
2047       parser.parseComma() || parser.parseOperand(val) ||
2048       parseAtomicOrdering(parser, result, "ordering") ||
2049       parser.parseOptionalAttrDict(result.attributes) ||
2050       parser.parseColonType(type) ||
2051       parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type),
2052                             result.operands) ||
2053       parser.resolveOperand(val, type, result.operands))
2054     return failure();
2055 
2056   result.addTypes(type);
2057   return success();
2058 }
2059 
2060 static LogicalResult verify(AtomicRMWOp op) {
2061   auto ptrType = op.ptr().getType().cast<LLVM::LLVMPointerType>();
2062   auto valType = op.val().getType();
2063   if (valType != ptrType.getElementType())
2064     return op.emitOpError("expected LLVM IR element type for operand #0 to "
2065                           "match type for operand #1");
2066   auto resType = op.res().getType();
2067   if (resType != valType)
2068     return op.emitOpError(
2069         "expected LLVM IR result type to match type for operand #1");
2070   if (op.bin_op() == AtomicBinOp::fadd || op.bin_op() == AtomicBinOp::fsub) {
2071     if (!mlir::LLVM::isCompatibleFloatingPointType(valType))
2072       return op.emitOpError("expected LLVM IR floating point type");
2073   } else if (op.bin_op() == AtomicBinOp::xchg) {
2074     auto intType = valType.dyn_cast<IntegerType>();
2075     unsigned intBitWidth = intType ? intType.getWidth() : 0;
2076     if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 &&
2077         intBitWidth != 64 && !valType.isa<BFloat16Type>() &&
2078         !valType.isa<Float16Type>() && !valType.isa<Float32Type>() &&
2079         !valType.isa<Float64Type>())
2080       return op.emitOpError("unexpected LLVM IR type for 'xchg' bin_op");
2081   } else {
2082     auto intType = valType.dyn_cast<IntegerType>();
2083     unsigned intBitWidth = intType ? intType.getWidth() : 0;
2084     if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 &&
2085         intBitWidth != 64)
2086       return op.emitOpError("expected LLVM IR integer type");
2087   }
2088 
2089   if (static_cast<unsigned>(op.ordering()) <
2090       static_cast<unsigned>(AtomicOrdering::monotonic))
2091     return op.emitOpError()
2092            << "expected at least '"
2093            << stringifyAtomicOrdering(AtomicOrdering::monotonic)
2094            << "' ordering";
2095 
2096   return success();
2097 }
2098 
2099 //===----------------------------------------------------------------------===//
2100 // Printer, parser and verifier for LLVM::AtomicCmpXchgOp.
2101 //===----------------------------------------------------------------------===//
2102 
2103 static void printAtomicCmpXchgOp(OpAsmPrinter &p, AtomicCmpXchgOp &op) {
2104   p << op.getOperationName() << ' ' << op.ptr() << ", " << op.cmp() << ", "
2105     << op.val() << ' ' << stringifyAtomicOrdering(op.success_ordering()) << ' '
2106     << stringifyAtomicOrdering(op.failure_ordering());
2107   p.printOptionalAttrDict(op->getAttrs(),
2108                           {"success_ordering", "failure_ordering"});
2109   p << " : " << op.val().getType();
2110 }
2111 
2112 // <operation> ::= `llvm.cmpxchg` ssa-use `,` ssa-use `,` ssa-use
2113 //                 keyword keyword attribute-dict? `:` type
2114 static ParseResult parseAtomicCmpXchgOp(OpAsmParser &parser,
2115                                         OperationState &result) {
2116   auto &builder = parser.getBuilder();
2117   Type type;
2118   OpAsmParser::OperandType ptr, cmp, val;
2119   if (parser.parseOperand(ptr) || parser.parseComma() ||
2120       parser.parseOperand(cmp) || parser.parseComma() ||
2121       parser.parseOperand(val) ||
2122       parseAtomicOrdering(parser, result, "success_ordering") ||
2123       parseAtomicOrdering(parser, result, "failure_ordering") ||
2124       parser.parseOptionalAttrDict(result.attributes) ||
2125       parser.parseColonType(type) ||
2126       parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type),
2127                             result.operands) ||
2128       parser.resolveOperand(cmp, type, result.operands) ||
2129       parser.resolveOperand(val, type, result.operands))
2130     return failure();
2131 
2132   auto boolType = IntegerType::get(builder.getContext(), 1);
2133   auto resultType =
2134       LLVMStructType::getLiteral(builder.getContext(), {type, boolType});
2135   result.addTypes(resultType);
2136 
2137   return success();
2138 }
2139 
2140 static LogicalResult verify(AtomicCmpXchgOp op) {
2141   auto ptrType = op.ptr().getType().cast<LLVM::LLVMPointerType>();
2142   if (!ptrType)
2143     return op.emitOpError("expected LLVM IR pointer type for operand #0");
2144   auto cmpType = op.cmp().getType();
2145   auto valType = op.val().getType();
2146   if (cmpType != ptrType.getElementType() || cmpType != valType)
2147     return op.emitOpError("expected LLVM IR element type for operand #0 to "
2148                           "match type for all other operands");
2149   auto intType = valType.dyn_cast<IntegerType>();
2150   unsigned intBitWidth = intType ? intType.getWidth() : 0;
2151   if (!valType.isa<LLVMPointerType>() && intBitWidth != 8 &&
2152       intBitWidth != 16 && intBitWidth != 32 && intBitWidth != 64 &&
2153       !valType.isa<BFloat16Type>() && !valType.isa<Float16Type>() &&
2154       !valType.isa<Float32Type>() && !valType.isa<Float64Type>())
2155     return op.emitOpError("unexpected LLVM IR type");
2156   if (op.success_ordering() < AtomicOrdering::monotonic ||
2157       op.failure_ordering() < AtomicOrdering::monotonic)
2158     return op.emitOpError("ordering must be at least 'monotonic'");
2159   if (op.failure_ordering() == AtomicOrdering::release ||
2160       op.failure_ordering() == AtomicOrdering::acq_rel)
2161     return op.emitOpError("failure ordering cannot be 'release' or 'acq_rel'");
2162   return success();
2163 }
2164 
2165 //===----------------------------------------------------------------------===//
2166 // Printer, parser and verifier for LLVM::FenceOp.
2167 //===----------------------------------------------------------------------===//
2168 
2169 // <operation> ::= `llvm.fence` (`syncscope(`strAttr`)`)? keyword
2170 // attribute-dict?
2171 static ParseResult parseFenceOp(OpAsmParser &parser, OperationState &result) {
2172   StringAttr sScope;
2173   StringRef syncscopeKeyword = "syncscope";
2174   if (!failed(parser.parseOptionalKeyword(syncscopeKeyword))) {
2175     if (parser.parseLParen() ||
2176         parser.parseAttribute(sScope, syncscopeKeyword, result.attributes) ||
2177         parser.parseRParen())
2178       return failure();
2179   } else {
2180     result.addAttribute(syncscopeKeyword,
2181                         parser.getBuilder().getStringAttr(""));
2182   }
2183   if (parseAtomicOrdering(parser, result, "ordering") ||
2184       parser.parseOptionalAttrDict(result.attributes))
2185     return failure();
2186   return success();
2187 }
2188 
2189 static void printFenceOp(OpAsmPrinter &p, FenceOp &op) {
2190   StringRef syncscopeKeyword = "syncscope";
2191   p << op.getOperationName() << ' ';
2192   if (!op->getAttr(syncscopeKeyword).cast<StringAttr>().getValue().empty())
2193     p << "syncscope(" << op->getAttr(syncscopeKeyword) << ") ";
2194   p << stringifyAtomicOrdering(op.ordering());
2195 }
2196 
2197 static LogicalResult verify(FenceOp &op) {
2198   if (op.ordering() == AtomicOrdering::not_atomic ||
2199       op.ordering() == AtomicOrdering::unordered ||
2200       op.ordering() == AtomicOrdering::monotonic)
2201     return op.emitOpError("can be given only acquire, release, acq_rel, "
2202                           "and seq_cst orderings");
2203   return success();
2204 }
2205 
2206 //===----------------------------------------------------------------------===//
2207 // LLVMDialect initialization, type parsing, and registration.
2208 //===----------------------------------------------------------------------===//
2209 
2210 void LLVMDialect::initialize() {
2211   addAttributes<FMFAttr, LoopOptionsAttr>();
2212 
2213   // clang-format off
2214   addTypes<LLVMVoidType,
2215            LLVMPPCFP128Type,
2216            LLVMX86MMXType,
2217            LLVMTokenType,
2218            LLVMLabelType,
2219            LLVMMetadataType,
2220            LLVMFunctionType,
2221            LLVMPointerType,
2222            LLVMFixedVectorType,
2223            LLVMScalableVectorType,
2224            LLVMArrayType,
2225            LLVMStructType>();
2226   // clang-format on
2227   addOperations<
2228 #define GET_OP_LIST
2229 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc"
2230       >();
2231 
2232   // Support unknown operations because not all LLVM operations are registered.
2233   allowUnknownOperations();
2234 }
2235 
2236 #define GET_OP_CLASSES
2237 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc"
2238 
2239 /// Parse a type registered to this dialect.
2240 Type LLVMDialect::parseType(DialectAsmParser &parser) const {
2241   return detail::parseType(parser);
2242 }
2243 
2244 /// Print a type registered to this dialect.
2245 void LLVMDialect::printType(Type type, DialectAsmPrinter &os) const {
2246   return detail::printType(type, os);
2247 }
2248 
2249 LogicalResult LLVMDialect::verifyDataLayoutString(
2250     StringRef descr, llvm::function_ref<void(const Twine &)> reportError) {
2251   llvm::Expected<llvm::DataLayout> maybeDataLayout =
2252       llvm::DataLayout::parse(descr);
2253   if (maybeDataLayout)
2254     return success();
2255 
2256   std::string message;
2257   llvm::raw_string_ostream messageStream(message);
2258   llvm::logAllUnhandledErrors(maybeDataLayout.takeError(), messageStream);
2259   reportError("invalid data layout descriptor: " + messageStream.str());
2260   return failure();
2261 }
2262 
2263 /// Verify LLVM dialect attributes.
2264 LogicalResult LLVMDialect::verifyOperationAttribute(Operation *op,
2265                                                     NamedAttribute attr) {
2266   // If the `llvm.loop` attribute is present, enforce the following structure,
2267   // which the module translation can assume.
2268   if (attr.first.strref() == LLVMDialect::getLoopAttrName()) {
2269     auto loopAttr = attr.second.dyn_cast<DictionaryAttr>();
2270     if (!loopAttr)
2271       return op->emitOpError() << "expected '" << LLVMDialect::getLoopAttrName()
2272                                << "' to be a dictionary attribute";
2273     Optional<NamedAttribute> parallelAccessGroup =
2274         loopAttr.getNamed(LLVMDialect::getParallelAccessAttrName());
2275     if (parallelAccessGroup.hasValue()) {
2276       auto accessGroups = parallelAccessGroup->second.dyn_cast<ArrayAttr>();
2277       if (!accessGroups)
2278         return op->emitOpError()
2279                << "expected '" << LLVMDialect::getParallelAccessAttrName()
2280                << "' to be an array attribute";
2281       for (Attribute attr : accessGroups) {
2282         auto accessGroupRef = attr.dyn_cast<SymbolRefAttr>();
2283         if (!accessGroupRef)
2284           return op->emitOpError()
2285                  << "expected '" << attr << "' to be a symbol reference";
2286         StringRef metadataName = accessGroupRef.getRootReference();
2287         auto metadataOp =
2288             SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
2289                 op->getParentOp(), metadataName);
2290         if (!metadataOp)
2291           return op->emitOpError()
2292                  << "expected '" << attr << "' to reference a metadata op";
2293         StringRef accessGroupName = accessGroupRef.getLeafReference();
2294         Operation *accessGroupOp =
2295             SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
2296         if (!accessGroupOp)
2297           return op->emitOpError()
2298                  << "expected '" << attr << "' to reference an access_group op";
2299       }
2300     }
2301 
2302     Optional<NamedAttribute> loopOptions =
2303         loopAttr.getNamed(LLVMDialect::getLoopOptionsAttrName());
2304     if (loopOptions.hasValue() && !loopOptions->second.isa<LoopOptionsAttr>())
2305       return op->emitOpError()
2306              << "expected '" << LLVMDialect::getLoopOptionsAttrName()
2307              << "' to be a `loopopts` attribute";
2308   }
2309 
2310   // If the data layout attribute is present, it must use the LLVM data layout
2311   // syntax. Try parsing it and report errors in case of failure. Users of this
2312   // attribute may assume it is well-formed and can pass it to the (asserting)
2313   // llvm::DataLayout constructor.
2314   if (attr.first.strref() != LLVM::LLVMDialect::getDataLayoutAttrName())
2315     return success();
2316   if (auto stringAttr = attr.second.dyn_cast<StringAttr>())
2317     return verifyDataLayoutString(
2318         stringAttr.getValue(),
2319         [op](const Twine &message) { op->emitOpError() << message.str(); });
2320 
2321   return op->emitOpError() << "expected '"
2322                            << LLVM::LLVMDialect::getDataLayoutAttrName()
2323                            << "' to be a string attribute";
2324 }
2325 
2326 /// Verify LLVMIR function argument attributes.
2327 LogicalResult LLVMDialect::verifyRegionArgAttribute(Operation *op,
2328                                                     unsigned regionIdx,
2329                                                     unsigned argIdx,
2330                                                     NamedAttribute argAttr) {
2331   // Check that llvm.noalias is a unit attribute.
2332   if (argAttr.first == LLVMDialect::getNoAliasAttrName() &&
2333       !argAttr.second.isa<UnitAttr>())
2334     return op->emitError()
2335            << "expected llvm.noalias argument attribute to be a unit attribute";
2336   // Check that llvm.align is an integer attribute.
2337   if (argAttr.first == LLVMDialect::getAlignAttrName() &&
2338       !argAttr.second.isa<IntegerAttr>())
2339     return op->emitError()
2340            << "llvm.align argument attribute of non integer type";
2341   return success();
2342 }
2343 
2344 //===----------------------------------------------------------------------===//
2345 // Utility functions.
2346 //===----------------------------------------------------------------------===//
2347 
2348 Value mlir::LLVM::createGlobalString(Location loc, OpBuilder &builder,
2349                                      StringRef name, StringRef value,
2350                                      LLVM::Linkage linkage) {
2351   assert(builder.getInsertionBlock() &&
2352          builder.getInsertionBlock()->getParentOp() &&
2353          "expected builder to point to a block constrained in an op");
2354   auto module =
2355       builder.getInsertionBlock()->getParentOp()->getParentOfType<ModuleOp>();
2356   assert(module && "builder points to an op outside of a module");
2357 
2358   // Create the global at the entry of the module.
2359   OpBuilder moduleBuilder(module.getBodyRegion(), builder.getListener());
2360   MLIRContext *ctx = builder.getContext();
2361   auto type = LLVM::LLVMArrayType::get(IntegerType::get(ctx, 8), value.size());
2362   auto global = moduleBuilder.create<LLVM::GlobalOp>(
2363       loc, type, /*isConstant=*/true, linkage, name,
2364       builder.getStringAttr(value), /*alignment=*/0);
2365 
2366   // Get the pointer to the first character in the global string.
2367   Value globalPtr = builder.create<LLVM::AddressOfOp>(loc, global);
2368   Value cst0 = builder.create<LLVM::ConstantOp>(
2369       loc, IntegerType::get(ctx, 64),
2370       builder.getIntegerAttr(builder.getIndexType(), 0));
2371   return builder.create<LLVM::GEPOp>(
2372       loc, LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8)), globalPtr,
2373       ValueRange{cst0, cst0});
2374 }
2375 
2376 bool mlir::LLVM::satisfiesLLVMModule(Operation *op) {
2377   return op->hasTrait<OpTrait::SymbolTable>() &&
2378          op->hasTrait<OpTrait::IsIsolatedFromAbove>();
2379 }
2380 
2381 static constexpr const FastmathFlags FastmathFlagsList[] = {
2382     // clang-format off
2383     FastmathFlags::nnan,
2384     FastmathFlags::ninf,
2385     FastmathFlags::nsz,
2386     FastmathFlags::arcp,
2387     FastmathFlags::contract,
2388     FastmathFlags::afn,
2389     FastmathFlags::reassoc,
2390     FastmathFlags::fast,
2391     // clang-format on
2392 };
2393 
2394 void FMFAttr::print(DialectAsmPrinter &printer) const {
2395   printer << "fastmath<";
2396   auto flags = llvm::make_filter_range(FastmathFlagsList, [&](auto flag) {
2397     return bitEnumContains(this->getFlags(), flag);
2398   });
2399   llvm::interleaveComma(flags, printer,
2400                         [&](auto flag) { printer << stringifyEnum(flag); });
2401   printer << ">";
2402 }
2403 
2404 Attribute FMFAttr::parse(MLIRContext *context, DialectAsmParser &parser,
2405                          Type type) {
2406   if (failed(parser.parseLess()))
2407     return {};
2408 
2409   FastmathFlags flags = {};
2410   if (failed(parser.parseOptionalGreater())) {
2411     do {
2412       StringRef elemName;
2413       if (failed(parser.parseKeyword(&elemName)))
2414         return {};
2415 
2416       auto elem = symbolizeFastmathFlags(elemName);
2417       if (!elem) {
2418         parser.emitError(parser.getNameLoc(), "Unknown fastmath flag: ")
2419             << elemName;
2420         return {};
2421       }
2422 
2423       flags = flags | *elem;
2424     } while (succeeded(parser.parseOptionalComma()));
2425 
2426     if (failed(parser.parseGreater()))
2427       return {};
2428   }
2429 
2430   return FMFAttr::get(parser.getBuilder().getContext(), flags);
2431 }
2432 
2433 LoopOptionsAttrBuilder::LoopOptionsAttrBuilder(LoopOptionsAttr attr)
2434     : options(attr.getOptions().begin(), attr.getOptions().end()) {}
2435 
2436 template <typename T>
2437 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setOption(LoopOptionCase tag,
2438                                                           Optional<T> value) {
2439   auto option = llvm::find_if(
2440       options, [tag](auto option) { return option.first == tag; });
2441   if (option != options.end()) {
2442     if (value.hasValue())
2443       option->second = *value;
2444     else
2445       options.erase(option);
2446   } else {
2447     options.push_back(LoopOptionsAttr::OptionValuePair(tag, *value));
2448   }
2449   return *this;
2450 }
2451 
2452 LoopOptionsAttrBuilder &
2453 LoopOptionsAttrBuilder::setDisableLICM(Optional<bool> value) {
2454   return setOption(LoopOptionCase::disable_licm, value);
2455 }
2456 
2457 /// Set the `interleave_count` option to the provided value. If no value
2458 /// is provided the option is deleted.
2459 LoopOptionsAttrBuilder &
2460 LoopOptionsAttrBuilder::setInterleaveCount(Optional<uint64_t> count) {
2461   return setOption(LoopOptionCase::interleave_count, count);
2462 }
2463 
2464 /// Set the `disable_unroll` option to the provided value. If no value
2465 /// is provided the option is deleted.
2466 LoopOptionsAttrBuilder &
2467 LoopOptionsAttrBuilder::setDisableUnroll(Optional<bool> value) {
2468   return setOption(LoopOptionCase::disable_unroll, value);
2469 }
2470 
2471 /// Set the `disable_pipeline` option to the provided value. If no value
2472 /// is provided the option is deleted.
2473 LoopOptionsAttrBuilder &
2474 LoopOptionsAttrBuilder::setDisablePipeline(Optional<bool> value) {
2475   return setOption(LoopOptionCase::disable_pipeline, value);
2476 }
2477 
2478 /// Set the `pipeline_initiation_interval` option to the provided value.
2479 /// If no value is provided the option is deleted.
2480 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setPipelineInitiationInterval(
2481     Optional<uint64_t> count) {
2482   return setOption(LoopOptionCase::pipeline_initiation_interval, count);
2483 }
2484 
2485 template <typename T>
2486 static Optional<T>
2487 getOption(ArrayRef<std::pair<LoopOptionCase, int64_t>> options,
2488           LoopOptionCase option) {
2489   auto it =
2490       lower_bound(options, option, [](auto optionPair, LoopOptionCase option) {
2491         return optionPair.first < option;
2492       });
2493   if (it == options.end())
2494     return {};
2495   return static_cast<T>(it->second);
2496 }
2497 
2498 Optional<bool> LoopOptionsAttr::disableUnroll() {
2499   return getOption<bool>(getOptions(), LoopOptionCase::disable_unroll);
2500 }
2501 
2502 Optional<bool> LoopOptionsAttr::disableLICM() {
2503   return getOption<bool>(getOptions(), LoopOptionCase::disable_licm);
2504 }
2505 
2506 Optional<int64_t> LoopOptionsAttr::interleaveCount() {
2507   return getOption<int64_t>(getOptions(), LoopOptionCase::interleave_count);
2508 }
2509 
2510 /// Build the LoopOptions Attribute from a sorted array of individual options.
2511 LoopOptionsAttr LoopOptionsAttr::get(
2512     MLIRContext *context,
2513     ArrayRef<std::pair<LoopOptionCase, int64_t>> sortedOptions) {
2514   assert(llvm::is_sorted(sortedOptions, llvm::less_first()) &&
2515          "LoopOptionsAttr ctor expects a sorted options array");
2516   return Base::get(context, sortedOptions);
2517 }
2518 
2519 /// Build the LoopOptions Attribute from a sorted array of individual options.
2520 LoopOptionsAttr LoopOptionsAttr::get(MLIRContext *context,
2521                                      LoopOptionsAttrBuilder &optionBuilders) {
2522   llvm::sort(optionBuilders.options, llvm::less_first());
2523   return Base::get(context, optionBuilders.options);
2524 }
2525 
2526 void LoopOptionsAttr::print(DialectAsmPrinter &printer) const {
2527   printer << getMnemonic() << "<";
2528   llvm::interleaveComma(getOptions(), printer, [&](auto option) {
2529     printer << stringifyEnum(option.first) << " = ";
2530     switch (option.first) {
2531     case LoopOptionCase::disable_licm:
2532     case LoopOptionCase::disable_unroll:
2533     case LoopOptionCase::disable_pipeline:
2534       printer << (option.second ? "true" : "false");
2535       break;
2536     case LoopOptionCase::interleave_count:
2537     case LoopOptionCase::pipeline_initiation_interval:
2538       printer << option.second;
2539       break;
2540     }
2541   });
2542   printer << ">";
2543 }
2544 
2545 Attribute LoopOptionsAttr::parse(MLIRContext *context, DialectAsmParser &parser,
2546                                  Type type) {
2547   if (failed(parser.parseLess()))
2548     return {};
2549 
2550   SmallVector<std::pair<LoopOptionCase, int64_t>> options;
2551   llvm::SmallDenseSet<LoopOptionCase> seenOptions;
2552   do {
2553     StringRef optionName;
2554     if (parser.parseKeyword(&optionName))
2555       return {};
2556 
2557     auto option = symbolizeLoopOptionCase(optionName);
2558     if (!option) {
2559       parser.emitError(parser.getNameLoc(), "unknown loop option: ")
2560           << optionName;
2561       return {};
2562     }
2563     if (!seenOptions.insert(*option).second) {
2564       parser.emitError(parser.getNameLoc(), "loop option present twice");
2565       return {};
2566     }
2567     if (failed(parser.parseEqual()))
2568       return {};
2569 
2570     int64_t value;
2571     switch (*option) {
2572     case LoopOptionCase::disable_licm:
2573     case LoopOptionCase::disable_unroll:
2574     case LoopOptionCase::disable_pipeline:
2575       if (succeeded(parser.parseOptionalKeyword("true")))
2576         value = 1;
2577       else if (succeeded(parser.parseOptionalKeyword("false")))
2578         value = 0;
2579       else {
2580         parser.emitError(parser.getNameLoc(),
2581                          "expected boolean value 'true' or 'false'");
2582         return {};
2583       }
2584       break;
2585     case LoopOptionCase::interleave_count:
2586     case LoopOptionCase::pipeline_initiation_interval:
2587       if (failed(parser.parseInteger(value))) {
2588         parser.emitError(parser.getNameLoc(), "expected integer value");
2589         return {};
2590       }
2591       break;
2592     }
2593     options.push_back(std::make_pair(*option, value));
2594   } while (succeeded(parser.parseOptionalComma()));
2595   if (failed(parser.parseGreater()))
2596     return {};
2597 
2598   llvm::sort(options, llvm::less_first());
2599   return get(parser.getBuilder().getContext(), options);
2600 }
2601 
2602 Attribute LLVMDialect::parseAttribute(DialectAsmParser &parser,
2603                                       Type type) const {
2604   if (type) {
2605     parser.emitError(parser.getNameLoc(), "unexpected type");
2606     return {};
2607   }
2608   StringRef attrKind;
2609   if (parser.parseKeyword(&attrKind))
2610     return {};
2611   {
2612     Attribute attr;
2613     auto parseResult =
2614         generatedAttributeParser(getContext(), parser, attrKind, type, attr);
2615     if (parseResult.hasValue())
2616       return attr;
2617   }
2618   parser.emitError(parser.getNameLoc(), "unknown attribute type: ") << attrKind;
2619   return {};
2620 }
2621 
2622 void LLVMDialect::printAttribute(Attribute attr, DialectAsmPrinter &os) const {
2623   if (succeeded(generatedAttributePrinter(attr, os)))
2624     return;
2625   llvm_unreachable("Unknown attribute type");
2626 }
2627