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