1 //===- ConvertFromLLVMIR.cpp - MLIR to LLVM IR conversion -----------------===//
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 implements a translation between LLVM IR and the MLIR LLVM dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Target/LLVMIR/Import.h"
14 
15 #include "mlir/Dialect/DLTI/DLTI.h"
16 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
17 #include "mlir/IR/Builders.h"
18 #include "mlir/IR/BuiltinOps.h"
19 #include "mlir/IR/BuiltinTypes.h"
20 #include "mlir/IR/MLIRContext.h"
21 #include "mlir/Interfaces/DataLayoutInterfaces.h"
22 #include "mlir/Target/LLVMIR/TypeFromLLVM.h"
23 #include "mlir/Tools/mlir-translate/Translation.h"
24 
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/ADT/TypeSwitch.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/Support/Error.h"
37 #include "llvm/Support/SourceMgr.h"
38 
39 using namespace mlir;
40 using namespace mlir::LLVM;
41 
42 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc"
43 
44 // Utility to print an LLVM value as a string for passing to emitError().
45 // FIXME: Diagnostic should be able to natively handle types that have
46 // operator << (raw_ostream&) defined.
47 static std::string diag(llvm::Value &v) {
48   std::string s;
49   llvm::raw_string_ostream os(s);
50   os << v;
51   return os.str();
52 }
53 
54 /// Creates an attribute containing ABI and preferred alignment numbers parsed
55 /// a string. The string may be either "abi:preferred" or just "abi". In the
56 /// latter case, the prefrred alignment is considered equal to ABI alignment.
57 static DenseIntElementsAttr parseDataLayoutAlignment(MLIRContext &ctx,
58                                                      StringRef spec) {
59   auto i32 = IntegerType::get(&ctx, 32);
60 
61   StringRef abiString, preferredString;
62   std::tie(abiString, preferredString) = spec.split(':');
63   int abi, preferred;
64   if (abiString.getAsInteger(/*Radix=*/10, abi))
65     return nullptr;
66 
67   if (preferredString.empty())
68     preferred = abi;
69   else if (preferredString.getAsInteger(/*Radix=*/10, preferred))
70     return nullptr;
71 
72   return DenseIntElementsAttr::get(VectorType::get({2}, i32), {abi, preferred});
73 }
74 
75 /// Returns a supported MLIR floating point type of the given bit width or null
76 /// if the bit width is not supported.
77 static FloatType getDLFloatType(MLIRContext &ctx, int32_t bitwidth) {
78   switch (bitwidth) {
79   case 16:
80     return FloatType::getF16(&ctx);
81   case 32:
82     return FloatType::getF32(&ctx);
83   case 64:
84     return FloatType::getF64(&ctx);
85   case 80:
86     return FloatType::getF80(&ctx);
87   case 128:
88     return FloatType::getF128(&ctx);
89   default:
90     return nullptr;
91   }
92 }
93 
94 DataLayoutSpecInterface
95 mlir::translateDataLayout(const llvm::DataLayout &dataLayout,
96                           MLIRContext *context) {
97   assert(context && "expected MLIR context");
98   std::string layoutstr = dataLayout.getStringRepresentation();
99 
100   // Remaining unhandled default layout defaults
101   // e (little endian if not set)
102   // p[n]:64:64:64 (non zero address spaces have 64-bit properties)
103   std::string append =
104       "p:64:64:64-S0-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f16:16:16-f64:"
105       "64:64-f128:128:128-v64:64:64-v128:128:128-a:0:64";
106   if (layoutstr.empty())
107     layoutstr = append;
108   else
109     layoutstr = layoutstr + "-" + append;
110 
111   StringRef layout(layoutstr);
112 
113   SmallVector<DataLayoutEntryInterface> entries;
114   StringSet<> seen;
115   while (!layout.empty()) {
116     // Split at '-'.
117     std::pair<StringRef, StringRef> split = layout.split('-');
118     StringRef current;
119     std::tie(current, layout) = split;
120 
121     // Split at ':'.
122     StringRef kind, spec;
123     std::tie(kind, spec) = current.split(':');
124     if (seen.contains(kind))
125       continue;
126     seen.insert(kind);
127 
128     char symbol = kind.front();
129     StringRef parameter = kind.substr(1);
130 
131     if (symbol == 'i' || symbol == 'f') {
132       unsigned bitwidth;
133       if (parameter.getAsInteger(/*Radix=*/10, bitwidth))
134         return nullptr;
135       DenseIntElementsAttr params = parseDataLayoutAlignment(*context, spec);
136       if (!params)
137         return nullptr;
138       auto entry = DataLayoutEntryAttr::get(
139           symbol == 'i' ? static_cast<Type>(IntegerType::get(context, bitwidth))
140                         : getDLFloatType(*context, bitwidth),
141           params);
142       entries.emplace_back(entry);
143     } else if (symbol == 'e' || symbol == 'E') {
144       auto value = StringAttr::get(
145           context, symbol == 'e' ? DLTIDialect::kDataLayoutEndiannessLittle
146                                  : DLTIDialect::kDataLayoutEndiannessBig);
147       auto entry = DataLayoutEntryAttr::get(
148           StringAttr::get(context, DLTIDialect::kDataLayoutEndiannessKey),
149           value);
150       entries.emplace_back(entry);
151     }
152   }
153 
154   return DataLayoutSpecAttr::get(context, entries);
155 }
156 
157 // Handles importing globals and functions from an LLVM module.
158 namespace {
159 class Importer {
160 public:
161   Importer(MLIRContext *context, ModuleOp module)
162       : b(context), context(context), module(module),
163         unknownLoc(FileLineColLoc::get(context, "imported-bitcode", 0, 0)),
164         typeTranslator(*context) {
165     b.setInsertionPointToStart(module.getBody());
166   }
167 
168   /// Imports `f` into the current module.
169   LogicalResult processFunction(llvm::Function *f);
170 
171   /// Imports GV as a GlobalOp, creating it if it doesn't exist.
172   GlobalOp processGlobal(llvm::GlobalVariable *gv);
173 
174 private:
175   /// Returns personality of `f` as a FlatSymbolRefAttr.
176   FlatSymbolRefAttr getPersonalityAsAttr(llvm::Function *f);
177   /// Imports `bb` into `block`, which must be initially empty.
178   LogicalResult processBasicBlock(llvm::BasicBlock *bb, Block *block);
179   /// Imports `inst` and populates instMap[inst] with the imported Value.
180   LogicalResult processInstruction(llvm::Instruction *inst);
181   /// Creates an LLVM-compatible MLIR type for `type`.
182   Type processType(llvm::Type *type);
183   /// `value` is an SSA-use. Return the remapped version of `value` or a
184   /// placeholder that will be remapped later if this is an instruction that
185   /// has not yet been visited.
186   Value processValue(llvm::Value *value);
187   /// Create the most accurate Location possible using a llvm::DebugLoc and
188   /// possibly an llvm::Instruction to narrow the Location if debug information
189   /// is unavailable.
190   Location processDebugLoc(const llvm::DebugLoc &loc,
191                            llvm::Instruction *inst = nullptr);
192   /// `br` branches to `target`. Append the block arguments to attach to the
193   /// generated branch op to `blockArguments`. These should be in the same order
194   /// as the PHIs in `target`.
195   LogicalResult processBranchArgs(llvm::Instruction *br,
196                                   llvm::BasicBlock *target,
197                                   SmallVectorImpl<Value> &blockArguments);
198   /// Returns the builtin type equivalent to be used in attributes for the given
199   /// LLVM IR dialect type.
200   Type getStdTypeForAttr(Type type);
201   /// Return `value` as an attribute to attach to a GlobalOp.
202   Attribute getConstantAsAttr(llvm::Constant *value);
203   /// Return `c` as an MLIR Value. This could either be a ConstantOp, or
204   /// an expanded sequence of ops in the current function's entry block (for
205   /// ConstantExprs or ConstantGEPs).
206   Value processConstant(llvm::Constant *c);
207 
208   /// The current builder, pointing at where the next Instruction should be
209   /// generated.
210   OpBuilder b;
211   /// The current context.
212   MLIRContext *context;
213   /// The current module being created.
214   ModuleOp module;
215   /// The entry block of the current function being processed.
216   Block *currentEntryBlock = nullptr;
217 
218   /// Globals are inserted before the first function, if any.
219   Block::iterator getGlobalInsertPt() {
220     auto it = module.getBody()->begin();
221     auto endIt = module.getBody()->end();
222     while (it != endIt && !isa<LLVMFuncOp>(it))
223       ++it;
224     return it;
225   }
226 
227   /// Functions are always inserted before the module terminator.
228   Block::iterator getFuncInsertPt() {
229     return std::prev(module.getBody()->end());
230   }
231 
232   /// Remapped blocks, for the current function.
233   DenseMap<llvm::BasicBlock *, Block *> blocks;
234   /// Remapped values. These are function-local.
235   DenseMap<llvm::Value *, Value> instMap;
236   /// Instructions that had not been defined when first encountered as a use.
237   /// Maps to the dummy Operation that was created in processValue().
238   DenseMap<llvm::Value *, Operation *> unknownInstMap;
239   /// Uniquing map of GlobalVariables.
240   DenseMap<llvm::GlobalVariable *, GlobalOp> globals;
241   /// Cached FileLineColLoc::get("imported-bitcode", 0, 0).
242   Location unknownLoc;
243   /// The stateful type translator (contains named structs).
244   LLVM::TypeFromLLVMIRTranslator typeTranslator;
245 };
246 } // namespace
247 
248 Location Importer::processDebugLoc(const llvm::DebugLoc &loc,
249                                    llvm::Instruction *inst) {
250   if (!loc && inst) {
251     std::string s;
252     llvm::raw_string_ostream os(s);
253     os << "llvm-imported-inst-%";
254     inst->printAsOperand(os, /*PrintType=*/false);
255     return FileLineColLoc::get(context, os.str(), 0, 0);
256   }
257   if (!loc) {
258     return unknownLoc;
259   }
260   // FIXME: Obtain the filename from DILocationInfo.
261   return FileLineColLoc::get(context, "imported-bitcode", loc.getLine(),
262                              loc.getCol());
263 }
264 
265 Type Importer::processType(llvm::Type *type) {
266   if (Type result = typeTranslator.translateType(type))
267     return result;
268 
269   // FIXME: Diagnostic should be able to natively handle types that have
270   // operator<<(raw_ostream&) defined.
271   std::string s;
272   llvm::raw_string_ostream os(s);
273   os << *type;
274   emitError(unknownLoc) << "unhandled type: " << os.str();
275   return nullptr;
276 }
277 
278 // We only need integers, floats, doubles, and vectors and tensors thereof for
279 // attributes. Scalar and vector types are converted to the standard
280 // equivalents. Array types are converted to ranked tensors; nested array types
281 // are converted to multi-dimensional tensors or vectors, depending on the
282 // innermost type being a scalar or a vector.
283 Type Importer::getStdTypeForAttr(Type type) {
284   if (!type)
285     return nullptr;
286 
287   if (type.isa<IntegerType, FloatType>())
288     return type;
289 
290   // LLVM vectors can only contain scalars.
291   if (LLVM::isCompatibleVectorType(type)) {
292     auto numElements = LLVM::getVectorNumElements(type);
293     if (numElements.isScalable()) {
294       emitError(unknownLoc) << "scalable vectors not supported";
295       return nullptr;
296     }
297     Type elementType = getStdTypeForAttr(LLVM::getVectorElementType(type));
298     if (!elementType)
299       return nullptr;
300     return VectorType::get(numElements.getKnownMinValue(), elementType);
301   }
302 
303   // LLVM arrays can contain other arrays or vectors.
304   if (auto arrayType = type.dyn_cast<LLVMArrayType>()) {
305     // Recover the nested array shape.
306     SmallVector<int64_t, 4> shape;
307     shape.push_back(arrayType.getNumElements());
308     while (arrayType.getElementType().isa<LLVMArrayType>()) {
309       arrayType = arrayType.getElementType().cast<LLVMArrayType>();
310       shape.push_back(arrayType.getNumElements());
311     }
312 
313     // If the innermost type is a vector, use the multi-dimensional vector as
314     // attribute type.
315     if (LLVM::isCompatibleVectorType(arrayType.getElementType())) {
316       auto numElements = LLVM::getVectorNumElements(arrayType.getElementType());
317       if (numElements.isScalable()) {
318         emitError(unknownLoc) << "scalable vectors not supported";
319         return nullptr;
320       }
321       shape.push_back(numElements.getKnownMinValue());
322 
323       Type elementType = getStdTypeForAttr(
324           LLVM::getVectorElementType(arrayType.getElementType()));
325       if (!elementType)
326         return nullptr;
327       return VectorType::get(shape, elementType);
328     }
329 
330     // Otherwise use a tensor.
331     Type elementType = getStdTypeForAttr(arrayType.getElementType());
332     if (!elementType)
333       return nullptr;
334     return RankedTensorType::get(shape, elementType);
335   }
336 
337   return nullptr;
338 }
339 
340 // Get the given constant as an attribute. Not all constants can be represented
341 // as attributes.
342 Attribute Importer::getConstantAsAttr(llvm::Constant *value) {
343   if (auto *ci = dyn_cast<llvm::ConstantInt>(value))
344     return b.getIntegerAttr(
345         IntegerType::get(context, ci->getType()->getBitWidth()),
346         ci->getValue());
347   if (auto *c = dyn_cast<llvm::ConstantDataArray>(value))
348     if (c->isString())
349       return b.getStringAttr(c->getAsString());
350   if (auto *c = dyn_cast<llvm::ConstantFP>(value)) {
351     auto *type = c->getType();
352     FloatType floatTy;
353     if (type->isBFloatTy())
354       floatTy = FloatType::getBF16(context);
355     else
356       floatTy = getDLFloatType(*context, type->getScalarSizeInBits());
357     assert(floatTy && "unsupported floating point type");
358     return b.getFloatAttr(floatTy, c->getValueAPF());
359   }
360   if (auto *f = dyn_cast<llvm::Function>(value))
361     return SymbolRefAttr::get(b.getContext(), f->getName());
362 
363   // Convert constant data to a dense elements attribute.
364   if (auto *cd = dyn_cast<llvm::ConstantDataSequential>(value)) {
365     Type type = processType(cd->getElementType());
366     if (!type)
367       return nullptr;
368 
369     auto attrType = getStdTypeForAttr(processType(cd->getType()))
370                         .dyn_cast_or_null<ShapedType>();
371     if (!attrType)
372       return nullptr;
373 
374     if (type.isa<IntegerType>()) {
375       SmallVector<APInt, 8> values;
376       values.reserve(cd->getNumElements());
377       for (unsigned i = 0, e = cd->getNumElements(); i < e; ++i)
378         values.push_back(cd->getElementAsAPInt(i));
379       return DenseElementsAttr::get(attrType, values);
380     }
381 
382     if (type.isa<Float32Type, Float64Type>()) {
383       SmallVector<APFloat, 8> values;
384       values.reserve(cd->getNumElements());
385       for (unsigned i = 0, e = cd->getNumElements(); i < e; ++i)
386         values.push_back(cd->getElementAsAPFloat(i));
387       return DenseElementsAttr::get(attrType, values);
388     }
389 
390     return nullptr;
391   }
392 
393   // Unpack constant aggregates to create dense elements attribute whenever
394   // possible. Return nullptr (failure) otherwise.
395   if (isa<llvm::ConstantAggregate>(value)) {
396     auto outerType = getStdTypeForAttr(processType(value->getType()))
397                          .dyn_cast_or_null<ShapedType>();
398     if (!outerType)
399       return nullptr;
400 
401     SmallVector<Attribute, 8> values;
402     SmallVector<int64_t, 8> shape;
403 
404     for (unsigned i = 0, e = value->getNumOperands(); i < e; ++i) {
405       auto nested = getConstantAsAttr(value->getAggregateElement(i))
406                         .dyn_cast_or_null<DenseElementsAttr>();
407       if (!nested)
408         return nullptr;
409 
410       values.append(nested.value_begin<Attribute>(),
411                     nested.value_end<Attribute>());
412     }
413 
414     return DenseElementsAttr::get(outerType, values);
415   }
416 
417   return nullptr;
418 }
419 
420 GlobalOp Importer::processGlobal(llvm::GlobalVariable *gv) {
421   auto it = globals.find(gv);
422   if (it != globals.end())
423     return it->second;
424 
425   OpBuilder b(module.getBody(), getGlobalInsertPt());
426   Attribute valueAttr;
427   if (gv->hasInitializer())
428     valueAttr = getConstantAsAttr(gv->getInitializer());
429   Type type = processType(gv->getValueType());
430   if (!type)
431     return nullptr;
432 
433   uint64_t alignment = 0;
434   llvm::MaybeAlign maybeAlign = gv->getAlign();
435   if (maybeAlign.hasValue()) {
436     llvm::Align align = maybeAlign.getValue();
437     alignment = align.value();
438   }
439 
440   GlobalOp op = b.create<GlobalOp>(
441       UnknownLoc::get(context), type, gv->isConstant(),
442       convertLinkageFromLLVM(gv->getLinkage()), gv->getName(), valueAttr,
443       alignment, /*addr_space=*/gv->getAddressSpace(),
444       /*dso_local=*/gv->isDSOLocal(), /*thread_local=*/gv->isThreadLocal());
445 
446   if (gv->hasInitializer() && !valueAttr) {
447     Region &r = op.getInitializerRegion();
448     currentEntryBlock = b.createBlock(&r);
449     b.setInsertionPoint(currentEntryBlock, currentEntryBlock->begin());
450     Value v = processConstant(gv->getInitializer());
451     if (!v)
452       return nullptr;
453     b.create<ReturnOp>(op.getLoc(), ArrayRef<Value>({v}));
454   }
455   if (gv->hasAtLeastLocalUnnamedAddr())
456     op.setUnnamedAddrAttr(UnnamedAddrAttr::get(
457         context, convertUnnamedAddrFromLLVM(gv->getUnnamedAddr())));
458   if (gv->hasSection())
459     op.setSectionAttr(b.getStringAttr(gv->getSection()));
460 
461   return globals[gv] = op;
462 }
463 
464 Value Importer::processConstant(llvm::Constant *c) {
465   OpBuilder bEntry(currentEntryBlock, currentEntryBlock->begin());
466   if (Attribute attr = getConstantAsAttr(c)) {
467     // These constants can be represented as attributes.
468     OpBuilder b(currentEntryBlock, currentEntryBlock->begin());
469     Type type = processType(c->getType());
470     if (!type)
471       return nullptr;
472     if (auto symbolRef = attr.dyn_cast<FlatSymbolRefAttr>())
473       return bEntry.create<AddressOfOp>(unknownLoc, type, symbolRef.getValue());
474     return bEntry.create<ConstantOp>(unknownLoc, type, attr);
475   }
476   if (auto *cn = dyn_cast<llvm::ConstantPointerNull>(c)) {
477     Type type = processType(cn->getType());
478     if (!type)
479       return nullptr;
480     return bEntry.create<NullOp>(unknownLoc, type);
481   }
482   if (auto *gv = dyn_cast<llvm::GlobalVariable>(c))
483     return bEntry.create<AddressOfOp>(UnknownLoc::get(context),
484                                       processGlobal(gv));
485 
486   if (auto *ce = dyn_cast<llvm::ConstantExpr>(c)) {
487     llvm::Instruction *i = ce->getAsInstruction();
488     OpBuilder::InsertionGuard guard(b);
489     b.setInsertionPoint(currentEntryBlock, currentEntryBlock->begin());
490     if (failed(processInstruction(i)))
491       return nullptr;
492     assert(instMap.count(i));
493 
494     // If we don't remove entry of `i` here, it's totally possible that the
495     // next time llvm::ConstantExpr::getAsInstruction is called again, which
496     // always allocates a new Instruction, memory address of the newly
497     // created Instruction might be the same as `i`. Making processInstruction
498     // falsely believe that the new Instruction has been processed before
499     // and raised an assertion error.
500     Value value = instMap[i];
501     instMap.erase(i);
502     // Remove this zombie LLVM instruction now, leaving us only with the MLIR
503     // op.
504     i->deleteValue();
505     return value;
506   }
507   if (auto *ue = dyn_cast<llvm::UndefValue>(c)) {
508     Type type = processType(ue->getType());
509     if (!type)
510       return nullptr;
511     return bEntry.create<UndefOp>(UnknownLoc::get(context), type);
512   }
513 
514   if (isa<llvm::ConstantAggregate>(c) || isa<llvm::ConstantAggregateZero>(c)) {
515     unsigned numElements = c->getNumOperands();
516     std::function<llvm::Constant *(unsigned)> getElement =
517         [&](unsigned index) -> llvm::Constant * {
518       return c->getAggregateElement(index);
519     };
520     // llvm::ConstantAggregateZero doesn't take any operand
521     // so its getNumOperands is always zero.
522     if (auto *caz = dyn_cast<llvm::ConstantAggregateZero>(c)) {
523       numElements = caz->getElementCount().getFixedValue();
524       // We want to capture the pointer rather than reference
525       // to the pointer since the latter will become dangling upon
526       // exiting the scope.
527       getElement = [=](unsigned index) -> llvm::Constant * {
528         return caz->getElementValue(index);
529       };
530     }
531 
532     // Generate a llvm.undef as the root value first.
533     Type rootType = processType(c->getType());
534     if (!rootType)
535       return nullptr;
536     Value root = bEntry.create<UndefOp>(unknownLoc, rootType);
537     for (unsigned i = 0; i < numElements; ++i) {
538       llvm::Constant *element = getElement(i);
539       Value elementValue = processConstant(element);
540       if (!elementValue)
541         return nullptr;
542       ArrayAttr indexAttr = bEntry.getI32ArrayAttr({static_cast<int32_t>(i)});
543       root = bEntry.create<InsertValueOp>(UnknownLoc::get(context), rootType,
544                                           root, elementValue, indexAttr);
545     }
546     return root;
547   }
548 
549   emitError(unknownLoc) << "unhandled constant: " << diag(*c);
550   return nullptr;
551 }
552 
553 Value Importer::processValue(llvm::Value *value) {
554   auto it = instMap.find(value);
555   if (it != instMap.end())
556     return it->second;
557 
558   // We don't expect to see instructions in dominator order. If we haven't seen
559   // this instruction yet, create an unknown op and remap it later.
560   if (isa<llvm::Instruction>(value)) {
561     Type type = processType(value->getType());
562     if (!type)
563       return nullptr;
564     unknownInstMap[value] =
565         b.create(UnknownLoc::get(context), b.getStringAttr("llvm.unknown"),
566                  /*operands=*/{}, type);
567     return unknownInstMap[value]->getResult(0);
568   }
569 
570   if (auto *c = dyn_cast<llvm::Constant>(value))
571     return processConstant(c);
572 
573   emitError(unknownLoc) << "unhandled value: " << diag(*value);
574   return nullptr;
575 }
576 
577 /// Return the MLIR OperationName for the given LLVM opcode.
578 static StringRef lookupOperationNameFromOpcode(unsigned opcode) {
579 // Maps from LLVM opcode to MLIR OperationName. This is deliberately ordered
580 // as in llvm/IR/Instructions.def to aid comprehension and spot missing
581 // instructions.
582 #define INST(llvm_n, mlir_n)                                                   \
583   { llvm::Instruction::llvm_n, LLVM::mlir_n##Op::getOperationName() }
584   static const DenseMap<unsigned, StringRef> opcMap = {
585       // clang-format off
586       INST(Ret, Return),
587       // Br is handled specially.
588       // Switch is handled specially.
589       // FIXME: indirectbr
590       // Invoke is handled specially.
591       INST(Resume, Resume),
592       INST(Unreachable, Unreachable),
593       // FIXME: cleanupret
594       // FIXME: catchret
595       // FIXME: catchswitch
596       // FIXME: callbr
597       INST(FNeg, FNeg),
598       INST(Add, Add),
599       INST(FAdd, FAdd),
600       INST(Sub, Sub),
601       INST(FSub, FSub),
602       INST(Mul, Mul),
603       INST(FMul, FMul),
604       INST(UDiv, UDiv),
605       INST(SDiv, SDiv),
606       INST(FDiv, FDiv),
607       INST(URem, URem),
608       INST(SRem, SRem),
609       INST(FRem, FRem),
610       INST(Shl, Shl),
611       INST(LShr, LShr),
612       INST(AShr, AShr),
613       INST(And, And),
614       INST(Or, Or),
615       INST(Xor, XOr),
616       INST(ExtractElement, ExtractElement),
617       INST(InsertElement, InsertElement),
618       // ShuffleVector is handled specially.
619       // ExtractValue is handled specially.
620       // InsertValue is handled specially.
621       INST(Alloca, Alloca),
622       INST(Load, Load),
623       INST(Store, Store),
624       INST(Fence, Fence),
625       // FIXME: atomiccmpxchg
626       // FIXME: atomicrmw
627       // Getelementptr is handled specially.
628       INST(Trunc, Trunc),
629       INST(ZExt, ZExt),
630       INST(SExt, SExt),
631       INST(FPToUI, FPToUI),
632       INST(FPToSI, FPToSI),
633       INST(UIToFP, UIToFP),
634       INST(SIToFP, SIToFP),
635       INST(FPTrunc, FPTrunc),
636       INST(FPExt, FPExt),
637       INST(PtrToInt, PtrToInt),
638       INST(IntToPtr, IntToPtr),
639       INST(BitCast, Bitcast),
640       INST(AddrSpaceCast, AddrSpaceCast),
641       // ICmp is handled specially.
642       // FCmp is handled specially.
643       // PHI is handled specially.
644       INST(Select, Select),
645       INST(Freeze, Freeze),
646       INST(Call, Call),
647       // FIXME: vaarg
648       // FIXME: landingpad
649       // FIXME: catchpad
650       // FIXME: cleanuppad
651       // clang-format on
652   };
653 #undef INST
654 
655   return opcMap.lookup(opcode);
656 }
657 
658 /// Return the MLIR OperationName for the given LLVM intrinsic ID.
659 static StringRef lookupOperationNameFromIntrinsicID(unsigned id) {
660   // Maps from LLVM intrinsic ID to MLIR OperationName.
661   static const DenseMap<unsigned, StringRef> intrMap = {
662 #include "mlir/Dialect/LLVMIR/LLVMIntrinsicToLLVMIROpPairs.inc"
663   };
664   return intrMap.lookup(id);
665 }
666 
667 static ICmpPredicate getICmpPredicate(llvm::CmpInst::Predicate p) {
668   switch (p) {
669   default:
670     llvm_unreachable("incorrect comparison predicate");
671   case llvm::CmpInst::Predicate::ICMP_EQ:
672     return LLVM::ICmpPredicate::eq;
673   case llvm::CmpInst::Predicate::ICMP_NE:
674     return LLVM::ICmpPredicate::ne;
675   case llvm::CmpInst::Predicate::ICMP_SLT:
676     return LLVM::ICmpPredicate::slt;
677   case llvm::CmpInst::Predicate::ICMP_SLE:
678     return LLVM::ICmpPredicate::sle;
679   case llvm::CmpInst::Predicate::ICMP_SGT:
680     return LLVM::ICmpPredicate::sgt;
681   case llvm::CmpInst::Predicate::ICMP_SGE:
682     return LLVM::ICmpPredicate::sge;
683   case llvm::CmpInst::Predicate::ICMP_ULT:
684     return LLVM::ICmpPredicate::ult;
685   case llvm::CmpInst::Predicate::ICMP_ULE:
686     return LLVM::ICmpPredicate::ule;
687   case llvm::CmpInst::Predicate::ICMP_UGT:
688     return LLVM::ICmpPredicate::ugt;
689   case llvm::CmpInst::Predicate::ICMP_UGE:
690     return LLVM::ICmpPredicate::uge;
691   }
692   llvm_unreachable("incorrect integer comparison predicate");
693 }
694 
695 static FCmpPredicate getFCmpPredicate(llvm::CmpInst::Predicate p) {
696   switch (p) {
697   default:
698     llvm_unreachable("incorrect comparison predicate");
699   case llvm::CmpInst::Predicate::FCMP_FALSE:
700     return LLVM::FCmpPredicate::_false;
701   case llvm::CmpInst::Predicate::FCMP_TRUE:
702     return LLVM::FCmpPredicate::_true;
703   case llvm::CmpInst::Predicate::FCMP_OEQ:
704     return LLVM::FCmpPredicate::oeq;
705   case llvm::CmpInst::Predicate::FCMP_ONE:
706     return LLVM::FCmpPredicate::one;
707   case llvm::CmpInst::Predicate::FCMP_OLT:
708     return LLVM::FCmpPredicate::olt;
709   case llvm::CmpInst::Predicate::FCMP_OLE:
710     return LLVM::FCmpPredicate::ole;
711   case llvm::CmpInst::Predicate::FCMP_OGT:
712     return LLVM::FCmpPredicate::ogt;
713   case llvm::CmpInst::Predicate::FCMP_OGE:
714     return LLVM::FCmpPredicate::oge;
715   case llvm::CmpInst::Predicate::FCMP_ORD:
716     return LLVM::FCmpPredicate::ord;
717   case llvm::CmpInst::Predicate::FCMP_ULT:
718     return LLVM::FCmpPredicate::ult;
719   case llvm::CmpInst::Predicate::FCMP_ULE:
720     return LLVM::FCmpPredicate::ule;
721   case llvm::CmpInst::Predicate::FCMP_UGT:
722     return LLVM::FCmpPredicate::ugt;
723   case llvm::CmpInst::Predicate::FCMP_UGE:
724     return LLVM::FCmpPredicate::uge;
725   case llvm::CmpInst::Predicate::FCMP_UNO:
726     return LLVM::FCmpPredicate::uno;
727   case llvm::CmpInst::Predicate::FCMP_UEQ:
728     return LLVM::FCmpPredicate::ueq;
729   case llvm::CmpInst::Predicate::FCMP_UNE:
730     return LLVM::FCmpPredicate::une;
731   }
732   llvm_unreachable("incorrect floating point comparison predicate");
733 }
734 
735 static AtomicOrdering getLLVMAtomicOrdering(llvm::AtomicOrdering ordering) {
736   switch (ordering) {
737   case llvm::AtomicOrdering::NotAtomic:
738     return LLVM::AtomicOrdering::not_atomic;
739   case llvm::AtomicOrdering::Unordered:
740     return LLVM::AtomicOrdering::unordered;
741   case llvm::AtomicOrdering::Monotonic:
742     return LLVM::AtomicOrdering::monotonic;
743   case llvm::AtomicOrdering::Acquire:
744     return LLVM::AtomicOrdering::acquire;
745   case llvm::AtomicOrdering::Release:
746     return LLVM::AtomicOrdering::release;
747   case llvm::AtomicOrdering::AcquireRelease:
748     return LLVM::AtomicOrdering::acq_rel;
749   case llvm::AtomicOrdering::SequentiallyConsistent:
750     return LLVM::AtomicOrdering::seq_cst;
751   }
752   llvm_unreachable("incorrect atomic ordering");
753 }
754 
755 // `br` branches to `target`. Return the branch arguments to `br`, in the
756 // same order of the PHIs in `target`.
757 LogicalResult
758 Importer::processBranchArgs(llvm::Instruction *br, llvm::BasicBlock *target,
759                             SmallVectorImpl<Value> &blockArguments) {
760   for (auto inst = target->begin(); isa<llvm::PHINode>(inst); ++inst) {
761     auto *pn = cast<llvm::PHINode>(&*inst);
762     Value value = processValue(pn->getIncomingValueForBlock(br->getParent()));
763     if (!value)
764       return failure();
765     blockArguments.push_back(value);
766   }
767   return success();
768 }
769 
770 LogicalResult Importer::processInstruction(llvm::Instruction *inst) {
771   // FIXME: Support uses of SubtargetData. Currently inbounds GEPs, fast-math
772   // flags and call / operand attributes are not supported.
773   Location loc = processDebugLoc(inst->getDebugLoc(), inst);
774   assert(!instMap.count(inst) &&
775          "processInstruction must be called only once per instruction!");
776   switch (inst->getOpcode()) {
777   default:
778     return emitError(loc) << "unknown instruction: " << diag(*inst);
779   case llvm::Instruction::Add:
780   case llvm::Instruction::FAdd:
781   case llvm::Instruction::Sub:
782   case llvm::Instruction::FSub:
783   case llvm::Instruction::Mul:
784   case llvm::Instruction::FMul:
785   case llvm::Instruction::UDiv:
786   case llvm::Instruction::SDiv:
787   case llvm::Instruction::FDiv:
788   case llvm::Instruction::URem:
789   case llvm::Instruction::SRem:
790   case llvm::Instruction::FRem:
791   case llvm::Instruction::Shl:
792   case llvm::Instruction::LShr:
793   case llvm::Instruction::AShr:
794   case llvm::Instruction::And:
795   case llvm::Instruction::Or:
796   case llvm::Instruction::Xor:
797   case llvm::Instruction::Load:
798   case llvm::Instruction::Store:
799   case llvm::Instruction::Ret:
800   case llvm::Instruction::Resume:
801   case llvm::Instruction::Trunc:
802   case llvm::Instruction::ZExt:
803   case llvm::Instruction::SExt:
804   case llvm::Instruction::FPToUI:
805   case llvm::Instruction::FPToSI:
806   case llvm::Instruction::UIToFP:
807   case llvm::Instruction::SIToFP:
808   case llvm::Instruction::FPTrunc:
809   case llvm::Instruction::FPExt:
810   case llvm::Instruction::PtrToInt:
811   case llvm::Instruction::IntToPtr:
812   case llvm::Instruction::AddrSpaceCast:
813   case llvm::Instruction::Freeze:
814   case llvm::Instruction::BitCast:
815   case llvm::Instruction::ExtractElement:
816   case llvm::Instruction::InsertElement:
817   case llvm::Instruction::Select:
818   case llvm::Instruction::FNeg:
819   case llvm::Instruction::Unreachable: {
820     OperationState state(loc, lookupOperationNameFromOpcode(inst->getOpcode()));
821     SmallVector<Value, 4> ops;
822     ops.reserve(inst->getNumOperands());
823     for (auto *op : inst->operand_values()) {
824       Value value = processValue(op);
825       if (!value)
826         return failure();
827       ops.push_back(value);
828     }
829     state.addOperands(ops);
830     if (!inst->getType()->isVoidTy()) {
831       Type type = processType(inst->getType());
832       if (!type)
833         return failure();
834       state.addTypes(type);
835     }
836     Operation *op = b.create(state);
837     if (!inst->getType()->isVoidTy())
838       instMap[inst] = op->getResult(0);
839     return success();
840   }
841   case llvm::Instruction::Alloca: {
842     Value size = processValue(inst->getOperand(0));
843     if (!size)
844       return failure();
845 
846     auto *allocaInst = cast<llvm::AllocaInst>(inst);
847     instMap[inst] =
848         b.create<AllocaOp>(loc, processType(inst->getType()),
849                            processType(allocaInst->getAllocatedType()), size,
850                            allocaInst->getAlign().value());
851     return success();
852   }
853   case llvm::Instruction::ICmp: {
854     Value lhs = processValue(inst->getOperand(0));
855     Value rhs = processValue(inst->getOperand(1));
856     if (!lhs || !rhs)
857       return failure();
858     instMap[inst] = b.create<ICmpOp>(
859         loc, getICmpPredicate(cast<llvm::ICmpInst>(inst)->getPredicate()), lhs,
860         rhs);
861     return success();
862   }
863   case llvm::Instruction::FCmp: {
864     Value lhs = processValue(inst->getOperand(0));
865     Value rhs = processValue(inst->getOperand(1));
866     if (!lhs || !rhs)
867       return failure();
868     instMap[inst] = b.create<FCmpOp>(
869         loc, b.getI1Type(),
870         getFCmpPredicate(cast<llvm::FCmpInst>(inst)->getPredicate()), lhs, rhs);
871     return success();
872   }
873   case llvm::Instruction::Br: {
874     auto *brInst = cast<llvm::BranchInst>(inst);
875     OperationState state(loc,
876                          brInst->isConditional() ? "llvm.cond_br" : "llvm.br");
877     if (brInst->isConditional()) {
878       Value condition = processValue(brInst->getCondition());
879       if (!condition)
880         return failure();
881       state.addOperands(condition);
882     }
883 
884     std::array<int32_t, 3> operandSegmentSizes = {1, 0, 0};
885     for (int i : llvm::seq<int>(0, brInst->getNumSuccessors())) {
886       auto *succ = brInst->getSuccessor(i);
887       SmallVector<Value, 4> blockArguments;
888       if (failed(processBranchArgs(brInst, succ, blockArguments)))
889         return failure();
890       state.addSuccessors(blocks[succ]);
891       state.addOperands(blockArguments);
892       operandSegmentSizes[i + 1] = blockArguments.size();
893     }
894 
895     if (brInst->isConditional()) {
896       state.addAttribute(LLVM::CondBrOp::getOperandSegmentSizeAttr(),
897                          b.getI32VectorAttr(operandSegmentSizes));
898     }
899 
900     b.create(state);
901     return success();
902   }
903   case llvm::Instruction::Switch: {
904     auto *swInst = cast<llvm::SwitchInst>(inst);
905     // Process the condition value.
906     Value condition = processValue(swInst->getCondition());
907     if (!condition)
908       return failure();
909 
910     SmallVector<Value> defaultBlockArgs;
911     // Process the default case.
912     llvm::BasicBlock *defaultBB = swInst->getDefaultDest();
913     if (failed(processBranchArgs(swInst, defaultBB, defaultBlockArgs)))
914       return failure();
915 
916     // Process the cases.
917     unsigned numCases = swInst->getNumCases();
918     SmallVector<SmallVector<Value>> caseOperands(numCases);
919     SmallVector<ValueRange> caseOperandRefs(numCases);
920     SmallVector<int32_t> caseValues(numCases);
921     SmallVector<Block *> caseBlocks(numCases);
922     for (const auto &en : llvm::enumerate(swInst->cases())) {
923       const llvm::SwitchInst::CaseHandle &caseHandle = en.value();
924       unsigned i = en.index();
925       llvm::BasicBlock *succBB = caseHandle.getCaseSuccessor();
926       if (failed(processBranchArgs(swInst, succBB, caseOperands[i])))
927         return failure();
928       caseOperandRefs[i] = caseOperands[i];
929       caseValues[i] = caseHandle.getCaseValue()->getSExtValue();
930       caseBlocks[i] = blocks[succBB];
931     }
932 
933     b.create<SwitchOp>(loc, condition, blocks[defaultBB], defaultBlockArgs,
934                        caseValues, caseBlocks, caseOperandRefs);
935     return success();
936   }
937   case llvm::Instruction::PHI: {
938     Type type = processType(inst->getType());
939     if (!type)
940       return failure();
941     instMap[inst] = b.getInsertionBlock()->addArgument(
942         type, processDebugLoc(inst->getDebugLoc(), inst));
943     return success();
944   }
945   case llvm::Instruction::Call: {
946     llvm::CallInst *ci = cast<llvm::CallInst>(inst);
947     SmallVector<Value, 4> ops;
948     ops.reserve(inst->getNumOperands());
949     for (auto &op : ci->args()) {
950       Value arg = processValue(op.get());
951       if (!arg)
952         return failure();
953       ops.push_back(arg);
954     }
955 
956     SmallVector<Type, 2> tys;
957     if (!ci->getType()->isVoidTy()) {
958       Type type = processType(inst->getType());
959       if (!type)
960         return failure();
961       tys.push_back(type);
962     }
963     Operation *op;
964     if (llvm::Function *callee = ci->getCalledFunction()) {
965       // For all intrinsics, try to generate to the corresponding op.
966       if (callee->isIntrinsic()) {
967         auto id = callee->getIntrinsicID();
968         StringRef opName = lookupOperationNameFromIntrinsicID(id);
969         if (!opName.empty()) {
970           OperationState state(loc, opName);
971           state.addOperands(ops);
972           state.addTypes(tys);
973           Operation *op = b.create(state);
974           if (!inst->getType()->isVoidTy())
975             instMap[inst] = op->getResult(0);
976           return success();
977         }
978       }
979       op = b.create<CallOp>(
980           loc, tys, SymbolRefAttr::get(b.getContext(), callee->getName()), ops);
981     } else {
982       Value calledValue = processValue(ci->getCalledOperand());
983       if (!calledValue)
984         return failure();
985       ops.insert(ops.begin(), calledValue);
986       op = b.create<CallOp>(loc, tys, ops);
987     }
988     if (!ci->getType()->isVoidTy())
989       instMap[inst] = op->getResult(0);
990     return success();
991   }
992   case llvm::Instruction::LandingPad: {
993     llvm::LandingPadInst *lpi = cast<llvm::LandingPadInst>(inst);
994     SmallVector<Value, 4> ops;
995 
996     for (unsigned i = 0, ie = lpi->getNumClauses(); i < ie; i++)
997       ops.push_back(processConstant(lpi->getClause(i)));
998 
999     Type ty = processType(lpi->getType());
1000     if (!ty)
1001       return failure();
1002 
1003     instMap[inst] = b.create<LandingpadOp>(loc, ty, lpi->isCleanup(), ops);
1004     return success();
1005   }
1006   case llvm::Instruction::Invoke: {
1007     llvm::InvokeInst *ii = cast<llvm::InvokeInst>(inst);
1008 
1009     SmallVector<Type, 2> tys;
1010     if (!ii->getType()->isVoidTy())
1011       tys.push_back(processType(inst->getType()));
1012 
1013     SmallVector<Value, 4> ops;
1014     ops.reserve(inst->getNumOperands() + 1);
1015     for (auto &op : ii->args())
1016       ops.push_back(processValue(op.get()));
1017 
1018     SmallVector<Value, 4> normalArgs, unwindArgs;
1019     (void)processBranchArgs(ii, ii->getNormalDest(), normalArgs);
1020     (void)processBranchArgs(ii, ii->getUnwindDest(), unwindArgs);
1021 
1022     Operation *op;
1023     if (llvm::Function *callee = ii->getCalledFunction()) {
1024       op = b.create<InvokeOp>(
1025           loc, tys, SymbolRefAttr::get(b.getContext(), callee->getName()), ops,
1026           blocks[ii->getNormalDest()], normalArgs, blocks[ii->getUnwindDest()],
1027           unwindArgs);
1028     } else {
1029       ops.insert(ops.begin(), processValue(ii->getCalledOperand()));
1030       op = b.create<InvokeOp>(loc, tys, ops, blocks[ii->getNormalDest()],
1031                               normalArgs, blocks[ii->getUnwindDest()],
1032                               unwindArgs);
1033     }
1034 
1035     if (!ii->getType()->isVoidTy())
1036       instMap[inst] = op->getResult(0);
1037     return success();
1038   }
1039   case llvm::Instruction::Fence: {
1040     StringRef syncscope;
1041     SmallVector<StringRef, 4> ssNs;
1042     llvm::LLVMContext &llvmContext = inst->getContext();
1043     llvm::FenceInst *fence = cast<llvm::FenceInst>(inst);
1044     llvmContext.getSyncScopeNames(ssNs);
1045     int fenceSyncScopeID = fence->getSyncScopeID();
1046     for (unsigned i = 0, e = ssNs.size(); i != e; i++) {
1047       if (fenceSyncScopeID == llvmContext.getOrInsertSyncScopeID(ssNs[i])) {
1048         syncscope = ssNs[i];
1049         break;
1050       }
1051     }
1052     b.create<FenceOp>(loc, getLLVMAtomicOrdering(fence->getOrdering()),
1053                       syncscope);
1054     return success();
1055   }
1056   case llvm::Instruction::GetElementPtr: {
1057     // FIXME: Support inbounds GEPs.
1058     llvm::GetElementPtrInst *gep = cast<llvm::GetElementPtrInst>(inst);
1059     Value basePtr = processValue(gep->getOperand(0));
1060     Type sourceElementType = processType(gep->getSourceElementType());
1061 
1062     SmallVector<Value> indices;
1063     for (llvm::Value *operand : llvm::drop_begin(gep->operand_values())) {
1064       indices.push_back(processValue(operand));
1065       if (!indices.back())
1066         return failure();
1067     }
1068     // Treat every indices as dynamic since GEPOp::build will refine those
1069     // indices into static attributes later. One small downside of this
1070     // approach is that many unused `llvm.mlir.constant` would be emitted
1071     // at first place.
1072     SmallVector<int32_t> structIndices(indices.size(),
1073                                        LLVM::GEPOp::kDynamicIndex);
1074 
1075     Type type = processType(inst->getType());
1076     if (!type)
1077       return failure();
1078     instMap[inst] = b.create<GEPOp>(loc, type, sourceElementType, basePtr,
1079                                     indices, structIndices);
1080     return success();
1081   }
1082   case llvm::Instruction::InsertValue: {
1083     auto *ivInst = cast<llvm::InsertValueInst>(inst);
1084     Value inserted = processValue(ivInst->getInsertedValueOperand());
1085     if (!inserted)
1086       return failure();
1087     Value aggOperand = processValue(ivInst->getAggregateOperand());
1088     if (!aggOperand)
1089       return failure();
1090 
1091     SmallVector<int32_t> idxValues;
1092     for (unsigned idx : ivInst->getIndices())
1093       idxValues.push_back(static_cast<int32_t>(idx));
1094     ArrayAttr indices = b.getI32ArrayAttr(idxValues);
1095 
1096     instMap[inst] = b.create<InsertValueOp>(loc, aggOperand, inserted, indices);
1097     return success();
1098   }
1099   case llvm::Instruction::ExtractValue: {
1100     auto *evInst = cast<llvm::ExtractValueInst>(inst);
1101     Value aggOperand = processValue(evInst->getAggregateOperand());
1102     if (!aggOperand)
1103       return failure();
1104 
1105     Type type = processType(inst->getType());
1106     if (!type)
1107       return failure();
1108 
1109     SmallVector<int32_t> idxValues;
1110     for (unsigned idx : evInst->getIndices())
1111       idxValues.push_back(static_cast<int32_t>(idx));
1112     ArrayAttr indices = b.getI32ArrayAttr(idxValues);
1113 
1114     instMap[inst] = b.create<ExtractValueOp>(loc, type, aggOperand, indices);
1115     return success();
1116   }
1117   case llvm::Instruction::ShuffleVector: {
1118     auto *svInst = cast<llvm::ShuffleVectorInst>(inst);
1119     Value vec1 = processValue(svInst->getOperand(0));
1120     if (!vec1)
1121       return failure();
1122     Value vec2 = processValue(svInst->getOperand(1));
1123     if (!vec2)
1124       return failure();
1125 
1126     ArrayAttr mask = b.getI32ArrayAttr(svInst->getShuffleMask());
1127 
1128     instMap[inst] = b.create<ShuffleVectorOp>(loc, vec1, vec2, mask);
1129     return success();
1130   }
1131   }
1132 }
1133 
1134 FlatSymbolRefAttr Importer::getPersonalityAsAttr(llvm::Function *f) {
1135   if (!f->hasPersonalityFn())
1136     return nullptr;
1137 
1138   llvm::Constant *pf = f->getPersonalityFn();
1139 
1140   // If it directly has a name, we can use it.
1141   if (pf->hasName())
1142     return SymbolRefAttr::get(b.getContext(), pf->getName());
1143 
1144   // If it doesn't have a name, currently, only function pointers that are
1145   // bitcast to i8* are parsed.
1146   if (auto *ce = dyn_cast<llvm::ConstantExpr>(pf)) {
1147     if (ce->getOpcode() == llvm::Instruction::BitCast &&
1148         ce->getType() == llvm::Type::getInt8PtrTy(f->getContext())) {
1149       if (auto *func = dyn_cast<llvm::Function>(ce->getOperand(0)))
1150         return SymbolRefAttr::get(b.getContext(), func->getName());
1151     }
1152   }
1153   return FlatSymbolRefAttr();
1154 }
1155 
1156 LogicalResult Importer::processFunction(llvm::Function *f) {
1157   blocks.clear();
1158   instMap.clear();
1159   unknownInstMap.clear();
1160 
1161   auto functionType =
1162       processType(f->getFunctionType()).dyn_cast<LLVMFunctionType>();
1163   if (!functionType)
1164     return failure();
1165 
1166   if (f->isIntrinsic()) {
1167     StringRef opName = lookupOperationNameFromIntrinsicID(f->getIntrinsicID());
1168     // Skip the intrinsic decleration if we could found a corresponding op.
1169     if (!opName.empty())
1170       return success();
1171   }
1172 
1173   bool dsoLocal = f->hasLocalLinkage();
1174   CConv cconv = convertCConvFromLLVM(f->getCallingConv());
1175 
1176   b.setInsertionPoint(module.getBody(), getFuncInsertPt());
1177   LLVMFuncOp fop = b.create<LLVMFuncOp>(
1178       UnknownLoc::get(context), f->getName(), functionType,
1179       convertLinkageFromLLVM(f->getLinkage()), dsoLocal, cconv);
1180 
1181   if (FlatSymbolRefAttr personality = getPersonalityAsAttr(f))
1182     fop->setAttr(b.getStringAttr("personality"), personality);
1183   else if (f->hasPersonalityFn())
1184     emitWarning(UnknownLoc::get(context),
1185                 "could not deduce personality, skipping it");
1186 
1187   if (f->hasGC())
1188     fop.setGarbageCollectorAttr(b.getStringAttr(f->getGC()));
1189 
1190   if (f->isDeclaration())
1191     return success();
1192 
1193   // Eagerly create all blocks.
1194   SmallVector<Block *, 4> blockList;
1195   for (llvm::BasicBlock &bb : *f) {
1196     blockList.push_back(b.createBlock(&fop.getBody(), fop.getBody().end()));
1197     blocks[&bb] = blockList.back();
1198   }
1199   currentEntryBlock = blockList[0];
1200 
1201   // Add function arguments to the entry block.
1202   for (const auto &kv : llvm::enumerate(f->args())) {
1203     instMap[&kv.value()] = blockList[0]->addArgument(
1204         functionType.getParamType(kv.index()), fop.getLoc());
1205   }
1206 
1207   for (auto bbs : llvm::zip(*f, blockList)) {
1208     if (failed(processBasicBlock(&std::get<0>(bbs), std::get<1>(bbs))))
1209       return failure();
1210   }
1211 
1212   // Now that all instructions are guaranteed to have been visited, ensure
1213   // any unknown uses we encountered are remapped.
1214   for (auto &llvmAndUnknown : unknownInstMap) {
1215     assert(instMap.count(llvmAndUnknown.first));
1216     Value newValue = instMap[llvmAndUnknown.first];
1217     Value oldValue = llvmAndUnknown.second->getResult(0);
1218     oldValue.replaceAllUsesWith(newValue);
1219     llvmAndUnknown.second->erase();
1220   }
1221   return success();
1222 }
1223 
1224 LogicalResult Importer::processBasicBlock(llvm::BasicBlock *bb, Block *block) {
1225   b.setInsertionPointToStart(block);
1226   for (llvm::Instruction &inst : *bb) {
1227     if (failed(processInstruction(&inst)))
1228       return failure();
1229   }
1230   return success();
1231 }
1232 
1233 OwningOpRef<ModuleOp>
1234 mlir::translateLLVMIRToModule(std::unique_ptr<llvm::Module> llvmModule,
1235                               MLIRContext *context) {
1236   context->loadDialect<LLVMDialect>();
1237   context->loadDialect<DLTIDialect>();
1238   OwningOpRef<ModuleOp> module(ModuleOp::create(
1239       FileLineColLoc::get(context, "", /*line=*/0, /*column=*/0)));
1240 
1241   DataLayoutSpecInterface dlSpec =
1242       translateDataLayout(llvmModule->getDataLayout(), context);
1243   if (!dlSpec) {
1244     emitError(UnknownLoc::get(context), "can't translate data layout");
1245     return {};
1246   }
1247 
1248   module.get()->setAttr(DLTIDialect::kDataLayoutAttrName, dlSpec);
1249 
1250   Importer deserializer(context, module.get());
1251   for (llvm::GlobalVariable &gv : llvmModule->globals()) {
1252     if (!deserializer.processGlobal(&gv))
1253       return {};
1254   }
1255   for (llvm::Function &f : llvmModule->functions()) {
1256     if (failed(deserializer.processFunction(&f)))
1257       return {};
1258   }
1259 
1260   return module;
1261 }
1262 
1263 // Deserializes the LLVM bitcode stored in `input` into an MLIR module in the
1264 // LLVM dialect.
1265 OwningOpRef<ModuleOp> translateLLVMIRToModule(llvm::SourceMgr &sourceMgr,
1266                                               MLIRContext *context) {
1267   llvm::SMDiagnostic err;
1268   llvm::LLVMContext llvmContext;
1269   std::unique_ptr<llvm::Module> llvmModule = llvm::parseIR(
1270       *sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID()), err, llvmContext);
1271   if (!llvmModule) {
1272     std::string errStr;
1273     llvm::raw_string_ostream errStream(errStr);
1274     err.print(/*ProgName=*/"", errStream);
1275     emitError(UnknownLoc::get(context)) << errStream.str();
1276     return {};
1277   }
1278   return translateLLVMIRToModule(std::move(llvmModule), context);
1279 }
1280 
1281 namespace mlir {
1282 void registerFromLLVMIRTranslation() {
1283   TranslateToMLIRRegistration fromLLVM(
1284       "import-llvm", [](llvm::SourceMgr &sourceMgr, MLIRContext *context) {
1285         return ::translateLLVMIRToModule(sourceMgr, context);
1286       });
1287 }
1288 } // namespace mlir
1289