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