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