Debian Codegraph @

clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp

raw
1 //====- LowerToLLVM.cpp - Lowering from CIR to LLVMIR ---------------------===//
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 lowering of CIR operations to LLVMIR.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "LowerToLLVM.h"
14
15 #include <array>
16 #include <deque>
17 #include <optional>
18
19 #include "mlir/Conversion/LLVMCommon/TypeConverter.h"
20 #include "mlir/Dialect/DLTI/DLTI.h"
21 #include "mlir/Dialect/Func/IR/FuncOps.h"
22 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
23 #include "mlir/Dialect/LLVMIR/LLVMTypes.h"
24 #include "mlir/IR/BuiltinAttributes.h"
25 #include "mlir/IR/BuiltinDialect.h"
26 #include "mlir/IR/BuiltinOps.h"
27 #include "mlir/IR/Types.h"
28 #include "mlir/Pass/Pass.h"
29 #include "mlir/Pass/PassManager.h"
30 #include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h"
31 #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
32 #include "mlir/Target/LLVMIR/Export.h"
33 #include "mlir/Transforms/DialectConversion.h"
34 #include "clang/CIR/Dialect/IR/CIRAttrs.h"
35 #include "clang/CIR/Dialect/IR/CIRDialect.h"
36 #include "clang/CIR/Dialect/IR/CIRTypes.h"
37 #include "clang/CIR/Dialect/Passes.h"
38 #include "clang/CIR/LoweringHelpers.h"
39 #include "clang/CIR/MissingFeatures.h"
40 #include "clang/CIR/Passes.h"
41 #include "llvm/ADT/TypeSwitch.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/TimeProfiler.h"
45
46 using namespace cir;
47 using namespace llvm;
48
49 namespace cir {
50 namespace direct {
51
52 //===----------------------------------------------------------------------===//
53 // Helper Methods
54 //===----------------------------------------------------------------------===//
55
56 namespace {
57 /// If the given type is a vector type, return the vector's element type.
58 /// Otherwise return the given type unchanged.
59 mlir::Type elementTypeIfVector(mlir::Type type) {
60 return llvm::TypeSwitch<mlir::Type, mlir::Type>(type)
61 .Case<cir::VectorType, mlir::VectorType>(
62 [](auto p) { return p.getElementType(); })
63 .Default([](mlir::Type p) { return p; });
64 }
65 } // namespace
66
67 /// Given a type convertor and a data layout, convert the given type to a type
68 /// that is suitable for memory operations. For example, this can be used to
69 /// lower cir.bool accesses to i8.
70 static mlir::Type convertTypeForMemory(const mlir::TypeConverter &converter,
71 mlir::DataLayout const &dataLayout,
72 mlir::Type type) {
73 // TODO(cir): Handle other types similarly to clang's codegen
74 // convertTypeForMemory
75 if (isa<cir::BoolType>(type)) {
76 return mlir::IntegerType::get(type.getContext(),
77 dataLayout.getTypeSizeInBits(type));
78 }
79
80 return converter.convertType(type);
81 }
82
83 static mlir::Value createIntCast(mlir::OpBuilder &bld, mlir::Value src,
84 mlir::IntegerType dstTy,
85 bool isSigned = false) {
86 mlir::Type srcTy = src.getType();
87 assert(mlir::isa<mlir::IntegerType>(srcTy));
88
89 unsigned srcWidth = mlir::cast<mlir::IntegerType>(srcTy).getWidth();
90 unsigned dstWidth = mlir::cast<mlir::IntegerType>(dstTy).getWidth();
91 mlir::Location loc = src.getLoc();
92
93 if (dstWidth > srcWidth && isSigned)
94 return mlir::LLVM::SExtOp::create(bld, loc, dstTy, src);
95 if (dstWidth > srcWidth)
96 return mlir::LLVM::ZExtOp::create(bld, loc, dstTy, src);
97 if (dstWidth < srcWidth)
98 return mlir::LLVM::TruncOp::create(bld, loc, dstTy, src);
99 return mlir::LLVM::BitcastOp::create(bld, loc, dstTy, src);
100 }
101
102 static mlir::LLVM::Visibility
103 lowerCIRVisibilityToLLVMVisibility(cir::VisibilityKind visibilityKind) {
104 switch (visibilityKind) {
105 case cir::VisibilityKind::Default:
106 return ::mlir::LLVM::Visibility::Default;
107 case cir::VisibilityKind::Hidden:
108 return ::mlir::LLVM::Visibility::Hidden;
109 case cir::VisibilityKind::Protected:
110 return ::mlir::LLVM::Visibility::Protected;
111 }
112 }
113
114 /// Emits the value from memory as expected by its users. Should be called when
115 /// the memory represetnation of a CIR type is not equal to its scalar
116 /// representation.
117 static mlir::Value emitFromMemory(mlir::ConversionPatternRewriter &rewriter,
118 mlir::DataLayout const &dataLayout,
119 cir::LoadOp op, mlir::Value value) {
120
121 // TODO(cir): Handle other types similarly to clang's codegen EmitFromMemory
122 if (auto boolTy = mlir::dyn_cast<cir::BoolType>(op.getType())) {
123 // Create a cast value from specified size in datalayout to i1
124 assert(value.getType().isInteger(dataLayout.getTypeSizeInBits(boolTy)));
125 return createIntCast(rewriter, value, rewriter.getI1Type());
126 }
127
128 return value;
129 }
130
131 /// Emits a value to memory with the expected scalar type. Should be called when
132 /// the memory represetnation of a CIR type is not equal to its scalar
133 /// representation.
134 static mlir::Value emitToMemory(mlir::ConversionPatternRewriter &rewriter,
135 mlir::DataLayout const &dataLayout,
136 mlir::Type origType, mlir::Value value) {
137
138 // TODO(cir): Handle other types similarly to clang's codegen EmitToMemory
139 if (auto boolTy = mlir::dyn_cast<cir::BoolType>(origType)) {
140 // Create zext of value from i1 to i8
141 mlir::IntegerType memType =
142 rewriter.getIntegerType(dataLayout.getTypeSizeInBits(boolTy));
143 return createIntCast(rewriter, value, memType);
144 }
145
146 return value;
147 }
148
149 mlir::LLVM::Linkage convertLinkage(cir::GlobalLinkageKind linkage) {
150 using CIR = cir::GlobalLinkageKind;
151 using LLVM = mlir::LLVM::Linkage;
152
153 switch (linkage) {
154 case CIR::AvailableExternallyLinkage:
155 return LLVM::AvailableExternally;
156 case CIR::CommonLinkage:
157 return LLVM::Common;
158 case CIR::ExternalLinkage:
159 return LLVM::External;
160 case CIR::ExternalWeakLinkage:
161 return LLVM::ExternWeak;
162 case CIR::InternalLinkage:
163 return LLVM::Internal;
164 case CIR::LinkOnceAnyLinkage:
165 return LLVM::Linkonce;
166 case CIR::LinkOnceODRLinkage:
167 return LLVM::LinkonceODR;
168 case CIR::PrivateLinkage:
169 return LLVM::Private;
170 case CIR::WeakAnyLinkage:
171 return LLVM::Weak;
172 case CIR::WeakODRLinkage:
173 return LLVM::WeakODR;
174 };
175 llvm_unreachable("Unknown CIR linkage type");
176 }
177
178 mlir::LogicalResult CIRToLLVMCopyOpLowering::matchAndRewrite(
179 cir::CopyOp op, OpAdaptor adaptor,
180 mlir::ConversionPatternRewriter &rewriter) const {
181 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
182 const mlir::Value length = mlir::LLVM::ConstantOp::create(
183 rewriter, op.getLoc(), rewriter.getI32Type(), op.getLength(layout));
184 assert(!cir::MissingFeatures::aggValueSlotVolatile());
185 rewriter.replaceOpWithNewOp<mlir::LLVM::MemcpyOp>(
186 op, adaptor.getDst(), adaptor.getSrc(), length, op.getIsVolatile());
187 return mlir::success();
188 }
189
190 mlir::LogicalResult CIRToLLVMSqrtOpLowering::matchAndRewrite(
191 cir::SqrtOp op, OpAdaptor adaptor,
192 mlir::ConversionPatternRewriter &rewriter) const {
193 mlir::Type resTy = typeConverter->convertType(op.getType());
194 rewriter.replaceOpWithNewOp<mlir::LLVM::SqrtOp>(op, resTy, adaptor.getSrc());
195 return mlir::success();
196 }
197
198 mlir::LogicalResult CIRToLLVMCosOpLowering::matchAndRewrite(
199 cir::CosOp op, OpAdaptor adaptor,
200 mlir::ConversionPatternRewriter &rewriter) const {
201 mlir::Type resTy = typeConverter->convertType(op.getType());
202 rewriter.replaceOpWithNewOp<mlir::LLVM::CosOp>(op, resTy, adaptor.getSrc());
203 return mlir::success();
204 }
205
206 mlir::LogicalResult CIRToLLVMExpOpLowering::matchAndRewrite(
207 cir::ExpOp op, OpAdaptor adaptor,
208 mlir::ConversionPatternRewriter &rewriter) const {
209 mlir::Type resTy = typeConverter->convertType(op.getType());
210 rewriter.replaceOpWithNewOp<mlir::LLVM::ExpOp>(op, resTy, adaptor.getSrc());
211 return mlir::success();
212 }
213
214 mlir::LogicalResult CIRToLLVMExp2OpLowering::matchAndRewrite(
215 cir::Exp2Op op, OpAdaptor adaptor,
216 mlir::ConversionPatternRewriter &rewriter) const {
217 mlir::Type resTy = typeConverter->convertType(op.getType());
218 rewriter.replaceOpWithNewOp<mlir::LLVM::Exp2Op>(op, resTy, adaptor.getSrc());
219 return mlir::success();
220 }
221
222 mlir::LogicalResult CIRToLLVMFloorOpLowering::matchAndRewrite(
223 cir::FloorOp op, OpAdaptor adaptor,
224 mlir::ConversionPatternRewriter &rewriter) const {
225 mlir::Type resTy = typeConverter->convertType(op.getType());
226 rewriter.replaceOpWithNewOp<mlir::LLVM::FFloorOp>(op, resTy,
227 adaptor.getSrc());
228 return mlir::success();
229 }
230
231 static mlir::Value getLLVMIntCast(mlir::ConversionPatternRewriter &rewriter,
232 mlir::Value llvmSrc, mlir::Type llvmDstIntTy,
233 bool isUnsigned, uint64_t cirSrcWidth,
234 uint64_t cirDstIntWidth) {
235 if (cirSrcWidth == cirDstIntWidth)
236 return llvmSrc;
237
238 auto loc = llvmSrc.getLoc();
239 if (cirSrcWidth < cirDstIntWidth) {
240 if (isUnsigned)
241 return mlir::LLVM::ZExtOp::create(rewriter, loc, llvmDstIntTy, llvmSrc);
242 return mlir::LLVM::SExtOp::create(rewriter, loc, llvmDstIntTy, llvmSrc);
243 }
244
245 // Otherwise truncate
246 return mlir::LLVM::TruncOp::create(rewriter, loc, llvmDstIntTy, llvmSrc);
247 }
248
249 class CIRAttrToValue {
250 public:
251 CIRAttrToValue(mlir::Operation *parentOp,
252 mlir::ConversionPatternRewriter &rewriter,
253 const mlir::TypeConverter *converter,
254 cir::LowerModule *lowerMod)
255 : parentOp(parentOp), rewriter(rewriter), converter(converter),
256 lowerMod(lowerMod) {}
257
258 mlir::Value visit(mlir::Attribute attr) {
259 return llvm::TypeSwitch<mlir::Attribute, mlir::Value>(attr)
260 .Case<cir::IntAttr, cir::FPAttr, cir::ConstComplexAttr,
261 cir::ConstArrayAttr, cir::ConstRecordAttr, cir::ConstVectorAttr,
262 cir::ConstPtrAttr, cir::GlobalViewAttr, cir::TypeInfoAttr,
263 cir::UndefAttr, cir::VTableAttr, cir::ZeroAttr>(
264 [&](auto attrT) { return visitCirAttr(attrT); })
265 .Default([&](auto attrT) { return mlir::Value(); });
266 }
267
268 mlir::Value visitCirAttr(cir::IntAttr intAttr);
269 mlir::Value visitCirAttr(cir::FPAttr fltAttr);
270 mlir::Value visitCirAttr(cir::ConstComplexAttr complexAttr);
271 mlir::Value visitCirAttr(cir::ConstPtrAttr ptrAttr);
272 mlir::Value visitCirAttr(cir::ConstArrayAttr attr);
273 mlir::Value visitCirAttr(cir::ConstRecordAttr attr);
274 mlir::Value visitCirAttr(cir::ConstVectorAttr attr);
275 mlir::Value visitCirAttr(cir::GlobalViewAttr attr);
276 mlir::Value visitCirAttr(cir::TypeInfoAttr attr);
277 mlir::Value visitCirAttr(cir::UndefAttr attr);
278 mlir::Value visitCirAttr(cir::VTableAttr attr);
279 mlir::Value visitCirAttr(cir::ZeroAttr attr);
280
281 private:
282 mlir::Operation *parentOp;
283 mlir::ConversionPatternRewriter &rewriter;
284 const mlir::TypeConverter *converter;
285 [[maybe_unused]] cir::LowerModule *lowerMod;
286 };
287
288 /// Switches on the type of attribute and calls the appropriate conversion.
289 mlir::Value lowerCirAttrAsValue(mlir::Operation *parentOp,
290 const mlir::Attribute attr,
291 mlir::ConversionPatternRewriter &rewriter,
292 const mlir::TypeConverter *converter,
293 cir::LowerModule *lowerMod) {
294 CIRAttrToValue valueConverter(parentOp, rewriter, converter, lowerMod);
295 mlir::Value value = valueConverter.visit(attr);
296 if (!value)
297 llvm_unreachable("unhandled attribute type");
298 return value;
299 }
300
301 void convertSideEffectForCall(mlir::Operation *callOp, bool isNothrow,
302 cir::SideEffect sideEffect,
303 mlir::LLVM::MemoryEffectsAttr &memoryEffect,
304 bool &noUnwind, bool &willReturn) {
305 using mlir::LLVM::ModRefInfo;
306
307 switch (sideEffect) {
308 case cir::SideEffect::All:
309 memoryEffect = {};
310 noUnwind = isNothrow;
311 willReturn = false;
312 break;
313
314 case cir::SideEffect::Pure:
315 memoryEffect = mlir::LLVM::MemoryEffectsAttr::get(
316 callOp->getContext(), /*other=*/ModRefInfo::Ref,
317 /*argMem=*/ModRefInfo::Ref,
318 /*inaccessibleMem=*/ModRefInfo::Ref,
319 /*errnoMem=*/ModRefInfo::Ref,
320 /*targetMem0=*/ModRefInfo::Ref,
321 /*targetMem1=*/ModRefInfo::Ref);
322 noUnwind = true;
323 willReturn = true;
324 break;
325
326 case cir::SideEffect::Const:
327 memoryEffect = mlir::LLVM::MemoryEffectsAttr::get(
328 callOp->getContext(), /*other=*/ModRefInfo::NoModRef,
329 /*argMem=*/ModRefInfo::NoModRef,
330 /*inaccessibleMem=*/ModRefInfo::NoModRef,
331 /*errnoMem=*/ModRefInfo::NoModRef,
332 /*targetMem0=*/ModRefInfo::NoModRef,
333 /*targetMem1=*/ModRefInfo::NoModRef);
334 noUnwind = true;
335 willReturn = true;
336 break;
337 }
338 }
339
340 static mlir::LLVM::CallIntrinsicOp
341 createCallLLVMIntrinsicOp(mlir::ConversionPatternRewriter &rewriter,
342 mlir::Location loc, const llvm::Twine &intrinsicName,
343 mlir::Type resultTy, mlir::ValueRange operands) {
344 auto intrinsicNameAttr =
345 mlir::StringAttr::get(rewriter.getContext(), intrinsicName);
346 return mlir::LLVM::CallIntrinsicOp::create(rewriter, loc, resultTy,
347 intrinsicNameAttr, operands);
348 }
349
350 static mlir::LLVM::CallIntrinsicOp replaceOpWithCallLLVMIntrinsicOp(
351 mlir::ConversionPatternRewriter &rewriter, mlir::Operation *op,
352 const llvm::Twine &intrinsicName, mlir::Type resultTy,
353 mlir::ValueRange operands) {
354 mlir::LLVM::CallIntrinsicOp callIntrinOp = createCallLLVMIntrinsicOp(
355 rewriter, op->getLoc(), intrinsicName, resultTy, operands);
356 rewriter.replaceOp(op, callIntrinOp.getOperation());
357 return callIntrinOp;
358 }
359
360 mlir::LogicalResult CIRToLLVMLLVMIntrinsicCallOpLowering::matchAndRewrite(
361 cir::LLVMIntrinsicCallOp op, OpAdaptor adaptor,
362 mlir::ConversionPatternRewriter &rewriter) const {
363 mlir::Type llvmResTy =
364 getTypeConverter()->convertType(op->getResultTypes()[0]);
365 if (!llvmResTy)
366 return op.emitError("expected LLVM result type");
367 StringRef name = op.getIntrinsicName();
368
369 // Some LLVM intrinsics require ElementType attribute to be attached to
370 // the argument of pointer type. That prevents us from generating LLVM IR
371 // because from LLVM dialect, we have LLVM IR like the below which fails
372 // LLVM IR verification.
373 // %3 = call i64 @llvm.aarch64.ldxr.p0(ptr %2)
374 // The expected LLVM IR should be like
375 // %3 = call i64 @llvm.aarch64.ldxr.p0(ptr elementtype(i32) %2)
376 // TODO(cir): MLIR LLVM dialect should handle this part as CIR has no way
377 // to set LLVM IR attribute.
378 assert(!cir::MissingFeatures::intrinsicElementTypeSupport());
379 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm." + name, llvmResTy,
380 adaptor.getOperands());
381 return mlir::success();
382 }
383
384 /// IntAttr visitor.
385 mlir::Value CIRAttrToValue::visitCirAttr(cir::IntAttr intAttr) {
386 mlir::Location loc = parentOp->getLoc();
387 return mlir::LLVM::ConstantOp::create(
388 rewriter, loc, converter->convertType(intAttr.getType()),
389 intAttr.getValue());
390 }
391
392 /// FPAttr visitor.
393 mlir::Value CIRAttrToValue::visitCirAttr(cir::FPAttr fltAttr) {
394 mlir::Location loc = parentOp->getLoc();
395 return mlir::LLVM::ConstantOp::create(
396 rewriter, loc, converter->convertType(fltAttr.getType()),
397 fltAttr.getValue());
398 }
399
400 /// ConstComplexAttr visitor.
401 mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstComplexAttr complexAttr) {
402 auto complexType = mlir::cast<cir::ComplexType>(complexAttr.getType());
403 mlir::Type complexElemTy = complexType.getElementType();
404 mlir::Type complexElemLLVMTy = converter->convertType(complexElemTy);
405
406 mlir::Attribute components[2];
407 if (const auto intType = mlir::dyn_cast<cir::IntType>(complexElemTy)) {
408 components[0] = rewriter.getIntegerAttr(
409 complexElemLLVMTy,
410 mlir::cast<cir::IntAttr>(complexAttr.getReal()).getValue());
411 components[1] = rewriter.getIntegerAttr(
412 complexElemLLVMTy,
413 mlir::cast<cir::IntAttr>(complexAttr.getImag()).getValue());
414 } else {
415 components[0] = rewriter.getFloatAttr(
416 complexElemLLVMTy,
417 mlir::cast<cir::FPAttr>(complexAttr.getReal()).getValue());
418 components[1] = rewriter.getFloatAttr(
419 complexElemLLVMTy,
420 mlir::cast<cir::FPAttr>(complexAttr.getImag()).getValue());
421 }
422
423 mlir::Location loc = parentOp->getLoc();
424 return mlir::LLVM::ConstantOp::create(
425 rewriter, loc, converter->convertType(complexAttr.getType()),
426 rewriter.getArrayAttr(components));
427 }
428
429 /// ConstPtrAttr visitor.
430 mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstPtrAttr ptrAttr) {
431 mlir::Location loc = parentOp->getLoc();
432 if (ptrAttr.isNullValue()) {
433 return mlir::LLVM::ZeroOp::create(
434 rewriter, loc, converter->convertType(ptrAttr.getType()));
435 }
436 mlir::DataLayout layout(parentOp->getParentOfType<mlir::ModuleOp>());
437 mlir::Value ptrVal = mlir::LLVM::ConstantOp::create(
438 rewriter, loc,
439 rewriter.getIntegerType(layout.getTypeSizeInBits(ptrAttr.getType())),
440 ptrAttr.getValue().getInt());
441 return mlir::LLVM::IntToPtrOp::create(
442 rewriter, loc, converter->convertType(ptrAttr.getType()), ptrVal);
443 }
444
445 // ConstArrayAttr visitor
446 mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstArrayAttr attr) {
447 mlir::Type llvmTy = converter->convertType(attr.getType());
448 mlir::Location loc = parentOp->getLoc();
449 mlir::Value result;
450
451 if (attr.hasTrailingZeros()) {
452 mlir::Type arrayTy = attr.getType();
453 result = mlir::LLVM::ZeroOp::create(rewriter, loc,
454 converter->convertType(arrayTy));
455 } else {
456 result = mlir::LLVM::UndefOp::create(rewriter, loc, llvmTy);
457 }
458
459 // Iteratively lower each constant element of the array.
460 if (auto arrayAttr = mlir::dyn_cast<mlir::ArrayAttr>(attr.getElts())) {
461 for (auto [idx, elt] : llvm::enumerate(arrayAttr)) {
462 mlir::DataLayout dataLayout(parentOp->getParentOfType<mlir::ModuleOp>());
463 mlir::Value init = visit(elt);
464 result =
465 mlir::LLVM::InsertValueOp::create(rewriter, loc, result, init, idx);
466 }
467 } else if (auto strAttr = mlir::dyn_cast<mlir::StringAttr>(attr.getElts())) {
468 // TODO(cir): this diverges from traditional lowering. Normally the string
469 // would be a global constant that is memcopied.
470 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(strAttr.getType());
471 assert(arrayTy && "String attribute must have an array type");
472 mlir::Type eltTy = arrayTy.getElementType();
473 for (auto [idx, elt] : llvm::enumerate(strAttr)) {
474 auto init = mlir::LLVM::ConstantOp::create(
475 rewriter, loc, converter->convertType(eltTy), elt);
476 result =
477 mlir::LLVM::InsertValueOp::create(rewriter, loc, result, init, idx);
478 }
479 } else {
480 llvm_unreachable("unexpected ConstArrayAttr elements");
481 }
482
483 return result;
484 }
485
486 /// ConstRecord visitor.
487 mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstRecordAttr constRecord) {
488 const mlir::Type llvmTy = converter->convertType(constRecord.getType());
489 const mlir::Location loc = parentOp->getLoc();
490 mlir::Value result = mlir::LLVM::UndefOp::create(rewriter, loc, llvmTy);
491
492 // Iteratively lower each constant element of the record.
493 for (auto [idx, elt] : llvm::enumerate(constRecord.getMembers())) {
494 mlir::Value init = visit(elt);
495 result =
496 mlir::LLVM::InsertValueOp::create(rewriter, loc, result, init, idx);
497 }
498
499 return result;
500 }
501
502 /// ConstVectorAttr visitor.
503 mlir::Value CIRAttrToValue::visitCirAttr(cir::ConstVectorAttr attr) {
504 const mlir::Type llvmTy = converter->convertType(attr.getType());
505 const mlir::Location loc = parentOp->getLoc();
506
507 SmallVector<mlir::Attribute> mlirValues;
508 for (const mlir::Attribute elementAttr : attr.getElts()) {
509 mlir::Attribute mlirAttr;
510 if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(elementAttr)) {
511 mlirAttr = rewriter.getIntegerAttr(
512 converter->convertType(intAttr.getType()), intAttr.getValue());
513 } else if (auto floatAttr = mlir::dyn_cast<cir::FPAttr>(elementAttr)) {
514 mlirAttr = rewriter.getFloatAttr(
515 converter->convertType(floatAttr.getType()), floatAttr.getValue());
516 } else {
517 llvm_unreachable(
518 "vector constant with an element that is neither an int nor a float");
519 }
520 mlirValues.push_back(mlirAttr);
521 }
522
523 return mlir::LLVM::ConstantOp::create(
524 rewriter, loc, llvmTy,
525 mlir::DenseElementsAttr::get(mlir::cast<mlir::ShapedType>(llvmTy),
526 mlirValues));
527 }
528
529 // GlobalViewAttr visitor.
530 mlir::Value CIRAttrToValue::visitCirAttr(cir::GlobalViewAttr globalAttr) {
531 auto moduleOp = parentOp->getParentOfType<mlir::ModuleOp>();
532 mlir::DataLayout dataLayout(moduleOp);
533 mlir::Type sourceType;
534 assert(!cir::MissingFeatures::addressSpace());
535 llvm::StringRef symName;
536 mlir::Operation *sourceSymbol =
537 mlir::SymbolTable::lookupSymbolIn(moduleOp, globalAttr.getSymbol());
538 if (auto llvmSymbol = dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
539 sourceType = llvmSymbol.getType();
540 symName = llvmSymbol.getSymName();
541 } else if (auto cirSymbol = dyn_cast<cir::GlobalOp>(sourceSymbol)) {
542 sourceType =
543 convertTypeForMemory(*converter, dataLayout, cirSymbol.getSymType());
544 symName = cirSymbol.getSymName();
545 } else if (auto llvmFun = dyn_cast<mlir::LLVM::LLVMFuncOp>(sourceSymbol)) {
546 sourceType = llvmFun.getFunctionType();
547 symName = llvmFun.getSymName();
548 } else if (auto fun = dyn_cast<cir::FuncOp>(sourceSymbol)) {
549 sourceType = converter->convertType(fun.getFunctionType());
550 symName = fun.getSymName();
551 } else if (auto alias = dyn_cast<mlir::LLVM::AliasOp>(sourceSymbol)) {
552 sourceType = alias.getType();
553 symName = alias.getSymName();
554 } else {
555 llvm_unreachable("Unexpected GlobalOp type");
556 }
557
558 mlir::Location loc = parentOp->getLoc();
559 mlir::Value addrOp = mlir::LLVM::AddressOfOp::create(
560 rewriter, loc, mlir::LLVM::LLVMPointerType::get(rewriter.getContext()),
561 symName);
562
563 if (globalAttr.getIndices()) {
564 llvm::SmallVector<mlir::LLVM::GEPArg> indices;
565
566 if (mlir::isa<mlir::LLVM::LLVMArrayType, mlir::LLVM::LLVMStructType>(
567 sourceType))
568 indices.push_back(0);
569
570 for (mlir::Attribute idx : globalAttr.getIndices()) {
571 auto intAttr = mlir::cast<mlir::IntegerAttr>(idx);
572 indices.push_back(intAttr.getValue().getSExtValue());
573 }
574 mlir::Type resTy = addrOp.getType();
575 mlir::Type eltTy = converter->convertType(sourceType);
576 addrOp =
577 mlir::LLVM::GEPOp::create(rewriter, loc, resTy, eltTy, addrOp, indices,
578 mlir::LLVM::GEPNoWrapFlags::none);
579 }
580
581 // The incubator has handling here for the attribute having integer type, but
582 // the only test case I could find that reaches it is a direct CIR-to-LLVM IR
583 // lowering with no clear indication of how the CIR might have been generated.
584 // We'll hit the unreachable below if this happens.
585 assert(!cir::MissingFeatures::globalViewIntLowering());
586
587 if (auto ptrTy = mlir::dyn_cast<cir::PointerType>(globalAttr.getType())) {
588 mlir::Type llvmEltTy =
589 convertTypeForMemory(*converter, dataLayout, ptrTy.getPointee());
590
591 if (llvmEltTy == sourceType)
592 return addrOp;
593
594 mlir::Type llvmDstTy = converter->convertType(globalAttr.getType());
595 return mlir::LLVM::BitcastOp::create(rewriter, parentOp->getLoc(),
596 llvmDstTy, addrOp);
597 }
598
599 llvm_unreachable("Expecting pointer or integer type for GlobalViewAttr");
600 }
601
602 // TypeInfoAttr visitor.
603 mlir::Value CIRAttrToValue::visitCirAttr(cir::TypeInfoAttr typeInfoAttr) {
604 mlir::Type llvmTy = converter->convertType(typeInfoAttr.getType());
605 mlir::Location loc = parentOp->getLoc();
606 mlir::Value result = mlir::LLVM::UndefOp::create(rewriter, loc, llvmTy);
607
608 for (auto [idx, elt] : llvm::enumerate(typeInfoAttr.getData())) {
609 mlir::Value init = visit(elt);
610 result =
611 mlir::LLVM::InsertValueOp::create(rewriter, loc, result, init, idx);
612 }
613
614 return result;
615 }
616
617 /// UndefAttr visitor.
618 mlir::Value CIRAttrToValue::visitCirAttr(cir::UndefAttr undefAttr) {
619 mlir::Location loc = parentOp->getLoc();
620 return mlir::LLVM::UndefOp::create(
621 rewriter, loc, converter->convertType(undefAttr.getType()));
622 }
623
624 // VTableAttr visitor.
625 mlir::Value CIRAttrToValue::visitCirAttr(cir::VTableAttr vtableArr) {
626 mlir::Type llvmTy = converter->convertType(vtableArr.getType());
627 mlir::Location loc = parentOp->getLoc();
628 mlir::Value result = mlir::LLVM::UndefOp::create(rewriter, loc, llvmTy);
629
630 for (auto [idx, elt] : llvm::enumerate(vtableArr.getData())) {
631 mlir::Value init = visit(elt);
632 result =
633 mlir::LLVM::InsertValueOp::create(rewriter, loc, result, init, idx);
634 }
635
636 return result;
637 }
638
639 /// ZeroAttr visitor.
640 mlir::Value CIRAttrToValue::visitCirAttr(cir::ZeroAttr attr) {
641 mlir::Location loc = parentOp->getLoc();
642 return mlir::LLVM::ZeroOp::create(rewriter, loc,
643 converter->convertType(attr.getType()));
644 }
645
646 // This class handles rewriting initializer attributes for types that do not
647 // require region initialization.
648 class GlobalInitAttrRewriter {
649 public:
650 GlobalInitAttrRewriter(mlir::Type type,
651 mlir::ConversionPatternRewriter &rewriter)
652 : llvmType(type), rewriter(rewriter) {}
653
654 mlir::Attribute visit(mlir::Attribute attr) {
655 return llvm::TypeSwitch<mlir::Attribute, mlir::Attribute>(attr)
656 .Case<cir::IntAttr, cir::FPAttr, cir::BoolAttr>(
657 [&](auto attrT) { return visitCirAttr(attrT); })
658 .Default([&](auto attrT) { return mlir::Attribute(); });
659 }
660
661 mlir::Attribute visitCirAttr(cir::IntAttr attr) {
662 return rewriter.getIntegerAttr(llvmType, attr.getValue());
663 }
664
665 mlir::Attribute visitCirAttr(cir::FPAttr attr) {
666 return rewriter.getFloatAttr(llvmType, attr.getValue());
667 }
668
669 mlir::Attribute visitCirAttr(cir::BoolAttr attr) {
670 return rewriter.getBoolAttr(attr.getValue());
671 }
672
673 private:
674 mlir::Type llvmType;
675 mlir::ConversionPatternRewriter &rewriter;
676 };
677
678 // This pass requires the CIR to be in a "flat" state. All blocks in each
679 // function must belong to the parent region. Once scopes and control flow
680 // are implemented in CIR, a pass will be run before this one to flatten
681 // the CIR and get it into the state that this pass requires.
682 struct ConvertCIRToLLVMPass
683 : public mlir::PassWrapper<ConvertCIRToLLVMPass,
684 mlir::OperationPass<mlir::ModuleOp>> {
685 void getDependentDialects(mlir::DialectRegistry &registry) const override {
686 registry.insert<mlir::BuiltinDialect, mlir::DLTIDialect,
687 mlir::LLVM::LLVMDialect, mlir::func::FuncDialect>();
688 }
689 void runOnOperation() final;
690
691 void processCIRAttrs(mlir::ModuleOp module);
692
693 StringRef getDescription() const override {
694 return "Convert the prepared CIR dialect module to LLVM dialect";
695 }
696
697 StringRef getArgument() const override { return "cir-flat-to-llvm"; }
698 };
699
700 mlir::LogicalResult CIRToLLVMACosOpLowering::matchAndRewrite(
701 cir::ACosOp op, OpAdaptor adaptor,
702 mlir::ConversionPatternRewriter &rewriter) const {
703 mlir::Type resTy = typeConverter->convertType(op.getType());
704 rewriter.replaceOpWithNewOp<mlir::LLVM::ACosOp>(op, resTy,
705 adaptor.getOperands()[0]);
706 return mlir::success();
707 }
708
709 mlir::LogicalResult CIRToLLVMASinOpLowering::matchAndRewrite(
710 cir::ASinOp op, OpAdaptor adaptor,
711 mlir::ConversionPatternRewriter &rewriter) const {
712 mlir::Type resTy = typeConverter->convertType(op.getType());
713 rewriter.replaceOpWithNewOp<mlir::LLVM::ASinOp>(op, resTy, adaptor.getSrc());
714 return mlir::success();
715 }
716
717 mlir::LogicalResult CIRToLLVMIsFPClassOpLowering::matchAndRewrite(
718 cir::IsFPClassOp op, OpAdaptor adaptor,
719 mlir::ConversionPatternRewriter &rewriter) const {
720 mlir::Value src = adaptor.getSrc();
721 cir::FPClassTest flags = adaptor.getFlags();
722 mlir::IntegerType retTy = rewriter.getI1Type();
723
724 rewriter.replaceOpWithNewOp<mlir::LLVM::IsFPClass>(
725 op, retTy, src, static_cast<uint32_t>(flags));
726 return mlir::success();
727 }
728
729 mlir::LogicalResult CIRToLLVMAssumeOpLowering::matchAndRewrite(
730 cir::AssumeOp op, OpAdaptor adaptor,
731 mlir::ConversionPatternRewriter &rewriter) const {
732 auto cond = adaptor.getPredicate();
733 rewriter.replaceOpWithNewOp<mlir::LLVM::AssumeOp>(op, cond);
734 return mlir::success();
735 }
736
737 mlir::LogicalResult CIRToLLVMAssumeAlignedOpLowering::matchAndRewrite(
738 cir::AssumeAlignedOp op, OpAdaptor adaptor,
739 mlir::ConversionPatternRewriter &rewriter) const {
740 SmallVector<mlir::Value, 3> opBundleArgs{adaptor.getPointer()};
741
742 auto alignment = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
743 adaptor.getAlignmentAttr());
744 opBundleArgs.push_back(alignment);
745
746 if (mlir::Value offset = adaptor.getOffset())
747 opBundleArgs.push_back(offset);
748
749 auto cond = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
750 rewriter.getI1Type(), 1);
751 mlir::LLVM::AssumeOp::create(rewriter, op.getLoc(), cond, "align",
752 opBundleArgs);
753
754 // The llvm.assume operation does not have a result, so we need to replace
755 // all uses of this cir.assume_aligned operation with the input ptr itself.
756 rewriter.replaceOp(op, adaptor.getPointer());
757 return mlir::success();
758 }
759
760 mlir::LogicalResult CIRToLLVMAssumeSepStorageOpLowering::matchAndRewrite(
761 cir::AssumeSepStorageOp op, OpAdaptor adaptor,
762 mlir::ConversionPatternRewriter &rewriter) const {
763 auto cond = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
764 rewriter.getI1Type(), 1);
765 rewriter.replaceOpWithNewOp<mlir::LLVM::AssumeOp>(
766 op, cond, mlir::LLVM::AssumeSeparateStorageTag{}, adaptor.getPtr1(),
767 adaptor.getPtr2());
768 return mlir::success();
769 }
770
771 static mlir::LLVM::AtomicOrdering
772 getLLVMMemOrder(std::optional<cir::MemOrder> memorder) {
773 if (!memorder)
774 return mlir::LLVM::AtomicOrdering::not_atomic;
775 switch (*memorder) {
776 case cir::MemOrder::Relaxed:
777 return mlir::LLVM::AtomicOrdering::monotonic;
778 case cir::MemOrder::Consume:
779 case cir::MemOrder::Acquire:
780 return mlir::LLVM::AtomicOrdering::acquire;
781 case cir::MemOrder::Release:
782 return mlir::LLVM::AtomicOrdering::release;
783 case cir::MemOrder::AcquireRelease:
784 return mlir::LLVM::AtomicOrdering::acq_rel;
785 case cir::MemOrder::SequentiallyConsistent:
786 return mlir::LLVM::AtomicOrdering::seq_cst;
787 }
788 llvm_unreachable("unknown memory order");
789 }
790
791 static std::optional<llvm::StringRef>
792 getLLVMSyncScope(std::optional<cir::SyncScopeKind> syncScope) {
793 if (syncScope.has_value())
794 return syncScope.value() == cir::SyncScopeKind::SingleThread
795 ? "singlethread"
796 : "";
797 return std::nullopt;
798 }
799
800 mlir::LogicalResult CIRToLLVMAtomicCmpXchgOpLowering::matchAndRewrite(
801 cir::AtomicCmpXchgOp op, OpAdaptor adaptor,
802 mlir::ConversionPatternRewriter &rewriter) const {
803 mlir::Value expected = adaptor.getExpected();
804 mlir::Value desired = adaptor.getDesired();
805
806 auto cmpxchg = mlir::LLVM::AtomicCmpXchgOp::create(
807 rewriter, op.getLoc(), adaptor.getPtr(), expected, desired,
808 getLLVMMemOrder(adaptor.getSuccOrder()),
809 getLLVMMemOrder(adaptor.getFailOrder()));
810 assert(!cir::MissingFeatures::atomicScope());
811 cmpxchg.setAlignment(adaptor.getAlignment());
812 cmpxchg.setWeak(adaptor.getWeak());
813 cmpxchg.setVolatile_(adaptor.getIsVolatile());
814
815 // Check result and apply stores accordingly.
816 auto old = mlir::LLVM::ExtractValueOp::create(rewriter, op.getLoc(),
817 cmpxchg.getResult(), 0);
818 auto cmp = mlir::LLVM::ExtractValueOp::create(rewriter, op.getLoc(),
819 cmpxchg.getResult(), 1);
820
821 rewriter.replaceOp(op, {old, cmp});
822 return mlir::success();
823 }
824
825 mlir::LogicalResult CIRToLLVMAtomicXchgOpLowering::matchAndRewrite(
826 cir::AtomicXchgOp op, OpAdaptor adaptor,
827 mlir::ConversionPatternRewriter &rewriter) const {
828 assert(!cir::MissingFeatures::atomicSyncScopeID());
829 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(adaptor.getMemOrder());
830 rewriter.replaceOpWithNewOp<mlir::LLVM::AtomicRMWOp>(
831 op, mlir::LLVM::AtomicBinOp::xchg, adaptor.getPtr(), adaptor.getVal(),
832 llvmOrder);
833 return mlir::success();
834 }
835
836 mlir::LogicalResult CIRToLLVMAtomicTestAndSetOpLowering::matchAndRewrite(
837 cir::AtomicTestAndSetOp op, OpAdaptor adaptor,
838 mlir::ConversionPatternRewriter &rewriter) const {
839 assert(!cir::MissingFeatures::atomicSyncScopeID());
840
841 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(op.getMemOrder());
842
843 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
844 rewriter.getI8Type(), 1);
845 auto rmw = mlir::LLVM::AtomicRMWOp::create(
846 rewriter, op.getLoc(), mlir::LLVM::AtomicBinOp::xchg, adaptor.getPtr(),
847 one, llvmOrder, /*syncscope=*/llvm::StringRef(),
848 adaptor.getAlignment().value_or(0), op.getIsVolatile());
849
850 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
851 rewriter.getI8Type(), 0);
852 auto cmp = mlir::LLVM::ICmpOp::create(
853 rewriter, op.getLoc(), mlir::LLVM::ICmpPredicate::ne, rmw, zero);
854
855 rewriter.replaceOp(op, cmp);
856 return mlir::success();
857 }
858
859 mlir::LogicalResult CIRToLLVMAtomicClearOpLowering::matchAndRewrite(
860 cir::AtomicClearOp op, OpAdaptor adaptor,
861 mlir::ConversionPatternRewriter &rewriter) const {
862 assert(!cir::MissingFeatures::atomicSyncScopeID());
863
864 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(op.getMemOrder());
865 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
866 rewriter.getI8Type(), 0);
867 auto store = mlir::LLVM::StoreOp::create(
868 rewriter, op.getLoc(), zero, adaptor.getPtr(),
869 adaptor.getAlignment().value_or(0), op.getIsVolatile(),
870 /*isNonTemporal=*/false, /*isInvariantGroup=*/false, llvmOrder);
871
872 rewriter.replaceOp(op, store);
873 return mlir::success();
874 }
875
876 mlir::LogicalResult CIRToLLVMAtomicFenceOpLowering::matchAndRewrite(
877 cir::AtomicFenceOp op, OpAdaptor adaptor,
878 mlir::ConversionPatternRewriter &rewriter) const {
879 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(adaptor.getOrdering());
880
881 auto fence = mlir::LLVM::FenceOp::create(rewriter, op.getLoc(), llvmOrder);
882 fence.setSyncscope(getLLVMSyncScope(adaptor.getSyncscope()));
883
884 rewriter.replaceOp(op, fence);
885
886 return mlir::success();
887 }
888
889 static mlir::LLVM::AtomicBinOp
890 getLLVMAtomicBinOp(cir::AtomicFetchKind k, bool isInt, bool isSignedInt) {
891 switch (k) {
892 case cir::AtomicFetchKind::Add:
893 return isInt ? mlir::LLVM::AtomicBinOp::add : mlir::LLVM::AtomicBinOp::fadd;
894 case cir::AtomicFetchKind::Sub:
895 return isInt ? mlir::LLVM::AtomicBinOp::sub : mlir::LLVM::AtomicBinOp::fsub;
896 case cir::AtomicFetchKind::And:
897 return mlir::LLVM::AtomicBinOp::_and;
898 case cir::AtomicFetchKind::Xor:
899 return mlir::LLVM::AtomicBinOp::_xor;
900 case cir::AtomicFetchKind::Or:
901 return mlir::LLVM::AtomicBinOp::_or;
902 case cir::AtomicFetchKind::Nand:
903 return mlir::LLVM::AtomicBinOp::nand;
904 case cir::AtomicFetchKind::Max: {
905 if (!isInt)
906 return mlir::LLVM::AtomicBinOp::fmax;
907 return isSignedInt ? mlir::LLVM::AtomicBinOp::max
908 : mlir::LLVM::AtomicBinOp::umax;
909 }
910 case cir::AtomicFetchKind::Min: {
911 if (!isInt)
912 return mlir::LLVM::AtomicBinOp::fmin;
913 return isSignedInt ? mlir::LLVM::AtomicBinOp::min
914 : mlir::LLVM::AtomicBinOp::umin;
915 }
916 }
917 llvm_unreachable("Unknown atomic fetch opcode");
918 }
919
920 static llvm::StringLiteral getLLVMBinop(cir::AtomicFetchKind k, bool isInt) {
921 switch (k) {
922 case cir::AtomicFetchKind::Add:
923 return isInt ? mlir::LLVM::AddOp::getOperationName()
924 : mlir::LLVM::FAddOp::getOperationName();
925 case cir::AtomicFetchKind::Sub:
926 return isInt ? mlir::LLVM::SubOp::getOperationName()
927 : mlir::LLVM::FSubOp::getOperationName();
928 case cir::AtomicFetchKind::And:
929 return mlir::LLVM::AndOp::getOperationName();
930 case cir::AtomicFetchKind::Xor:
931 return mlir::LLVM::XOrOp::getOperationName();
932 case cir::AtomicFetchKind::Or:
933 return mlir::LLVM::OrOp::getOperationName();
934 case cir::AtomicFetchKind::Nand:
935 // There's no nand binop in LLVM, this is later fixed with a not.
936 return mlir::LLVM::AndOp::getOperationName();
937 case cir::AtomicFetchKind::Max:
938 case cir::AtomicFetchKind::Min:
939 llvm_unreachable("handled in buildMinMaxPostOp");
940 }
941 llvm_unreachable("Unknown atomic fetch opcode");
942 }
943
944 mlir::Value CIRToLLVMAtomicFetchOpLowering::buildPostOp(
945 cir::AtomicFetchOp op, OpAdaptor adaptor,
946 mlir::ConversionPatternRewriter &rewriter, mlir::Value rmwVal,
947 bool isInt) const {
948 SmallVector<mlir::Value> atomicOperands = {rmwVal, adaptor.getVal()};
949 SmallVector<mlir::Type> atomicResTys = {rmwVal.getType()};
950 return rewriter
951 .create(op.getLoc(),
952 rewriter.getStringAttr(getLLVMBinop(op.getBinop(), isInt)),
953 atomicOperands, atomicResTys, {})
954 ->getResult(0);
955 }
956
957 mlir::Value CIRToLLVMAtomicFetchOpLowering::buildMinMaxPostOp(
958 cir::AtomicFetchOp op, OpAdaptor adaptor,
959 mlir::ConversionPatternRewriter &rewriter, mlir::Value rmwVal, bool isInt,
960 bool isSigned) const {
961 mlir::Location loc = op.getLoc();
962
963 if (!isInt) {
964 if (op.getBinop() == cir::AtomicFetchKind::Max)
965 return mlir::LLVM::MaxNumOp::create(rewriter, loc, rmwVal,
966 adaptor.getVal());
967 return mlir::LLVM::MinNumOp::create(rewriter, loc, rmwVal,
968 adaptor.getVal());
969 }
970
971 mlir::LLVM::ICmpPredicate pred;
972 if (op.getBinop() == cir::AtomicFetchKind::Max) {
973 pred = isSigned ? mlir::LLVM::ICmpPredicate::sgt
974 : mlir::LLVM::ICmpPredicate::ugt;
975 } else { // Min
976 pred = isSigned ? mlir::LLVM::ICmpPredicate::slt
977 : mlir::LLVM::ICmpPredicate::ult;
978 }
979 mlir::Value cmp = mlir::LLVM::ICmpOp::create(
980 rewriter, loc,
981 mlir::LLVM::ICmpPredicateAttr::get(rewriter.getContext(), pred), rmwVal,
982 adaptor.getVal());
983 return mlir::LLVM::SelectOp::create(rewriter, loc, cmp, rmwVal,
984 adaptor.getVal());
985 }
986
987 mlir::LogicalResult CIRToLLVMAtomicFetchOpLowering::matchAndRewrite(
988 cir::AtomicFetchOp op, OpAdaptor adaptor,
989 mlir::ConversionPatternRewriter &rewriter) const {
990 bool isInt = false;
991 bool isSignedInt = false;
992 if (auto intTy = mlir::dyn_cast<cir::IntType>(op.getVal().getType())) {
993 isInt = true;
994 isSignedInt = intTy.isSigned();
995 } else if (mlir::isa<cir::SingleType, cir::DoubleType>(
996 op.getVal().getType())) {
997 isInt = false;
998 } else {
999 return op.emitError() << "Unsupported type: " << op.getVal().getType();
1000 }
1001
1002 mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(op.getMemOrder());
1003 mlir::LLVM::AtomicBinOp llvmBinOp =
1004 getLLVMAtomicBinOp(op.getBinop(), isInt, isSignedInt);
1005 auto rmwVal = mlir::LLVM::AtomicRMWOp::create(rewriter, op.getLoc(),
1006 llvmBinOp, adaptor.getPtr(),
1007 adaptor.getVal(), llvmOrder);
1008
1009 mlir::Value result = rmwVal.getResult();
1010 if (!op.getFetchFirst()) {
1011 if (op.getBinop() == cir::AtomicFetchKind::Max ||
1012 op.getBinop() == cir::AtomicFetchKind::Min)
1013 result = buildMinMaxPostOp(op, adaptor, rewriter, rmwVal.getRes(), isInt,
1014 isSignedInt);
1015 else
1016 result = buildPostOp(op, adaptor, rewriter, rmwVal.getRes(), isInt);
1017
1018 // Compensate lack of nand binop in LLVM IR.
1019 if (op.getBinop() == cir::AtomicFetchKind::Nand) {
1020 auto negOne = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1021 result.getType(), -1);
1022 result = mlir::LLVM::XOrOp::create(rewriter, op.getLoc(), result, negOne);
1023 }
1024 }
1025
1026 rewriter.replaceOp(op, result);
1027 return mlir::success();
1028 }
1029
1030 mlir::LogicalResult CIRToLLVMBitClrsbOpLowering::matchAndRewrite(
1031 cir::BitClrsbOp op, OpAdaptor adaptor,
1032 mlir::ConversionPatternRewriter &rewriter) const {
1033 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1034 adaptor.getInput().getType(), 0);
1035 auto isNeg = mlir::LLVM::ICmpOp::create(
1036 rewriter, op.getLoc(),
1037 mlir::LLVM::ICmpPredicateAttr::get(rewriter.getContext(),
1038 mlir::LLVM::ICmpPredicate::slt),
1039 adaptor.getInput(), zero);
1040
1041 auto negOne = mlir::LLVM::ConstantOp::create(
1042 rewriter, op.getLoc(), adaptor.getInput().getType(), -1);
1043 auto flipped = mlir::LLVM::XOrOp::create(rewriter, op.getLoc(),
1044 adaptor.getInput(), negOne);
1045
1046 auto select = mlir::LLVM::SelectOp::create(rewriter, op.getLoc(), isNeg,
1047 flipped, adaptor.getInput());
1048
1049 auto resTy = getTypeConverter()->convertType(op.getType());
1050 auto clz = mlir::LLVM::CountLeadingZerosOp::create(
1051 rewriter, op.getLoc(), resTy, select, /*is_zero_poison=*/false);
1052
1053 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 1);
1054 auto res = mlir::LLVM::SubOp::create(rewriter, op.getLoc(), clz, one,
1055 mlir::LLVM::IntegerOverflowFlags::nuw);
1056 rewriter.replaceOp(op, res);
1057
1058 return mlir::LogicalResult::success();
1059 }
1060
1061 mlir::LogicalResult CIRToLLVMBitClzOpLowering::matchAndRewrite(
1062 cir::BitClzOp op, OpAdaptor adaptor,
1063 mlir::ConversionPatternRewriter &rewriter) const {
1064 auto resTy = getTypeConverter()->convertType(op.getType());
1065 auto llvmOp = mlir::LLVM::CountLeadingZerosOp::create(
1066 rewriter, op.getLoc(), resTy, adaptor.getInput(), op.getPoisonZero());
1067 rewriter.replaceOp(op, llvmOp);
1068 return mlir::LogicalResult::success();
1069 }
1070
1071 mlir::LogicalResult CIRToLLVMBitCtzOpLowering::matchAndRewrite(
1072 cir::BitCtzOp op, OpAdaptor adaptor,
1073 mlir::ConversionPatternRewriter &rewriter) const {
1074 auto resTy = getTypeConverter()->convertType(op.getType());
1075 auto llvmOp = mlir::LLVM::CountTrailingZerosOp::create(
1076 rewriter, op.getLoc(), resTy, adaptor.getInput(), op.getPoisonZero());
1077 rewriter.replaceOp(op, llvmOp);
1078 return mlir::LogicalResult::success();
1079 }
1080
1081 mlir::LogicalResult CIRToLLVMBitFfsOpLowering::matchAndRewrite(
1082 cir::BitFfsOp op, OpAdaptor adaptor,
1083 mlir::ConversionPatternRewriter &rewriter) const {
1084 auto resTy = getTypeConverter()->convertType(op.getType());
1085 auto ctz = mlir::LLVM::CountTrailingZerosOp::create(rewriter, op.getLoc(),
1086 resTy, adaptor.getInput(),
1087 /*is_zero_poison=*/true);
1088
1089 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 1);
1090 auto ctzAddOne = mlir::LLVM::AddOp::create(rewriter, op.getLoc(), ctz, one);
1091
1092 auto zeroInputTy = mlir::LLVM::ConstantOp::create(
1093 rewriter, op.getLoc(), adaptor.getInput().getType(), 0);
1094 auto isZero = mlir::LLVM::ICmpOp::create(
1095 rewriter, op.getLoc(),
1096 mlir::LLVM::ICmpPredicateAttr::get(rewriter.getContext(),
1097 mlir::LLVM::ICmpPredicate::eq),
1098 adaptor.getInput(), zeroInputTy);
1099
1100 auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 0);
1101 auto res = mlir::LLVM::SelectOp::create(rewriter, op.getLoc(), isZero, zero,
1102 ctzAddOne);
1103 rewriter.replaceOp(op, res);
1104
1105 return mlir::LogicalResult::success();
1106 }
1107
1108 mlir::LogicalResult CIRToLLVMBitParityOpLowering::matchAndRewrite(
1109 cir::BitParityOp op, OpAdaptor adaptor,
1110 mlir::ConversionPatternRewriter &rewriter) const {
1111 auto resTy = getTypeConverter()->convertType(op.getType());
1112 auto popcnt = mlir::LLVM::CtPopOp::create(rewriter, op.getLoc(), resTy,
1113 adaptor.getInput());
1114
1115 auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(), resTy, 1);
1116 auto popcntMod2 =
1117 mlir::LLVM::AndOp::create(rewriter, op.getLoc(), popcnt, one);
1118 rewriter.replaceOp(op, popcntMod2);
1119
1120 return mlir::LogicalResult::success();
1121 }
1122
1123 mlir::LogicalResult CIRToLLVMBitPopcountOpLowering::matchAndRewrite(
1124 cir::BitPopcountOp op, OpAdaptor adaptor,
1125 mlir::ConversionPatternRewriter &rewriter) const {
1126 auto resTy = getTypeConverter()->convertType(op.getType());
1127 auto llvmOp = mlir::LLVM::CtPopOp::create(rewriter, op.getLoc(), resTy,
1128 adaptor.getInput());
1129 rewriter.replaceOp(op, llvmOp);
1130 return mlir::LogicalResult::success();
1131 }
1132
1133 mlir::LogicalResult CIRToLLVMBitReverseOpLowering::matchAndRewrite(
1134 cir::BitReverseOp op, OpAdaptor adaptor,
1135 mlir::ConversionPatternRewriter &rewriter) const {
1136 rewriter.replaceOpWithNewOp<mlir::LLVM::BitReverseOp>(op, adaptor.getInput());
1137 return mlir::success();
1138 }
1139
1140 mlir::LogicalResult CIRToLLVMBrCondOpLowering::matchAndRewrite(
1141 cir::BrCondOp brOp, OpAdaptor adaptor,
1142 mlir::ConversionPatternRewriter &rewriter) const {
1143 // When ZExtOp is implemented, we'll need to check if the condition is a
1144 // ZExtOp and if so, delete it if it has a single use.
1145 assert(!cir::MissingFeatures::zextOp());
1146
1147 mlir::Value i1Condition = adaptor.getCond();
1148
1149 rewriter.replaceOpWithNewOp<mlir::LLVM::CondBrOp>(
1150 brOp, i1Condition, brOp.getDestTrue(), adaptor.getDestOperandsTrue(),
1151 brOp.getDestFalse(), adaptor.getDestOperandsFalse());
1152
1153 return mlir::success();
1154 }
1155
1156 mlir::LogicalResult CIRToLLVMByteSwapOpLowering::matchAndRewrite(
1157 cir::ByteSwapOp op, OpAdaptor adaptor,
1158 mlir::ConversionPatternRewriter &rewriter) const {
1159 rewriter.replaceOpWithNewOp<mlir::LLVM::ByteSwapOp>(op, adaptor.getInput());
1160 return mlir::LogicalResult::success();
1161 }
1162
1163 mlir::Type CIRToLLVMCastOpLowering::convertTy(mlir::Type ty) const {
1164 return getTypeConverter()->convertType(ty);
1165 }
1166
1167 mlir::LogicalResult CIRToLLVMCastOpLowering::matchAndRewrite(
1168 cir::CastOp castOp, OpAdaptor adaptor,
1169 mlir::ConversionPatternRewriter &rewriter) const {
1170 // For arithmetic conversions, LLVM IR uses the same instruction to convert
1171 // both individual scalars and entire vectors. This lowering pass handles
1172 // both situations.
1173
1174 switch (castOp.getKind()) {
1175 case cir::CastKind::array_to_ptrdecay: {
1176 const auto ptrTy = mlir::cast<cir::PointerType>(castOp.getType());
1177 mlir::Value sourceValue = adaptor.getSrc();
1178 mlir::Type targetType = convertTy(ptrTy);
1179 mlir::Type elementTy = convertTypeForMemory(*getTypeConverter(), dataLayout,
1180 ptrTy.getPointee());
1181 llvm::SmallVector<mlir::LLVM::GEPArg> offset{0};
1182 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
1183 castOp, targetType, elementTy, sourceValue, offset);
1184 break;
1185 }
1186 case cir::CastKind::int_to_bool: {
1187 mlir::Value llvmSrcVal = adaptor.getSrc();
1188 mlir::Value zeroInt = mlir::LLVM::ConstantOp::create(
1189 rewriter, castOp.getLoc(), llvmSrcVal.getType(), 0);
1190 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
1191 castOp, mlir::LLVM::ICmpPredicate::ne, llvmSrcVal, zeroInt);
1192 break;
1193 }
1194 case cir::CastKind::integral: {
1195 mlir::Type srcType = castOp.getSrc().getType();
1196 mlir::Type dstType = castOp.getType();
1197 mlir::Value llvmSrcVal = adaptor.getSrc();
1198 mlir::Type llvmDstType = getTypeConverter()->convertType(dstType);
1199 cir::IntType srcIntType =
1200 mlir::cast<cir::IntType>(elementTypeIfVector(srcType));
1201 cir::IntType dstIntType =
1202 mlir::cast<cir::IntType>(elementTypeIfVector(dstType));
1203 rewriter.replaceOp(castOp, getLLVMIntCast(rewriter, llvmSrcVal, llvmDstType,
1204 srcIntType.isUnsigned(),
1205 srcIntType.getWidth(),
1206 dstIntType.getWidth()));
1207 break;
1208 }
1209 case cir::CastKind::floating: {
1210 mlir::Value llvmSrcVal = adaptor.getSrc();
1211 mlir::Type llvmDstTy = getTypeConverter()->convertType(castOp.getType());
1212
1213 mlir::Type srcTy = elementTypeIfVector(castOp.getSrc().getType());
1214 mlir::Type dstTy = elementTypeIfVector(castOp.getType());
1215
1216 if (!mlir::isa<cir::FPTypeInterface>(dstTy) ||
1217 !mlir::isa<cir::FPTypeInterface>(srcTy))
1218 return castOp.emitError() << "NYI cast from " << srcTy << " to " << dstTy;
1219
1220 auto getFloatWidth = [](mlir::Type ty) -> unsigned {
1221 return mlir::cast<cir::FPTypeInterface>(ty).getWidth();
1222 };
1223
1224 if (getFloatWidth(srcTy) > getFloatWidth(dstTy))
1225 rewriter.replaceOpWithNewOp<mlir::LLVM::FPTruncOp>(castOp, llvmDstTy,
1226 llvmSrcVal);
1227 else
1228 rewriter.replaceOpWithNewOp<mlir::LLVM::FPExtOp>(castOp, llvmDstTy,
1229 llvmSrcVal);
1230 return mlir::success();
1231 }
1232 case cir::CastKind::int_to_ptr: {
1233 auto dstTy = mlir::cast<cir::PointerType>(castOp.getType());
1234 mlir::Value llvmSrcVal = adaptor.getSrc();
1235 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1236 rewriter.replaceOpWithNewOp<mlir::LLVM::IntToPtrOp>(castOp, llvmDstTy,
1237 llvmSrcVal);
1238 return mlir::success();
1239 }
1240 case cir::CastKind::ptr_to_int: {
1241 auto dstTy = mlir::cast<cir::IntType>(castOp.getType());
1242 mlir::Value llvmSrcVal = adaptor.getSrc();
1243 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1244 rewriter.replaceOpWithNewOp<mlir::LLVM::PtrToIntOp>(castOp, llvmDstTy,
1245 llvmSrcVal);
1246 return mlir::success();
1247 }
1248 case cir::CastKind::float_to_bool: {
1249 mlir::Value llvmSrcVal = adaptor.getSrc();
1250 auto kind = mlir::LLVM::FCmpPredicate::une;
1251
1252 // Check if float is not equal to zero.
1253 auto zeroFloat = mlir::LLVM::ConstantOp::create(
1254 rewriter, castOp.getLoc(), llvmSrcVal.getType(),
1255 mlir::FloatAttr::get(llvmSrcVal.getType(), 0.0));
1256
1257 // Extend comparison result to either bool (C++) or int (C).
1258 rewriter.replaceOpWithNewOp<mlir::LLVM::FCmpOp>(castOp, kind, llvmSrcVal,
1259 zeroFloat);
1260
1261 return mlir::success();
1262 }
1263 case cir::CastKind::bool_to_int: {
1264 auto dstTy = mlir::cast<cir::IntType>(castOp.getType());
1265 mlir::Value llvmSrcVal = adaptor.getSrc();
1266 auto llvmSrcTy = mlir::cast<mlir::IntegerType>(llvmSrcVal.getType());
1267 auto llvmDstTy =
1268 mlir::cast<mlir::IntegerType>(getTypeConverter()->convertType(dstTy));
1269 if (llvmSrcTy.getWidth() == llvmDstTy.getWidth())
1270 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(castOp, llvmDstTy,
1271 llvmSrcVal);
1272 else
1273 rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(castOp, llvmDstTy,
1274 llvmSrcVal);
1275 return mlir::success();
1276 }
1277 case cir::CastKind::bool_to_float: {
1278 mlir::Type dstTy = castOp.getType();
1279 mlir::Value llvmSrcVal = adaptor.getSrc();
1280 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1281 rewriter.replaceOpWithNewOp<mlir::LLVM::UIToFPOp>(castOp, llvmDstTy,
1282 llvmSrcVal);
1283 return mlir::success();
1284 }
1285 case cir::CastKind::int_to_float: {
1286 mlir::Type dstTy = castOp.getType();
1287 mlir::Value llvmSrcVal = adaptor.getSrc();
1288 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1289 if (mlir::cast<cir::IntType>(elementTypeIfVector(castOp.getSrc().getType()))
1290 .isSigned())
1291 rewriter.replaceOpWithNewOp<mlir::LLVM::SIToFPOp>(castOp, llvmDstTy,
1292 llvmSrcVal);
1293 else
1294 rewriter.replaceOpWithNewOp<mlir::LLVM::UIToFPOp>(castOp, llvmDstTy,
1295 llvmSrcVal);
1296 return mlir::success();
1297 }
1298 case cir::CastKind::float_to_int: {
1299 mlir::Type dstTy = castOp.getType();
1300 mlir::Value llvmSrcVal = adaptor.getSrc();
1301 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1302 if (mlir::cast<cir::IntType>(elementTypeIfVector(castOp.getType()))
1303 .isSigned())
1304 rewriter.replaceOpWithNewOp<mlir::LLVM::FPToSIOp>(castOp, llvmDstTy,
1305 llvmSrcVal);
1306 else
1307 rewriter.replaceOpWithNewOp<mlir::LLVM::FPToUIOp>(castOp, llvmDstTy,
1308 llvmSrcVal);
1309 return mlir::success();
1310 }
1311 case cir::CastKind::bitcast: {
1312 mlir::Type dstTy = castOp.getType();
1313 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1314
1315 assert(!MissingFeatures::cxxABI());
1316 assert(!MissingFeatures::dataMemberType());
1317
1318 mlir::Value llvmSrcVal = adaptor.getSrc();
1319 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(castOp, llvmDstTy,
1320 llvmSrcVal);
1321 return mlir::success();
1322 }
1323 case cir::CastKind::ptr_to_bool: {
1324 mlir::Value llvmSrcVal = adaptor.getSrc();
1325 mlir::Value zeroPtr = mlir::LLVM::ZeroOp::create(rewriter, castOp.getLoc(),
1326 llvmSrcVal.getType());
1327 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
1328 castOp, mlir::LLVM::ICmpPredicate::ne, llvmSrcVal, zeroPtr);
1329 break;
1330 }
1331 case cir::CastKind::address_space: {
1332 mlir::Type dstTy = castOp.getType();
1333 mlir::Value llvmSrcVal = adaptor.getSrc();
1334 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1335 rewriter.replaceOpWithNewOp<mlir::LLVM::AddrSpaceCastOp>(castOp, llvmDstTy,
1336 llvmSrcVal);
1337 break;
1338 }
1339 case cir::CastKind::member_ptr_to_bool:
1340 assert(!MissingFeatures::cxxABI());
1341 assert(!MissingFeatures::methodType());
1342 break;
1343 default: {
1344 return castOp.emitError("Unhandled cast kind: ")
1345 << castOp.getKindAttrName();
1346 }
1347 }
1348
1349 return mlir::success();
1350 }
1351
1352 static mlir::Value convertToIndexTy(mlir::ConversionPatternRewriter &rewriter,
1353 mlir::ModuleOp mod, mlir::Value index,
1354 mlir::Type baseTy, cir::IntType strideTy) {
1355 mlir::Operation *indexOp = index.getDefiningOp();
1356 if (!indexOp)
1357 return index;
1358
1359 auto indexType = mlir::cast<mlir::IntegerType>(index.getType());
1360 mlir::DataLayout llvmLayout(mod);
1361 std::optional<uint64_t> layoutWidth = llvmLayout.getTypeIndexBitwidth(baseTy);
1362
1363 // If there is no change in width, don't do anything.
1364 if (!layoutWidth || *layoutWidth == indexType.getWidth())
1365 return index;
1366
1367 // If the index comes from a subtraction, make sure the extension happens
1368 // before it. To achieve that, look at unary minus, which already got
1369 // lowered to "sub 0, x".
1370 auto sub = dyn_cast<mlir::LLVM::SubOp>(indexOp);
1371 bool rewriteSub = false;
1372 if (sub) {
1373 if (auto lhsConst =
1374 dyn_cast<mlir::LLVM::ConstantOp>(sub.getLhs().getDefiningOp())) {
1375 auto lhsConstInt = mlir::dyn_cast<mlir::IntegerAttr>(lhsConst.getValue());
1376 if (lhsConstInt && lhsConstInt.getValue() == 0) {
1377 index = sub.getRhs();
1378 rewriteSub = true;
1379 }
1380 }
1381 }
1382
1383 auto llvmDstType = rewriter.getIntegerType(*layoutWidth);
1384 bool isUnsigned = strideTy && strideTy.isUnsigned();
1385 index = getLLVMIntCast(rewriter, index, llvmDstType, isUnsigned,
1386 indexType.getWidth(), *layoutWidth);
1387
1388 if (rewriteSub) {
1389 index = mlir::LLVM::SubOp::create(
1390 rewriter, index.getLoc(),
1391 mlir::LLVM::ConstantOp::create(rewriter, index.getLoc(),
1392 index.getType(), 0),
1393 index);
1394 // TODO: ensure sub is trivially dead now.
1395 rewriter.eraseOp(sub);
1396 }
1397
1398 return index;
1399 }
1400
1401 mlir::LogicalResult CIRToLLVMPtrStrideOpLowering::matchAndRewrite(
1402 cir::PtrStrideOp ptrStrideOp, OpAdaptor adaptor,
1403 mlir::ConversionPatternRewriter &rewriter) const {
1404
1405 const mlir::TypeConverter *tc = getTypeConverter();
1406 const mlir::Type resultTy = tc->convertType(ptrStrideOp.getType());
1407
1408 mlir::Type elementTy =
1409 convertTypeForMemory(*tc, dataLayout, ptrStrideOp.getElementType());
1410
1411 // void and function types doesn't really have a layout to use in GEPs,
1412 // make it i8 instead.
1413 if (mlir::isa<mlir::LLVM::LLVMVoidType>(elementTy) ||
1414 mlir::isa<mlir::LLVM::LLVMFunctionType>(elementTy))
1415 elementTy = mlir::IntegerType::get(elementTy.getContext(), 8,
1416 mlir::IntegerType::Signless);
1417 // Zero-extend, sign-extend or trunc the pointer value.
1418 mlir::Value index = adaptor.getStride();
1419 index = convertToIndexTy(
1420 rewriter, ptrStrideOp->getParentOfType<mlir::ModuleOp>(), index,
1421 adaptor.getBase().getType(),
1422 dyn_cast<cir::IntType>(ptrStrideOp.getOperand(1).getType()));
1423
1424 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
1425 ptrStrideOp, resultTy, elementTy, adaptor.getBase(), index);
1426 return mlir::success();
1427 }
1428
1429 mlir::LogicalResult CIRToLLVMGetElementOpLowering::matchAndRewrite(
1430 cir::GetElementOp op, OpAdaptor adaptor,
1431 mlir::ConversionPatternRewriter &rewriter) const {
1432 if (auto arrayTy =
1433 mlir::dyn_cast<cir::ArrayType>(op.getBaseType().getPointee())) {
1434 const mlir::TypeConverter *converter = getTypeConverter();
1435 const mlir::Type llArrayTy = converter->convertType(arrayTy);
1436 const mlir::Type llResultTy = converter->convertType(op.getType());
1437 mlir::Type elementTy =
1438 convertTypeForMemory(*converter, dataLayout, op.getElementType());
1439
1440 // void and function types don't really have a layout to use in GEPs,
1441 // make it i8 instead.
1442 if (mlir::isa<mlir::LLVM::LLVMVoidType>(elementTy) ||
1443 mlir::isa<mlir::LLVM::LLVMFunctionType>(elementTy))
1444 elementTy = rewriter.getIntegerType(8);
1445
1446 mlir::Value index = adaptor.getIndex();
1447 index =
1448 convertToIndexTy(rewriter, op->getParentOfType<mlir::ModuleOp>(), index,
1449 adaptor.getBase().getType(),
1450 dyn_cast<cir::IntType>(op.getOperand(1).getType()));
1451
1452 // Since the base address is a pointer to an aggregate, the first
1453 // offset is always zero. The second offset tell us which member it
1454 // will access.
1455 std::array<mlir::LLVM::GEPArg, 2> offset{0, index};
1456 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(op, llResultTy, llArrayTy,
1457 adaptor.getBase(), offset);
1458 return mlir::success();
1459 }
1460
1461 op.emitError() << "NYI: GetElementOp lowering to LLVM for non-array";
1462 return mlir::failure();
1463 }
1464
1465 mlir::LogicalResult CIRToLLVMBaseClassAddrOpLowering::matchAndRewrite(
1466 cir::BaseClassAddrOp baseClassOp, OpAdaptor adaptor,
1467 mlir::ConversionPatternRewriter &rewriter) const {
1468 const mlir::Type resultType =
1469 getTypeConverter()->convertType(baseClassOp.getType());
1470 mlir::Value derivedAddr = adaptor.getDerivedAddr();
1471 llvm::SmallVector<mlir::LLVM::GEPArg, 1> offset = {
1472 adaptor.getOffset().getZExtValue()};
1473 mlir::Type byteType = mlir::IntegerType::get(resultType.getContext(), 8,
1474 mlir::IntegerType::Signless);
1475 if (adaptor.getOffset().getZExtValue() == 0) {
1476 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(
1477 baseClassOp, resultType, adaptor.getDerivedAddr());
1478 return mlir::success();
1479 }
1480
1481 if (baseClassOp.getAssumeNotNull()) {
1482 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
1483 baseClassOp, resultType, byteType, derivedAddr, offset);
1484 } else {
1485 auto loc = baseClassOp.getLoc();
1486 mlir::Value isNull = mlir::LLVM::ICmpOp::create(
1487 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, derivedAddr,
1488 mlir::LLVM::ZeroOp::create(rewriter, loc, derivedAddr.getType()));
1489 mlir::Value adjusted = mlir::LLVM::GEPOp::create(
1490 rewriter, loc, resultType, byteType, derivedAddr, offset);
1491 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(baseClassOp, isNull,
1492 derivedAddr, adjusted);
1493 }
1494 return mlir::success();
1495 }
1496
1497 mlir::LogicalResult CIRToLLVMDerivedClassAddrOpLowering::matchAndRewrite(
1498 cir::DerivedClassAddrOp derivedClassOp, OpAdaptor adaptor,
1499 mlir::ConversionPatternRewriter &rewriter) const {
1500 const mlir::Type resultType =
1501 getTypeConverter()->convertType(derivedClassOp.getType());
1502 mlir::Value baseAddr = adaptor.getBaseAddr();
1503 // The offset is set in the operation as an unsigned value, but it must be
1504 // applied as a negative offset.
1505 int64_t offsetVal = -(adaptor.getOffset().getZExtValue());
1506 if (offsetVal == 0) {
1507 // If the offset is zero, we can just return the base address,
1508 rewriter.replaceOp(derivedClassOp, baseAddr);
1509 return mlir::success();
1510 }
1511 llvm::SmallVector<mlir::LLVM::GEPArg, 1> offset = {offsetVal};
1512 mlir::Type byteType = mlir::IntegerType::get(resultType.getContext(), 8,
1513 mlir::IntegerType::Signless);
1514 if (derivedClassOp.getAssumeNotNull()) {
1515 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
1516 derivedClassOp, resultType, byteType, baseAddr, offset,
1517 mlir::LLVM::GEPNoWrapFlags::inbounds);
1518 } else {
1519 mlir::Location loc = derivedClassOp.getLoc();
1520 mlir::Value isNull = mlir::LLVM::ICmpOp::create(
1521 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, baseAddr,
1522 mlir::LLVM::ZeroOp::create(rewriter, loc, baseAddr.getType()));
1523 mlir::Value adjusted =
1524 mlir::LLVM::GEPOp::create(rewriter, loc, resultType, byteType, baseAddr,
1525 offset, mlir::LLVM::GEPNoWrapFlags::inbounds);
1526 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(derivedClassOp, isNull,
1527 baseAddr, adjusted);
1528 }
1529 return mlir::success();
1530 }
1531
1532 mlir::LogicalResult CIRToLLVMATanOpLowering::matchAndRewrite(
1533 cir::ATanOp op, OpAdaptor adaptor,
1534 mlir::ConversionPatternRewriter &rewriter) const {
1535 mlir::Type resTy = typeConverter->convertType(op.getType());
1536 rewriter.replaceOpWithNewOp<mlir::LLVM::ATanOp>(op, resTy, adaptor.getSrc());
1537 return mlir::success();
1538 }
1539
1540 mlir::LogicalResult CIRToLLVMCeilOpLowering::matchAndRewrite(
1541 cir::CeilOp op, OpAdaptor adaptor,
1542 mlir::ConversionPatternRewriter &rewriter) const {
1543 mlir::Type resTy = typeConverter->convertType(op.getType());
1544 rewriter.replaceOpWithNewOp<mlir::LLVM::FCeilOp>(op, resTy, adaptor.getSrc());
1545 return mlir::success();
1546 }
1547
1548 mlir::LogicalResult CIRToLLVMAllocaOpLowering::matchAndRewrite(
1549 cir::AllocaOp op, OpAdaptor adaptor,
1550 mlir::ConversionPatternRewriter &rewriter) const {
1551 mlir::Value size =
1552 op.isDynamic()
1553 ? adaptor.getDynAllocSize()
1554 : mlir::LLVM::ConstantOp::create(
1555 rewriter, op.getLoc(),
1556 typeConverter->convertType(rewriter.getIndexType()), 1);
1557 mlir::Type elementTy =
1558 convertTypeForMemory(*getTypeConverter(), dataLayout, op.getAllocaType());
1559 mlir::Type resultTy =
1560 convertTypeForMemory(*getTypeConverter(), dataLayout, op.getType());
1561
1562 assert(!cir::MissingFeatures::addressSpace());
1563 assert(!cir::MissingFeatures::opAllocaAnnotations());
1564
1565 rewriter.replaceOpWithNewOp<mlir::LLVM::AllocaOp>(
1566 op, resultTy, elementTy, size, op.getAlignmentAttr().getInt());
1567
1568 return mlir::success();
1569 }
1570
1571 mlir::LogicalResult CIRToLLVMReturnOpLowering::matchAndRewrite(
1572 cir::ReturnOp op, OpAdaptor adaptor,
1573 mlir::ConversionPatternRewriter &rewriter) const {
1574 rewriter.replaceOpWithNewOp<mlir::LLVM::ReturnOp>(op, adaptor.getOperands());
1575 return mlir::LogicalResult::success();
1576 }
1577
1578 mlir::LogicalResult CIRToLLVMRotateOpLowering::matchAndRewrite(
1579 cir::RotateOp op, OpAdaptor adaptor,
1580 mlir::ConversionPatternRewriter &rewriter) const {
1581 // Note that LLVM intrinsic calls to @llvm.fsh{r,l}.i* have the same type as
1582 // the operand.
1583 mlir::Value input = adaptor.getInput();
1584 if (op.isRotateLeft())
1585 rewriter.replaceOpWithNewOp<mlir::LLVM::FshlOp>(op, input, input,
1586 adaptor.getAmount());
1587 else
1588 rewriter.replaceOpWithNewOp<mlir::LLVM::FshrOp>(op, input, input,
1589 adaptor.getAmount());
1590 return mlir::LogicalResult::success();
1591 }
1592
1593 static mlir::LogicalResult
1594 rewriteCallOrInvoke(mlir::Operation *op, mlir::ValueRange callOperands,
1595 mlir::ConversionPatternRewriter &rewriter,
1596 const mlir::TypeConverter *converter,
1597 mlir::FlatSymbolRefAttr calleeAttr) {
1598 llvm::SmallVector<mlir::Type, 8> llvmResults;
1599 mlir::ValueTypeRange<mlir::ResultRange> cirResults = op->getResultTypes();
1600 auto call = cast<cir::CIRCallOpInterface>(op);
1601
1602 if (converter->convertTypes(cirResults, llvmResults).failed())
1603 return mlir::failure();
1604
1605 assert(!cir::MissingFeatures::opCallCallConv());
1606
1607 mlir::LLVM::MemoryEffectsAttr memoryEffects;
1608 bool noUnwind = false;
1609 bool willReturn = false;
1610 convertSideEffectForCall(op, call.getNothrow(), call.getSideEffect(),
1611 memoryEffects, noUnwind, willReturn);
1612
1613 mlir::LLVM::LLVMFunctionType llvmFnTy;
1614
1615 // Temporary to handle the case where we need to prepend an operand if the
1616 // callee is an alias.
1617 SmallVector<mlir::Value> adjustedCallOperands;
1618
1619 if (calleeAttr) { // direct call
1620 mlir::Operation *callee =
1621 mlir::SymbolTable::lookupNearestSymbolFrom(op, calleeAttr);
1622 if (auto fn = mlir::dyn_cast<mlir::FunctionOpInterface>(callee)) {
1623 llvmFnTy = converter->convertType<mlir::LLVM::LLVMFunctionType>(
1624 fn.getFunctionType());
1625 assert(llvmFnTy && "Failed to convert function type");
1626 } else if (auto alias = mlir::cast<mlir::LLVM::AliasOp>(callee)) {
1627 // If the callee was an alias. In that case,
1628 // we need to prepend the address of the alias to the operands. The
1629 // way aliases work in the LLVM dialect is a little counter-intuitive.
1630 // The AliasOp itself is a pseudo-function that returns the address of
1631 // the global value being aliased, but when we generate the call we
1632 // need to insert an operation that gets the address of the AliasOp.
1633 // This all gets sorted out when the LLVM dialect is lowered to LLVM IR.
1634 auto symAttr = mlir::cast<mlir::FlatSymbolRefAttr>(calleeAttr);
1635 auto addrOfAlias =
1636 mlir::LLVM::AddressOfOp::create(
1637 rewriter, op->getLoc(),
1638 mlir::LLVM::LLVMPointerType::get(rewriter.getContext()), symAttr)
1639 .getResult();
1640 adjustedCallOperands.push_back(addrOfAlias);
1641
1642 // Now add the regular operands and assign this to the range value.
1643 llvm::append_range(adjustedCallOperands, callOperands);
1644 callOperands = adjustedCallOperands;
1645
1646 // Clear the callee attribute because we're calling an alias.
1647 calleeAttr = {};
1648 llvmFnTy = mlir::cast<mlir::LLVM::LLVMFunctionType>(alias.getType());
1649 } else {
1650 // Was this an ifunc?
1651 return op->emitError("Unexpected callee type!");
1652 }
1653 } else { // indirect call
1654 assert(!op->getOperands().empty() &&
1655 "operands list must no be empty for the indirect call");
1656 auto calleeTy = op->getOperands().front().getType();
1657 auto calleePtrTy = cast<cir::PointerType>(calleeTy);
1658 auto calleeFuncTy = cast<cir::FuncType>(calleePtrTy.getPointee());
1659 llvm::append_range(adjustedCallOperands, callOperands);
1660 llvmFnTy = cast<mlir::LLVM::LLVMFunctionType>(
1661 converter->convertType(calleeFuncTy));
1662 }
1663
1664 assert(!cir::MissingFeatures::opCallLandingPad());
1665 assert(!cir::MissingFeatures::opCallContinueBlock());
1666 assert(!cir::MissingFeatures::opCallCallConv());
1667
1668 auto newOp = rewriter.replaceOpWithNewOp<mlir::LLVM::CallOp>(
1669 op, llvmFnTy, calleeAttr, callOperands);
1670 if (memoryEffects)
1671 newOp.setMemoryEffectsAttr(memoryEffects);
1672 newOp.setNoUnwind(noUnwind);
1673 newOp.setWillReturn(willReturn);
1674
1675 return mlir::success();
1676 }
1677
1678 mlir::LogicalResult CIRToLLVMCallOpLowering::matchAndRewrite(
1679 cir::CallOp op, OpAdaptor adaptor,
1680 mlir::ConversionPatternRewriter &rewriter) const {
1681 return rewriteCallOrInvoke(op.getOperation(), adaptor.getOperands(), rewriter,
1682 getTypeConverter(), op.getCalleeAttr());
1683 }
1684
1685 mlir::LogicalResult CIRToLLVMReturnAddrOpLowering::matchAndRewrite(
1686 cir::ReturnAddrOp op, OpAdaptor adaptor,
1687 mlir::ConversionPatternRewriter &rewriter) const {
1688 const mlir::Type llvmPtrTy = getTypeConverter()->convertType(op.getType());
1689 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.returnaddress",
1690 llvmPtrTy, adaptor.getOperands());
1691 return mlir::success();
1692 }
1693
1694 mlir::LogicalResult CIRToLLVMFrameAddrOpLowering::matchAndRewrite(
1695 cir::FrameAddrOp op, OpAdaptor adaptor,
1696 mlir::ConversionPatternRewriter &rewriter) const {
1697 const mlir::Type llvmPtrTy = getTypeConverter()->convertType(op.getType());
1698 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.frameaddress", llvmPtrTy,
1699 adaptor.getOperands());
1700 return mlir::success();
1701 }
1702
1703 mlir::LogicalResult CIRToLLVMAddrOfReturnAddrOpLowering::matchAndRewrite(
1704 cir::AddrOfReturnAddrOp op, OpAdaptor adaptor,
1705 mlir::ConversionPatternRewriter &rewriter) const {
1706 const mlir::Type llvmPtrTy = getTypeConverter()->convertType(op.getType());
1707 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.addressofreturnaddress",
1708 llvmPtrTy, adaptor.getOperands());
1709 return mlir::success();
1710 }
1711
1712 mlir::LogicalResult CIRToLLVMLoadOpLowering::matchAndRewrite(
1713 cir::LoadOp op, OpAdaptor adaptor,
1714 mlir::ConversionPatternRewriter &rewriter) const {
1715 const mlir::Type llvmTy =
1716 convertTypeForMemory(*getTypeConverter(), dataLayout, op.getType());
1717 mlir::LLVM::AtomicOrdering ordering = getLLVMMemOrder(op.getMemOrder());
1718 std::optional<size_t> opAlign = op.getAlignment();
1719 unsigned alignment =
1720 (unsigned)opAlign.value_or(dataLayout.getTypeABIAlignment(llvmTy));
1721
1722 assert(!cir::MissingFeatures::lowerModeOptLevel());
1723
1724 // TODO: nontemporal.
1725 assert(!cir::MissingFeatures::opLoadStoreNontemporal());
1726 std::optional<llvm::StringRef> syncScope =
1727 getLLVMSyncScope(op.getSyncScope());
1728 mlir::LLVM::LoadOp newLoad = mlir::LLVM::LoadOp::create(
1729 rewriter, op->getLoc(), llvmTy, adaptor.getAddr(), alignment,
1730 op.getIsVolatile(), /*isNonTemporal=*/false,
1731 /*isInvariant=*/false, /*isInvariantGroup=*/false, ordering,
1732 syncScope.value_or(llvm::StringRef()));
1733
1734 // Convert adapted result to its original type if needed.
1735 mlir::Value result =
1736 emitFromMemory(rewriter, dataLayout, op, newLoad.getResult());
1737 rewriter.replaceOp(op, result);
1738 assert(!cir::MissingFeatures::opLoadStoreTbaa());
1739 return mlir::LogicalResult::success();
1740 }
1741
1742 mlir::LogicalResult CIRToLLVMStoreOpLowering::matchAndRewrite(
1743 cir::StoreOp op, OpAdaptor adaptor,
1744 mlir::ConversionPatternRewriter &rewriter) const {
1745 mlir::LLVM::AtomicOrdering memorder = getLLVMMemOrder(op.getMemOrder());
1746 const mlir::Type llvmTy =
1747 getTypeConverter()->convertType(op.getValue().getType());
1748 std::optional<size_t> opAlign = op.getAlignment();
1749 unsigned alignment =
1750 (unsigned)opAlign.value_or(dataLayout.getTypeABIAlignment(llvmTy));
1751
1752 assert(!cir::MissingFeatures::lowerModeOptLevel());
1753
1754 // Convert adapted value to its memory type if needed.
1755 mlir::Value value = emitToMemory(rewriter, dataLayout,
1756 op.getValue().getType(), adaptor.getValue());
1757 // TODO: nontemporal.
1758 assert(!cir::MissingFeatures::opLoadStoreNontemporal());
1759 assert(!cir::MissingFeatures::opLoadStoreTbaa());
1760 std::optional<llvm::StringRef> syncScope =
1761 getLLVMSyncScope(op.getSyncScope());
1762 mlir::LLVM::StoreOp storeOp = mlir::LLVM::StoreOp::create(
1763 rewriter, op->getLoc(), value, adaptor.getAddr(), alignment,
1764 op.getIsVolatile(),
1765 /*isNonTemporal=*/false, /*isInvariantGroup=*/false, memorder,
1766 syncScope.value_or(llvm::StringRef()));
1767 rewriter.replaceOp(op, storeOp);
1768 assert(!cir::MissingFeatures::opLoadStoreTbaa());
1769 return mlir::LogicalResult::success();
1770 }
1771
1772 bool hasTrailingZeros(cir::ConstArrayAttr attr) {
1773 auto array = mlir::dyn_cast<mlir::ArrayAttr>(attr.getElts());
1774 return attr.hasTrailingZeros() ||
1775 (array && std::count_if(array.begin(), array.end(), [](auto elt) {
1776 auto ar = dyn_cast<cir::ConstArrayAttr>(elt);
1777 return ar && hasTrailingZeros(ar);
1778 }));
1779 }
1780
1781 mlir::LogicalResult CIRToLLVMConstantOpLowering::matchAndRewrite(
1782 cir::ConstantOp op, OpAdaptor adaptor,
1783 mlir::ConversionPatternRewriter &rewriter) const {
1784 mlir::Attribute attr = op.getValue();
1785
1786 if (mlir::isa<cir::PoisonAttr>(attr)) {
1787 rewriter.replaceOpWithNewOp<mlir::LLVM::PoisonOp>(
1788 op, getTypeConverter()->convertType(op.getType()));
1789 return mlir::success();
1790 }
1791
1792 if (mlir::isa<mlir::IntegerType>(op.getType())) {
1793 // Verified cir.const operations cannot actually be of these types, but the
1794 // lowering pass may generate temporary cir.const operations with these
1795 // types. This is OK since MLIR allows unverified operations to be alive
1796 // during a pass as long as they don't live past the end of the pass.
1797 attr = op.getValue();
1798 } else if (mlir::isa<cir::BoolType>(op.getType())) {
1799 int value = mlir::cast<cir::BoolAttr>(op.getValue()).getValue();
1800 attr = rewriter.getIntegerAttr(typeConverter->convertType(op.getType()),
1801 value);
1802 } else if (mlir::isa<cir::IntType>(op.getType())) {
1803 // Lower GlobalViewAttr to llvm.mlir.addressof + llvm.mlir.ptrtoint
1804 if (auto ga = mlir::dyn_cast<cir::GlobalViewAttr>(op.getValue())) {
1805 // See the comment in visitCirAttr for why this isn't implemented.
1806 assert(!cir::MissingFeatures::globalViewIntLowering());
1807 op.emitError() << "global view with integer type";
1808 return mlir::failure();
1809 }
1810
1811 attr = rewriter.getIntegerAttr(
1812 typeConverter->convertType(op.getType()),
1813 mlir::cast<cir::IntAttr>(op.getValue()).getValue());
1814 } else if (mlir::isa<cir::FPTypeInterface>(op.getType())) {
1815 attr = rewriter.getFloatAttr(
1816 typeConverter->convertType(op.getType()),
1817 mlir::cast<cir::FPAttr>(op.getValue()).getValue());
1818 } else if (mlir::isa<cir::PointerType>(op.getType())) {
1819 // Optimize with dedicated LLVM op for null pointers.
1820 if (mlir::isa<cir::ConstPtrAttr>(op.getValue())) {
1821 if (mlir::cast<cir::ConstPtrAttr>(op.getValue()).isNullValue()) {
1822 rewriter.replaceOpWithNewOp<mlir::LLVM::ZeroOp>(
1823 op, typeConverter->convertType(op.getType()));
1824 return mlir::success();
1825 }
1826 }
1827 // Lower GlobalViewAttr to llvm.mlir.addressof
1828 if (auto gv = mlir::dyn_cast<cir::GlobalViewAttr>(op.getValue())) {
1829 auto newOp =
1830 lowerCirAttrAsValue(op, gv, rewriter, getTypeConverter(), lowerMod);
1831 rewriter.replaceOp(op, newOp);
1832 return mlir::success();
1833 }
1834 attr = op.getValue();
1835 } else if (const auto arrTy = mlir::dyn_cast<cir::ArrayType>(op.getType())) {
1836 const auto constArr = mlir::dyn_cast<cir::ConstArrayAttr>(op.getValue());
1837 if (!constArr && !isa<cir::ZeroAttr, cir::UndefAttr>(op.getValue()))
1838 return op.emitError() << "array does not have a constant initializer";
1839
1840 std::optional<mlir::Attribute> denseAttr;
1841 if (constArr && hasTrailingZeros(constArr)) {
1842 const mlir::Value newOp = lowerCirAttrAsValue(
1843 op, constArr, rewriter, getTypeConverter(), lowerMod);
1844 rewriter.replaceOp(op, newOp);
1845 return mlir::success();
1846 } else if (constArr &&
1847 (denseAttr = lowerConstArrayAttr(constArr, typeConverter))) {
1848 attr = denseAttr.value();
1849 } else {
1850 const mlir::Value initVal = lowerCirAttrAsValue(
1851 op, op.getValue(), rewriter, typeConverter, lowerMod);
1852 rewriter.replaceOp(op, initVal);
1853 return mlir::success();
1854 }
1855 } else if (const auto recordAttr =
1856 mlir::dyn_cast<cir::ConstRecordAttr>(op.getValue())) {
1857 auto initVal =
1858 lowerCirAttrAsValue(op, recordAttr, rewriter, typeConverter, lowerMod);
1859 rewriter.replaceOp(op, initVal);
1860 return mlir::success();
1861 } else if (const auto vecTy = mlir::dyn_cast<cir::VectorType>(op.getType())) {
1862 rewriter.replaceOp(op, lowerCirAttrAsValue(op, op.getValue(), rewriter,
1863 getTypeConverter(), lowerMod));
1864 return mlir::success();
1865 } else if (auto recTy = mlir::dyn_cast<cir::RecordType>(op.getType())) {
1866 if (mlir::isa<cir::ZeroAttr, cir::UndefAttr>(attr)) {
1867 mlir::Value initVal =
1868 lowerCirAttrAsValue(op, attr, rewriter, typeConverter, lowerMod);
1869 rewriter.replaceOp(op, initVal);
1870 return mlir::success();
1871 }
1872 return op.emitError() << "unsupported lowering for record constant type "
1873 << op.getType();
1874 } else if (auto complexTy = mlir::dyn_cast<cir::ComplexType>(op.getType())) {
1875 mlir::Type complexElemTy = complexTy.getElementType();
1876 mlir::Type complexElemLLVMTy = typeConverter->convertType(complexElemTy);
1877
1878 if (auto zeroInitAttr = mlir::dyn_cast<cir::ZeroAttr>(op.getValue())) {
1879 mlir::TypedAttr zeroAttr = rewriter.getZeroAttr(complexElemLLVMTy);
1880 mlir::ArrayAttr array = rewriter.getArrayAttr({zeroAttr, zeroAttr});
1881 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
1882 op, getTypeConverter()->convertType(op.getType()), array);
1883 return mlir::success();
1884 }
1885
1886 auto complexAttr = mlir::cast<cir::ConstComplexAttr>(op.getValue());
1887
1888 mlir::Attribute components[2];
1889 if (mlir::isa<cir::IntType>(complexElemTy)) {
1890 components[0] = rewriter.getIntegerAttr(
1891 complexElemLLVMTy,
1892 mlir::cast<cir::IntAttr>(complexAttr.getReal()).getValue());
1893 components[1] = rewriter.getIntegerAttr(
1894 complexElemLLVMTy,
1895 mlir::cast<cir::IntAttr>(complexAttr.getImag()).getValue());
1896 } else {
1897 components[0] = rewriter.getFloatAttr(
1898 complexElemLLVMTy,
1899 mlir::cast<cir::FPAttr>(complexAttr.getReal()).getValue());
1900 components[1] = rewriter.getFloatAttr(
1901 complexElemLLVMTy,
1902 mlir::cast<cir::FPAttr>(complexAttr.getImag()).getValue());
1903 }
1904
1905 attr = rewriter.getArrayAttr(components);
1906 } else {
1907 return op.emitError() << "unsupported constant type " << op.getType();
1908 }
1909
1910 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
1911 op, getTypeConverter()->convertType(op.getType()), attr);
1912
1913 return mlir::success();
1914 }
1915
1916 static uint64_t getTypeSize(mlir::Type type, mlir::Operation &op) {
1917 mlir::DataLayout layout(op.getParentOfType<mlir::ModuleOp>());
1918 // For LLVM purposes we treat void as u8.
1919 if (isa<cir::VoidType>(type))
1920 type = cir::IntType::get(type.getContext(), 8, /*isSigned=*/false);
1921 return llvm::divideCeil(layout.getTypeSizeInBits(type), 8);
1922 }
1923
1924 mlir::LogicalResult CIRToLLVMPrefetchOpLowering::matchAndRewrite(
1925 cir::PrefetchOp op, OpAdaptor adaptor,
1926 mlir::ConversionPatternRewriter &rewriter) const {
1927 rewriter.replaceOpWithNewOp<mlir::LLVM::Prefetch>(
1928 op, adaptor.getAddr(), adaptor.getIsWrite(), adaptor.getLocality(),
1929 /*DataCache=*/1);
1930 return mlir::success();
1931 }
1932
1933 mlir::LogicalResult CIRToLLVMPtrDiffOpLowering::matchAndRewrite(
1934 cir::PtrDiffOp op, OpAdaptor adaptor,
1935 mlir::ConversionPatternRewriter &rewriter) const {
1936 auto dstTy = mlir::cast<cir::IntType>(op.getType());
1937 mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
1938
1939 auto lhs = mlir::LLVM::PtrToIntOp::create(rewriter, op.getLoc(), llvmDstTy,
1940 adaptor.getLhs());
1941 auto rhs = mlir::LLVM::PtrToIntOp::create(rewriter, op.getLoc(), llvmDstTy,
1942 adaptor.getRhs());
1943
1944 auto diff =
1945 mlir::LLVM::SubOp::create(rewriter, op.getLoc(), llvmDstTy, lhs, rhs);
1946
1947 cir::PointerType ptrTy = op.getLhs().getType();
1948 assert(!cir::MissingFeatures::llvmLoweringPtrDiffConsidersPointee());
1949 uint64_t typeSize = getTypeSize(ptrTy.getPointee(), *op);
1950
1951 // Avoid silly division by 1.
1952 mlir::Value resultVal = diff.getResult();
1953 if (typeSize != 1) {
1954 auto typeSizeVal = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
1955 llvmDstTy, typeSize);
1956
1957 if (dstTy.isUnsigned()) {
1958 auto uDiv =
1959 mlir::LLVM::UDivOp::create(rewriter, op.getLoc(), diff, typeSizeVal);
1960 uDiv.setIsExact(true);
1961 resultVal = uDiv.getResult();
1962 } else {
1963 auto sDiv =
1964 mlir::LLVM::SDivOp::create(rewriter, op.getLoc(), diff, typeSizeVal);
1965 sDiv.setIsExact(true);
1966 resultVal = sDiv.getResult();
1967 }
1968 }
1969 rewriter.replaceOp(op, resultVal);
1970 return mlir::success();
1971 }
1972
1973 mlir::LogicalResult CIRToLLVMExpectOpLowering::matchAndRewrite(
1974 cir::ExpectOp op, OpAdaptor adaptor,
1975 mlir::ConversionPatternRewriter &rewriter) const {
1976 // TODO(cir): do not generate LLVM intrinsics under -O0
1977 assert(!cir::MissingFeatures::optInfoAttr());
1978
1979 std::optional<llvm::APFloat> prob = op.getProb();
1980 if (prob)
1981 rewriter.replaceOpWithNewOp<mlir::LLVM::ExpectWithProbabilityOp>(
1982 op, adaptor.getVal(), adaptor.getExpected(), prob.value());
1983 else
1984 rewriter.replaceOpWithNewOp<mlir::LLVM::ExpectOp>(op, adaptor.getVal(),
1985 adaptor.getExpected());
1986 return mlir::success();
1987 }
1988
1989 mlir::LogicalResult CIRToLLVMFAbsOpLowering::matchAndRewrite(
1990 cir::FAbsOp op, OpAdaptor adaptor,
1991 mlir::ConversionPatternRewriter &rewriter) const {
1992 mlir::Type resTy = typeConverter->convertType(op.getType());
1993 rewriter.replaceOpWithNewOp<mlir::LLVM::FAbsOp>(op, resTy,
1994 adaptor.getOperands()[0]);
1995 return mlir::success();
1996 }
1997
1998 /// Convert the `cir.func` attributes to `llvm.func` attributes.
1999 /// Only retain those attributes that are not constructed by
2000 /// `LLVMFuncOp::build`. If `filterArgAttrs` is set, also filter out
2001 /// argument attributes.
2002 void CIRToLLVMFuncOpLowering::lowerFuncAttributes(
2003 cir::FuncOp func, bool filterArgAndResAttrs,
2004 SmallVectorImpl<mlir::NamedAttribute> &result) const {
2005 assert(!cir::MissingFeatures::opFuncCallingConv());
2006 for (mlir::NamedAttribute attr : func->getAttrs()) {
2007 assert(!cir::MissingFeatures::opFuncCallingConv());
2008 if (attr.getName() == mlir::SymbolTable::getSymbolAttrName() ||
2009 attr.getName() == func.getFunctionTypeAttrName() ||
2010 attr.getName() == getLinkageAttrNameString() ||
2011 attr.getName() == func.getGlobalVisibilityAttrName() ||
2012 attr.getName() == func.getDsoLocalAttrName() ||
2013 attr.getName() == func.getInlineKindAttrName() ||
2014 (filterArgAndResAttrs &&
2015 (attr.getName() == func.getArgAttrsAttrName() ||
2016 attr.getName() == func.getResAttrsAttrName())))
2017 continue;
2018
2019 assert(!cir::MissingFeatures::opFuncExtraAttrs());
2020 result.push_back(attr);
2021 }
2022 }
2023
2024 mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewriteAlias(
2025 cir::FuncOp op, llvm::StringRef aliasee, mlir::Type ty, OpAdaptor adaptor,
2026 mlir::ConversionPatternRewriter &rewriter) const {
2027 SmallVector<mlir::NamedAttribute, 4> attributes;
2028 lowerFuncAttributes(op, /*filterArgAndResAttrs=*/false, attributes);
2029
2030 mlir::Location loc = op.getLoc();
2031 auto aliasOp = rewriter.replaceOpWithNewOp<mlir::LLVM::AliasOp>(
2032 op, ty, convertLinkage(op.getLinkage()), op.getName(), op.getDsoLocal(),
2033 /*threadLocal=*/false, attributes);
2034
2035 // Create the alias body
2036 mlir::OpBuilder builder(op.getContext());
2037 mlir::Block *block = builder.createBlock(&aliasOp.getInitializerRegion());
2038 builder.setInsertionPointToStart(block);
2039 // The type of AddressOfOp is always a pointer.
2040 assert(!cir::MissingFeatures::addressSpace());
2041 mlir::Type ptrTy = mlir::LLVM::LLVMPointerType::get(ty.getContext());
2042 auto addrOp = mlir::LLVM::AddressOfOp::create(builder, loc, ptrTy, aliasee);
2043 mlir::LLVM::ReturnOp::create(builder, loc, addrOp);
2044
2045 return mlir::success();
2046 }
2047
2048 mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewrite(
2049 cir::FuncOp op, OpAdaptor adaptor,
2050 mlir::ConversionPatternRewriter &rewriter) const {
2051
2052 cir::FuncType fnType = op.getFunctionType();
2053 bool isDsoLocal = op.getDsoLocal();
2054 mlir::TypeConverter::SignatureConversion signatureConversion(
2055 fnType.getNumInputs());
2056
2057 for (const auto &argType : llvm::enumerate(fnType.getInputs())) {
2058 mlir::Type convertedType = typeConverter->convertType(argType.value());
2059 if (!convertedType)
2060 return mlir::failure();
2061 signatureConversion.addInputs(argType.index(), convertedType);
2062 }
2063
2064 mlir::Type resultType =
2065 getTypeConverter()->convertType(fnType.getReturnType());
2066
2067 // Create the LLVM function operation.
2068 mlir::Type llvmFnTy = mlir::LLVM::LLVMFunctionType::get(
2069 resultType ? resultType : mlir::LLVM::LLVMVoidType::get(getContext()),
2070 signatureConversion.getConvertedTypes(),
2071 /*isVarArg=*/fnType.isVarArg());
2072
2073 // If this is an alias, it needs to be lowered to llvm::AliasOp.
2074 if (std::optional<llvm::StringRef> aliasee = op.getAliasee())
2075 return matchAndRewriteAlias(op, *aliasee, llvmFnTy, adaptor, rewriter);
2076
2077 // LLVMFuncOp expects a single FileLine Location instead of a fused
2078 // location.
2079 mlir::Location loc = op.getLoc();
2080 if (mlir::FusedLoc fusedLoc = mlir::dyn_cast<mlir::FusedLoc>(loc))
2081 loc = fusedLoc.getLocations()[0];
2082 assert((mlir::isa<mlir::FileLineColLoc>(loc) ||
2083 mlir::isa<mlir::UnknownLoc>(loc)) &&
2084 "expected single location or unknown location here");
2085
2086 mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
2087 assert(!cir::MissingFeatures::opFuncCallingConv());
2088 mlir::LLVM::CConv cconv = mlir::LLVM::CConv::C;
2089 SmallVector<mlir::NamedAttribute, 4> attributes;
2090 lowerFuncAttributes(op, /*filterArgAndResAttrs=*/false, attributes);
2091
2092 mlir::LLVM::LLVMFuncOp fn = mlir::LLVM::LLVMFuncOp::create(
2093 rewriter, loc, op.getName(), llvmFnTy, linkage, isDsoLocal, cconv,
2094 mlir::SymbolRefAttr(), attributes);
2095
2096 assert(!cir::MissingFeatures::opFuncMultipleReturnVals());
2097
2098 if (std::optional<cir::InlineKind> inlineKind = op.getInlineKind()) {
2099 fn.setNoInline(*inlineKind == cir::InlineKind::NoInline);
2100 fn.setInlineHint(*inlineKind == cir::InlineKind::InlineHint);
2101 fn.setAlwaysInline(*inlineKind == cir::InlineKind::AlwaysInline);
2102 }
2103
2104 if (std::optional<llvm::StringRef> personality = op.getPersonality())
2105 fn.setPersonality(*personality);
2106
2107 fn.setVisibility_(
2108 lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
2109
2110 rewriter.inlineRegionBefore(op.getBody(), fn.getBody(), fn.end());
2111 if (failed(rewriter.convertRegionTypes(&fn.getBody(), *typeConverter,
2112 &signatureConversion)))
2113 return mlir::failure();
2114
2115 rewriter.eraseOp(op);
2116
2117 return mlir::LogicalResult::success();
2118 }
2119
2120 mlir::LogicalResult CIRToLLVMGetGlobalOpLowering::matchAndRewrite(
2121 cir::GetGlobalOp op, OpAdaptor adaptor,
2122 mlir::ConversionPatternRewriter &rewriter) const {
2123 // FIXME(cir): Premature DCE to avoid lowering stuff we're not using.
2124 // CIRGen should mitigate this and not emit the get_global.
2125 if (op->getUses().empty()) {
2126 rewriter.eraseOp(op);
2127 return mlir::success();
2128 }
2129
2130 mlir::Type type = getTypeConverter()->convertType(op.getType());
2131 mlir::Operation *newop = mlir::LLVM::AddressOfOp::create(
2132 rewriter, op.getLoc(), type, op.getName());
2133
2134 if (op.getTls()) {
2135 // Handle access to TLS via intrinsic.
2136 newop = mlir::LLVM::ThreadlocalAddressOp::create(rewriter, op.getLoc(),
2137 type, newop->getResult(0));
2138 }
2139
2140 rewriter.replaceOp(op, newop);
2141 return mlir::success();
2142 }
2143
2144 /// Replace CIR global with a region initialized LLVM global and update
2145 /// insertion point to the end of the initializer block.
2146 void CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
2147 cir::GlobalOp op, mlir::ConversionPatternRewriter &rewriter) const {
2148 const mlir::Type llvmType =
2149 convertTypeForMemory(*getTypeConverter(), dataLayout, op.getSymType());
2150
2151 // FIXME: These default values are placeholders until the the equivalent
2152 // attributes are available on cir.global ops. This duplicates code
2153 // in CIRToLLVMGlobalOpLowering::matchAndRewrite() but that will go
2154 // away when the placeholders are no longer needed.
2155 const bool isConst = op.getConstant();
2156 assert(!cir::MissingFeatures::addressSpace());
2157 const unsigned addrSpace = 0;
2158 const bool isDsoLocal = op.getDsoLocal();
2159 const bool isThreadLocal = (bool)op.getTlsModelAttr();
2160 const uint64_t alignment = op.getAlignment().value_or(0);
2161 const mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
2162 const StringRef symbol = op.getSymName();
2163 mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
2164
2165 SmallVector<mlir::NamedAttribute> attributes;
2166 mlir::LLVM::GlobalOp newGlobalOp =
2167 rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
2168 op, llvmType, isConst, linkage, symbol, nullptr, alignment, addrSpace,
2169 isDsoLocal, isThreadLocal, comdatAttr, attributes);
2170 newGlobalOp.getRegion().emplaceBlock();
2171 rewriter.setInsertionPointToEnd(newGlobalOp.getInitializerBlock());
2172 }
2173
2174 mlir::LogicalResult
2175 CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
2176 cir::GlobalOp op, mlir::Attribute init,
2177 mlir::ConversionPatternRewriter &rewriter) const {
2178 // TODO: Generalize this handling when more types are needed here.
2179 assert(
2180 (isa<cir::ConstArrayAttr, cir::ConstRecordAttr, cir::ConstVectorAttr,
2181 cir::ConstPtrAttr, cir::ConstComplexAttr, cir::GlobalViewAttr,
2182 cir::TypeInfoAttr, cir::UndefAttr, cir::VTableAttr, cir::ZeroAttr>(
2183 init)));
2184
2185 // TODO(cir): once LLVM's dialect has proper equivalent attributes this
2186 // should be updated. For now, we use a custom op to initialize globals
2187 // to the appropriate value.
2188 const mlir::Location loc = op.getLoc();
2189 setupRegionInitializedLLVMGlobalOp(op, rewriter);
2190 CIRAttrToValue valueConverter(op, rewriter, typeConverter, lowerMod);
2191 mlir::Value value = valueConverter.visit(init);
2192 mlir::LLVM::ReturnOp::create(rewriter, loc, value);
2193 return mlir::success();
2194 }
2195
2196 mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
2197 cir::GlobalOp op, OpAdaptor adaptor,
2198 mlir::ConversionPatternRewriter &rewriter) const {
2199 // If this global requires non-trivial initialization or destruction,
2200 // that needs to be moved to runtime handlers during LoweringPrepare.
2201 if (!op.getCtorRegion().empty() || !op.getDtorRegion().empty())
2202 return op.emitError() << "GlobalOp ctor and dtor regions should be removed "
2203 "in LoweringPrepare";
2204
2205 std::optional<mlir::Attribute> init = op.getInitialValue();
2206
2207 // Fetch required values to create LLVM op.
2208 const mlir::Type cirSymType = op.getSymType();
2209
2210 // This is the LLVM dialect type.
2211 const mlir::Type llvmType =
2212 convertTypeForMemory(*getTypeConverter(), dataLayout, cirSymType);
2213 // FIXME: These default values are placeholders until the the equivalent
2214 // attributes are available on cir.global ops.
2215 const bool isConst = op.getConstant();
2216 assert(!cir::MissingFeatures::addressSpace());
2217 const unsigned addrSpace = 0;
2218 const bool isDsoLocal = op.getDsoLocal();
2219 const bool isThreadLocal = (bool)op.getTlsModelAttr();
2220 const uint64_t alignment = op.getAlignment().value_or(0);
2221 const mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
2222 const StringRef symbol = op.getSymName();
2223 SmallVector<mlir::NamedAttribute> attributes;
2224
2225 if (init.has_value()) {
2226 if (mlir::isa<cir::FPAttr, cir::IntAttr, cir::BoolAttr>(init.value())) {
2227 GlobalInitAttrRewriter initRewriter(llvmType, rewriter);
2228 init = initRewriter.visit(init.value());
2229 // If initRewriter returned a null attribute, init will have a value but
2230 // the value will be null. If that happens, initRewriter didn't handle the
2231 // attribute type. It probably needs to be added to
2232 // GlobalInitAttrRewriter.
2233 if (!init.value()) {
2234 op.emitError() << "unsupported initializer '" << init.value() << "'";
2235 return mlir::failure();
2236 }
2237 } else if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
2238 cir::ConstRecordAttr, cir::ConstPtrAttr,
2239 cir::ConstComplexAttr, cir::GlobalViewAttr,
2240 cir::TypeInfoAttr, cir::UndefAttr, cir::VTableAttr,
2241 cir::ZeroAttr>(init.value())) {
2242 // TODO(cir): once LLVM's dialect has proper equivalent attributes this
2243 // should be updated. For now, we use a custom op to initialize globals
2244 // to the appropriate value.
2245 return matchAndRewriteRegionInitializedGlobal(op, init.value(), rewriter);
2246 } else {
2247 // We will only get here if new initializer types are added and this
2248 // code is not updated to handle them.
2249 op.emitError() << "unsupported initializer '" << init.value() << "'";
2250 return mlir::failure();
2251 }
2252 }
2253
2254 mlir::LLVM::Visibility visibility =
2255 lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility());
2256 mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
2257 auto newOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
2258 op, llvmType, isConst, linkage, symbol, init.value_or(mlir::Attribute()),
2259 alignment, addrSpace, isDsoLocal, isThreadLocal, comdatAttr, attributes);
2260 newOp.setVisibility_(visibility);
2261
2262 return mlir::success();
2263 }
2264
2265 mlir::SymbolRefAttr
2266 CIRToLLVMGlobalOpLowering::getComdatAttr(cir::GlobalOp &op,
2267 mlir::OpBuilder &builder) const {
2268 if (!op.getComdat())
2269 return mlir::SymbolRefAttr{};
2270
2271 mlir::ModuleOp module = op->getParentOfType<mlir::ModuleOp>();
2272 mlir::OpBuilder::InsertionGuard guard(builder);
2273 StringRef comdatName("__llvm_comdat_globals");
2274 if (!comdatOp) {
2275 builder.setInsertionPointToStart(module.getBody());
2276 comdatOp =
2277 mlir::LLVM::ComdatOp::create(builder, module.getLoc(), comdatName);
2278 }
2279
2280 if (auto comdatSelector = comdatOp.lookupSymbol<mlir::LLVM::ComdatSelectorOp>(
2281 op.getSymName())) {
2282 return mlir::SymbolRefAttr::get(
2283 builder.getContext(), comdatName,
2284 mlir::FlatSymbolRefAttr::get(comdatSelector.getSymNameAttr()));
2285 }
2286
2287 builder.setInsertionPointToStart(&comdatOp.getBody().back());
2288 auto selectorOp = mlir::LLVM::ComdatSelectorOp::create(
2289 builder, comdatOp.getLoc(), op.getSymName(),
2290 mlir::LLVM::comdat::Comdat::Any);
2291 return mlir::SymbolRefAttr::get(
2292 builder.getContext(), comdatName,
2293 mlir::FlatSymbolRefAttr::get(selectorOp.getSymNameAttr()));
2294 }
2295
2296 mlir::LogicalResult CIRToLLVMSwitchFlatOpLowering::matchAndRewrite(
2297 cir::SwitchFlatOp op, OpAdaptor adaptor,
2298 mlir::ConversionPatternRewriter &rewriter) const {
2299
2300 llvm::SmallVector<mlir::APInt, 8> caseValues;
2301 for (mlir::Attribute val : op.getCaseValues()) {
2302 auto intAttr = cast<cir::IntAttr>(val);
2303 caseValues.push_back(intAttr.getValue());
2304 }
2305
2306 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
2307 llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
2308
2309 for (mlir::Block *x : op.getCaseDestinations())
2310 caseDestinations.push_back(x);
2311
2312 for (mlir::OperandRange x : op.getCaseOperands())
2313 caseOperands.push_back(x);
2314
2315 // Set switch op to branch to the newly created blocks.
2316 rewriter.setInsertionPoint(op);
2317 rewriter.replaceOpWithNewOp<mlir::LLVM::SwitchOp>(
2318 op, adaptor.getCondition(), op.getDefaultDestination(),
2319 op.getDefaultOperands(), caseValues, caseDestinations, caseOperands);
2320 return mlir::success();
2321 }
2322
2323 mlir::LogicalResult CIRToLLVMUnaryOpLowering::matchAndRewrite(
2324 cir::UnaryOp op, OpAdaptor adaptor,
2325 mlir::ConversionPatternRewriter &rewriter) const {
2326 assert(op.getType() == op.getInput().getType() &&
2327 "Unary operation's operand type and result type are different");
2328 mlir::Type type = op.getType();
2329 mlir::Type elementType = elementTypeIfVector(type);
2330 bool isVector = mlir::isa<cir::VectorType>(type);
2331 mlir::Type llvmType = getTypeConverter()->convertType(type);
2332 mlir::Location loc = op.getLoc();
2333
2334 // Integer unary operations: + - ~ ++ --
2335 if (mlir::isa<cir::IntType>(elementType)) {
2336 mlir::LLVM::IntegerOverflowFlags maybeNSW =
2337 op.getNoSignedWrap() ? mlir::LLVM::IntegerOverflowFlags::nsw
2338 : mlir::LLVM::IntegerOverflowFlags::none;
2339 switch (op.getKind()) {
2340 case cir::UnaryOpKind::Inc: {
2341 assert(!isVector && "++ not allowed on vector types");
2342 auto one = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, 1);
2343 rewriter.replaceOpWithNewOp<mlir::LLVM::AddOp>(
2344 op, llvmType, adaptor.getInput(), one, maybeNSW);
2345 return mlir::success();
2346 }
2347 case cir::UnaryOpKind::Dec: {
2348 assert(!isVector && "-- not allowed on vector types");
2349 auto one = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, 1);
2350 rewriter.replaceOpWithNewOp<mlir::LLVM::SubOp>(op, adaptor.getInput(),
2351 one, maybeNSW);
2352 return mlir::success();
2353 }
2354 case cir::UnaryOpKind::Plus:
2355 rewriter.replaceOp(op, adaptor.getInput());
2356 return mlir::success();
2357 case cir::UnaryOpKind::Minus: {
2358 mlir::Value zero;
2359 if (isVector)
2360 zero = mlir::LLVM::ZeroOp::create(rewriter, loc, llvmType);
2361 else
2362 zero = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, 0);
2363 rewriter.replaceOpWithNewOp<mlir::LLVM::SubOp>(
2364 op, zero, adaptor.getInput(), maybeNSW);
2365 return mlir::success();
2366 }
2367 case cir::UnaryOpKind::Not: {
2368 // bit-wise compliment operator, implemented as an XOR with -1.
2369 mlir::Value minusOne;
2370 if (isVector) {
2371 const uint64_t numElements =
2372 mlir::dyn_cast<cir::VectorType>(type).getSize();
2373 std::vector<int32_t> values(numElements, -1);
2374 mlir::DenseIntElementsAttr denseVec = rewriter.getI32VectorAttr(values);
2375 minusOne =
2376 mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, denseVec);
2377 } else {
2378 minusOne = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, -1);
2379 }
2380 rewriter.replaceOpWithNewOp<mlir::LLVM::XOrOp>(op, adaptor.getInput(),
2381 minusOne);
2382 return mlir::success();
2383 }
2384 }
2385 llvm_unreachable("Unexpected unary op for int");
2386 }
2387
2388 // Floating point unary operations: + - ++ --
2389 if (mlir::isa<cir::FPTypeInterface>(elementType)) {
2390 switch (op.getKind()) {
2391 case cir::UnaryOpKind::Inc: {
2392 assert(!isVector && "++ not allowed on vector types");
2393 mlir::LLVM::ConstantOp one = mlir::LLVM::ConstantOp::create(
2394 rewriter, loc, llvmType, rewriter.getFloatAttr(llvmType, 1.0));
2395 rewriter.replaceOpWithNewOp<mlir::LLVM::FAddOp>(op, llvmType, one,
2396 adaptor.getInput());
2397 return mlir::success();
2398 }
2399 case cir::UnaryOpKind::Dec: {
2400 assert(!isVector && "-- not allowed on vector types");
2401 mlir::LLVM::ConstantOp minusOne = mlir::LLVM::ConstantOp::create(
2402 rewriter, loc, llvmType, rewriter.getFloatAttr(llvmType, -1.0));
2403 rewriter.replaceOpWithNewOp<mlir::LLVM::FAddOp>(op, llvmType, minusOne,
2404 adaptor.getInput());
2405 return mlir::success();
2406 }
2407 case cir::UnaryOpKind::Plus:
2408 rewriter.replaceOp(op, adaptor.getInput());
2409 return mlir::success();
2410 case cir::UnaryOpKind::Minus:
2411 rewriter.replaceOpWithNewOp<mlir::LLVM::FNegOp>(op, llvmType,
2412 adaptor.getInput());
2413 return mlir::success();
2414 case cir::UnaryOpKind::Not:
2415 return op.emitError() << "Unary not is invalid for floating-point types";
2416 }
2417 llvm_unreachable("Unexpected unary op for float");
2418 }
2419
2420 // Boolean unary operations: ! only. (For all others, the operand has
2421 // already been promoted to int.)
2422 if (mlir::isa<cir::BoolType>(elementType)) {
2423 switch (op.getKind()) {
2424 case cir::UnaryOpKind::Inc:
2425 case cir::UnaryOpKind::Dec:
2426 case cir::UnaryOpKind::Plus:
2427 case cir::UnaryOpKind::Minus:
2428 // Some of these are allowed in source code, but we shouldn't get here
2429 // with a boolean type.
2430 return op.emitError() << "Unsupported unary operation on boolean type";
2431 case cir::UnaryOpKind::Not: {
2432 assert(!isVector && "NYI: op! on vector mask");
2433 auto one = mlir::LLVM::ConstantOp::create(rewriter, loc, llvmType, 1);
2434 rewriter.replaceOpWithNewOp<mlir::LLVM::XOrOp>(op, adaptor.getInput(),
2435 one);
2436 return mlir::success();
2437 }
2438 }
2439 llvm_unreachable("Unexpected unary op for bool");
2440 }
2441
2442 // Pointer unary operations: + only. (++ and -- of pointers are implemented
2443 // with cir.ptr_stride, not cir.unary.)
2444 if (mlir::isa<cir::PointerType>(elementType)) {
2445 switch (op.getKind()) {
2446 case cir::UnaryOpKind::Plus:
2447 rewriter.replaceOp(op, adaptor.getInput());
2448 return mlir::success();
2449 default:
2450 op.emitError() << "Unknown pointer unary operation during CIR lowering";
2451 return mlir::failure();
2452 }
2453 }
2454
2455 return op.emitError() << "Unary operation has unsupported type: "
2456 << elementType;
2457 }
2458
2459 mlir::LLVM::IntegerOverflowFlags
2460 CIRToLLVMBinOpLowering::getIntOverflowFlag(cir::BinOp op) const {
2461 if (op.getNoUnsignedWrap())
2462 return mlir::LLVM::IntegerOverflowFlags::nuw;
2463
2464 if (op.getNoSignedWrap())
2465 return mlir::LLVM::IntegerOverflowFlags::nsw;
2466
2467 return mlir::LLVM::IntegerOverflowFlags::none;
2468 }
2469
2470 static bool isIntTypeUnsigned(mlir::Type type) {
2471 // TODO: Ideally, we should only need to check cir::IntType here.
2472 return mlir::isa<cir::IntType>(type)
2473 ? mlir::cast<cir::IntType>(type).isUnsigned()
2474 : mlir::cast<mlir::IntegerType>(type).isUnsigned();
2475 }
2476
2477 mlir::LogicalResult CIRToLLVMBinOpLowering::matchAndRewrite(
2478 cir::BinOp op, OpAdaptor adaptor,
2479 mlir::ConversionPatternRewriter &rewriter) const {
2480 if (adaptor.getLhs().getType() != adaptor.getRhs().getType())
2481 return op.emitError() << "inconsistent operands' types not supported yet";
2482
2483 mlir::Type type = op.getRhs().getType();
2484 if (!mlir::isa<cir::IntType, cir::BoolType, cir::FPTypeInterface,
2485 mlir::IntegerType, cir::VectorType>(type))
2486 return op.emitError() << "operand type not supported yet";
2487
2488 const mlir::Type llvmTy = getTypeConverter()->convertType(op.getType());
2489 const mlir::Type llvmEltTy = elementTypeIfVector(llvmTy);
2490
2491 const mlir::Value rhs = adaptor.getRhs();
2492 const mlir::Value lhs = adaptor.getLhs();
2493 type = elementTypeIfVector(type);
2494
2495 switch (op.getKind()) {
2496 case cir::BinOpKind::Add:
2497 if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
2498 if (op.getSaturated()) {
2499 if (isIntTypeUnsigned(type)) {
2500 rewriter.replaceOpWithNewOp<mlir::LLVM::UAddSat>(op, lhs, rhs);
2501 break;
2502 }
2503 rewriter.replaceOpWithNewOp<mlir::LLVM::SAddSat>(op, lhs, rhs);
2504 break;
2505 }
2506 rewriter.replaceOpWithNewOp<mlir::LLVM::AddOp>(op, llvmTy, lhs, rhs,
2507 getIntOverflowFlag(op));
2508 } else {
2509 rewriter.replaceOpWithNewOp<mlir::LLVM::FAddOp>(op, lhs, rhs);
2510 }
2511 break;
2512 case cir::BinOpKind::Sub:
2513 if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
2514 if (op.getSaturated()) {
2515 if (isIntTypeUnsigned(type)) {
2516 rewriter.replaceOpWithNewOp<mlir::LLVM::USubSat>(op, lhs, rhs);
2517 break;
2518 }
2519 rewriter.replaceOpWithNewOp<mlir::LLVM::SSubSat>(op, lhs, rhs);
2520 break;
2521 }
2522 rewriter.replaceOpWithNewOp<mlir::LLVM::SubOp>(op, llvmTy, lhs, rhs,
2523 getIntOverflowFlag(op));
2524 } else {
2525 rewriter.replaceOpWithNewOp<mlir::LLVM::FSubOp>(op, lhs, rhs);
2526 }
2527 break;
2528 case cir::BinOpKind::Mul:
2529 if (mlir::isa<mlir::IntegerType>(llvmEltTy))
2530 rewriter.replaceOpWithNewOp<mlir::LLVM::MulOp>(op, llvmTy, lhs, rhs,
2531 getIntOverflowFlag(op));
2532 else
2533 rewriter.replaceOpWithNewOp<mlir::LLVM::FMulOp>(op, lhs, rhs);
2534 break;
2535 case cir::BinOpKind::Div:
2536 if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
2537 auto isUnsigned = isIntTypeUnsigned(type);
2538 if (isUnsigned)
2539 rewriter.replaceOpWithNewOp<mlir::LLVM::UDivOp>(op, lhs, rhs);
2540 else
2541 rewriter.replaceOpWithNewOp<mlir::LLVM::SDivOp>(op, lhs, rhs);
2542 } else {
2543 rewriter.replaceOpWithNewOp<mlir::LLVM::FDivOp>(op, lhs, rhs);
2544 }
2545 break;
2546 case cir::BinOpKind::Rem:
2547 if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
2548 auto isUnsigned = isIntTypeUnsigned(type);
2549 if (isUnsigned)
2550 rewriter.replaceOpWithNewOp<mlir::LLVM::URemOp>(op, lhs, rhs);
2551 else
2552 rewriter.replaceOpWithNewOp<mlir::LLVM::SRemOp>(op, lhs, rhs);
2553 } else {
2554 rewriter.replaceOpWithNewOp<mlir::LLVM::FRemOp>(op, lhs, rhs);
2555 }
2556 break;
2557 case cir::BinOpKind::And:
2558 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(op, lhs, rhs);
2559 break;
2560 case cir::BinOpKind::Or:
2561 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(op, lhs, rhs);
2562 break;
2563 case cir::BinOpKind::Xor:
2564 rewriter.replaceOpWithNewOp<mlir::LLVM::XOrOp>(op, lhs, rhs);
2565 break;
2566 case cir::BinOpKind::Max:
2567 if (mlir::isa<mlir::IntegerType>(llvmEltTy)) {
2568 auto isUnsigned = isIntTypeUnsigned(type);
2569 if (isUnsigned)
2570 rewriter.replaceOpWithNewOp<mlir::LLVM::UMaxOp>(op, llvmTy, lhs, rhs);
2571 else
2572 rewriter.replaceOpWithNewOp<mlir::LLVM::SMaxOp>(op, llvmTy, lhs, rhs);
2573 }
2574 break;
2575 }
2576 return mlir::LogicalResult::success();
2577 }
2578
2579 /// Convert from a CIR comparison kind to an LLVM IR integral comparison kind.
2580 static mlir::LLVM::ICmpPredicate
2581 convertCmpKindToICmpPredicate(cir::CmpOpKind kind, bool isSigned) {
2582 using CIR = cir::CmpOpKind;
2583 using LLVMICmp = mlir::LLVM::ICmpPredicate;
2584 switch (kind) {
2585 case CIR::eq:
2586 return LLVMICmp::eq;
2587 case CIR::ne:
2588 return LLVMICmp::ne;
2589 case CIR::lt:
2590 return (isSigned ? LLVMICmp::slt : LLVMICmp::ult);
2591 case CIR::le:
2592 return (isSigned ? LLVMICmp::sle : LLVMICmp::ule);
2593 case CIR::gt:
2594 return (isSigned ? LLVMICmp::sgt : LLVMICmp::ugt);
2595 case CIR::ge:
2596 return (isSigned ? LLVMICmp::sge : LLVMICmp::uge);
2597 }
2598 llvm_unreachable("Unknown CmpOpKind");
2599 }
2600
2601 /// Convert from a CIR comparison kind to an LLVM IR floating-point comparison
2602 /// kind.
2603 static mlir::LLVM::FCmpPredicate
2604 convertCmpKindToFCmpPredicate(cir::CmpOpKind kind) {
2605 using CIR = cir::CmpOpKind;
2606 using LLVMFCmp = mlir::LLVM::FCmpPredicate;
2607 switch (kind) {
2608 case CIR::eq:
2609 return LLVMFCmp::oeq;
2610 case CIR::ne:
2611 return LLVMFCmp::une;
2612 case CIR::lt:
2613 return LLVMFCmp::olt;
2614 case CIR::le:
2615 return LLVMFCmp::ole;
2616 case CIR::gt:
2617 return LLVMFCmp::ogt;
2618 case CIR::ge:
2619 return LLVMFCmp::oge;
2620 }
2621 llvm_unreachable("Unknown CmpOpKind");
2622 }
2623
2624 mlir::LogicalResult CIRToLLVMCmpOpLowering::matchAndRewrite(
2625 cir::CmpOp cmpOp, OpAdaptor adaptor,
2626 mlir::ConversionPatternRewriter &rewriter) const {
2627 mlir::Type type = cmpOp.getLhs().getType();
2628
2629 if (mlir::isa<cir::IntType, mlir::IntegerType>(type)) {
2630 bool isSigned = mlir::isa<cir::IntType>(type)
2631 ? mlir::cast<cir::IntType>(type).isSigned()
2632 : mlir::cast<mlir::IntegerType>(type).isSigned();
2633 mlir::LLVM::ICmpPredicate kind =
2634 convertCmpKindToICmpPredicate(cmpOp.getKind(), isSigned);
2635 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
2636 cmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
2637 return mlir::success();
2638 }
2639
2640 if (auto ptrTy = mlir::dyn_cast<cir::PointerType>(type)) {
2641 mlir::LLVM::ICmpPredicate kind =
2642 convertCmpKindToICmpPredicate(cmpOp.getKind(),
2643 /* isSigned=*/false);
2644 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
2645 cmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
2646 return mlir::success();
2647 }
2648
2649 if (auto vptrTy = mlir::dyn_cast<cir::VPtrType>(type)) {
2650 // !cir.vptr is a special case, but it's just a pointer to LLVM.
2651 auto kind = convertCmpKindToICmpPredicate(cmpOp.getKind(),
2652 /* isSigned=*/false);
2653 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
2654 cmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
2655 return mlir::success();
2656 }
2657
2658 if (mlir::isa<cir::FPTypeInterface>(type)) {
2659 mlir::LLVM::FCmpPredicate kind =
2660 convertCmpKindToFCmpPredicate(cmpOp.getKind());
2661 rewriter.replaceOpWithNewOp<mlir::LLVM::FCmpOp>(
2662 cmpOp, kind, adaptor.getLhs(), adaptor.getRhs());
2663 return mlir::success();
2664 }
2665
2666 if (mlir::isa<cir::ComplexType>(type)) {
2667 mlir::Value lhs = adaptor.getLhs();
2668 mlir::Value rhs = adaptor.getRhs();
2669 mlir::Location loc = cmpOp.getLoc();
2670
2671 auto complexType = mlir::cast<cir::ComplexType>(cmpOp.getLhs().getType());
2672 mlir::Type complexElemTy =
2673 getTypeConverter()->convertType(complexType.getElementType());
2674
2675 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
2676 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
2677 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
2678 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
2679 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
2680 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
2681 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
2682 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
2683
2684 if (cmpOp.getKind() == cir::CmpOpKind::eq) {
2685 if (complexElemTy.isInteger()) {
2686 auto realCmp = mlir::LLVM::ICmpOp::create(
2687 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, lhsReal, rhsReal);
2688 auto imagCmp = mlir::LLVM::ICmpOp::create(
2689 rewriter, loc, mlir::LLVM::ICmpPredicate::eq, lhsImag, rhsImag);
2690 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(cmpOp, realCmp, imagCmp);
2691 return mlir::success();
2692 }
2693
2694 auto realCmp = mlir::LLVM::FCmpOp::create(
2695 rewriter, loc, mlir::LLVM::FCmpPredicate::oeq, lhsReal, rhsReal);
2696 auto imagCmp = mlir::LLVM::FCmpOp::create(
2697 rewriter, loc, mlir::LLVM::FCmpPredicate::oeq, lhsImag, rhsImag);
2698 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(cmpOp, realCmp, imagCmp);
2699 return mlir::success();
2700 }
2701
2702 if (cmpOp.getKind() == cir::CmpOpKind::ne) {
2703 if (complexElemTy.isInteger()) {
2704 auto realCmp = mlir::LLVM::ICmpOp::create(
2705 rewriter, loc, mlir::LLVM::ICmpPredicate::ne, lhsReal, rhsReal);
2706 auto imagCmp = mlir::LLVM::ICmpOp::create(
2707 rewriter, loc, mlir::LLVM::ICmpPredicate::ne, lhsImag, rhsImag);
2708 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(cmpOp, realCmp, imagCmp);
2709 return mlir::success();
2710 }
2711
2712 auto realCmp = mlir::LLVM::FCmpOp::create(
2713 rewriter, loc, mlir::LLVM::FCmpPredicate::une, lhsReal, rhsReal);
2714 auto imagCmp = mlir::LLVM::FCmpOp::create(
2715 rewriter, loc, mlir::LLVM::FCmpPredicate::une, lhsImag, rhsImag);
2716 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(cmpOp, realCmp, imagCmp);
2717 return mlir::success();
2718 }
2719 }
2720
2721 return cmpOp.emitError() << "unsupported type for CmpOp: " << type;
2722 }
2723
2724 mlir::LogicalResult CIRToLLVMBinOpOverflowOpLowering::matchAndRewrite(
2725 cir::BinOpOverflowOp op, OpAdaptor adaptor,
2726 mlir::ConversionPatternRewriter &rewriter) const {
2727 mlir::Location loc = op.getLoc();
2728 cir::BinOpOverflowKind arithKind = op.getKind();
2729 cir::IntType operandTy = op.getLhs().getType();
2730 cir::IntType resultTy = op.getResult().getType();
2731
2732 EncompassedTypeInfo encompassedTyInfo =
2733 computeEncompassedTypeWidth(operandTy, resultTy);
2734 mlir::IntegerType encompassedLLVMTy =
2735 rewriter.getIntegerType(encompassedTyInfo.width);
2736
2737 mlir::Value lhs = adaptor.getLhs();
2738 mlir::Value rhs = adaptor.getRhs();
2739 if (operandTy.getWidth() < encompassedTyInfo.width) {
2740 if (operandTy.isSigned()) {
2741 lhs = mlir::LLVM::SExtOp::create(rewriter, loc, encompassedLLVMTy, lhs);
2742 rhs = mlir::LLVM::SExtOp::create(rewriter, loc, encompassedLLVMTy, rhs);
2743 } else {
2744 lhs = mlir::LLVM::ZExtOp::create(rewriter, loc, encompassedLLVMTy, lhs);
2745 rhs = mlir::LLVM::ZExtOp::create(rewriter, loc, encompassedLLVMTy, rhs);
2746 }
2747 }
2748
2749 std::string intrinName = getLLVMIntrinName(arithKind, encompassedTyInfo.sign,
2750 encompassedTyInfo.width);
2751 auto intrinNameAttr = mlir::StringAttr::get(op.getContext(), intrinName);
2752
2753 mlir::IntegerType overflowLLVMTy = rewriter.getI1Type();
2754 auto intrinRetTy = mlir::LLVM::LLVMStructType::getLiteral(
2755 rewriter.getContext(), {encompassedLLVMTy, overflowLLVMTy});
2756
2757 auto callLLVMIntrinOp = mlir::LLVM::CallIntrinsicOp::create(
2758 rewriter, loc, intrinRetTy, intrinNameAttr, mlir::ValueRange{lhs, rhs});
2759 mlir::Value intrinRet = callLLVMIntrinOp.getResult(0);
2760
2761 mlir::Value result = mlir::LLVM::ExtractValueOp::create(
2762 rewriter, loc, intrinRet, ArrayRef<int64_t>{0})
2763 .getResult();
2764 mlir::Value overflow = mlir::LLVM::ExtractValueOp::create(
2765 rewriter, loc, intrinRet, ArrayRef<int64_t>{1})
2766 .getResult();
2767
2768 if (resultTy.getWidth() < encompassedTyInfo.width) {
2769 mlir::Type resultLLVMTy = getTypeConverter()->convertType(resultTy);
2770 auto truncResult =
2771 mlir::LLVM::TruncOp::create(rewriter, loc, resultLLVMTy, result);
2772
2773 // Extend the truncated result back to the encompassing type to check for
2774 // any overflows during the truncation.
2775 mlir::Value truncResultExt;
2776 if (resultTy.isSigned())
2777 truncResultExt = mlir::LLVM::SExtOp::create(
2778 rewriter, loc, encompassedLLVMTy, truncResult);
2779 else
2780 truncResultExt = mlir::LLVM::ZExtOp::create(
2781 rewriter, loc, encompassedLLVMTy, truncResult);
2782 auto truncOverflow = mlir::LLVM::ICmpOp::create(
2783 rewriter, loc, mlir::LLVM::ICmpPredicate::ne, truncResultExt, result);
2784
2785 result = truncResult;
2786 overflow = mlir::LLVM::OrOp::create(rewriter, loc, overflow, truncOverflow);
2787 }
2788
2789 mlir::Type boolLLVMTy =
2790 getTypeConverter()->convertType(op.getOverflow().getType());
2791 if (boolLLVMTy != rewriter.getI1Type())
2792 overflow = mlir::LLVM::ZExtOp::create(rewriter, loc, boolLLVMTy, overflow);
2793
2794 rewriter.replaceOp(op, mlir::ValueRange{result, overflow});
2795
2796 return mlir::success();
2797 }
2798
2799 std::string CIRToLLVMBinOpOverflowOpLowering::getLLVMIntrinName(
2800 cir::BinOpOverflowKind opKind, bool isSigned, unsigned width) {
2801 // The intrinsic name is `@llvm.{s|u}{opKind}.with.overflow.i{width}`
2802
2803 std::string name = "llvm.";
2804
2805 if (isSigned)
2806 name.push_back('s');
2807 else
2808 name.push_back('u');
2809
2810 switch (opKind) {
2811 case cir::BinOpOverflowKind::Add:
2812 name.append("add.");
2813 break;
2814 case cir::BinOpOverflowKind::Sub:
2815 name.append("sub.");
2816 break;
2817 case cir::BinOpOverflowKind::Mul:
2818 name.append("mul.");
2819 break;
2820 }
2821
2822 name.append("with.overflow.i");
2823 name.append(std::to_string(width));
2824
2825 return name;
2826 }
2827
2828 CIRToLLVMBinOpOverflowOpLowering::EncompassedTypeInfo
2829 CIRToLLVMBinOpOverflowOpLowering::computeEncompassedTypeWidth(
2830 cir::IntType operandTy, cir::IntType resultTy) {
2831 bool sign = operandTy.getIsSigned() || resultTy.getIsSigned();
2832 unsigned width =
2833 std::max(operandTy.getWidth() + (sign && operandTy.isUnsigned()),
2834 resultTy.getWidth() + (sign && resultTy.isUnsigned()));
2835 return {sign, width};
2836 }
2837
2838 mlir::LogicalResult CIRToLLVMShiftOpLowering::matchAndRewrite(
2839 cir::ShiftOp op, OpAdaptor adaptor,
2840 mlir::ConversionPatternRewriter &rewriter) const {
2841 assert((op.getValue().getType() == op.getType()) &&
2842 "inconsistent operands' types NYI");
2843
2844 const mlir::Type llvmTy = getTypeConverter()->convertType(op.getType());
2845 mlir::Value amt = adaptor.getAmount();
2846 mlir::Value val = adaptor.getValue();
2847
2848 auto cirAmtTy = mlir::dyn_cast<cir::IntType>(op.getAmount().getType());
2849 bool isUnsigned;
2850 if (cirAmtTy) {
2851 auto cirValTy = mlir::cast<cir::IntType>(op.getValue().getType());
2852 isUnsigned = cirValTy.isUnsigned();
2853
2854 // Ensure shift amount is the same type as the value. Some undefined
2855 // behavior might occur in the casts below as per [C99 6.5.7.3].
2856 // Vector type shift amount needs no cast as type consistency is expected to
2857 // be already be enforced at CIRGen.
2858 if (cirAmtTy)
2859 amt = getLLVMIntCast(rewriter, amt, llvmTy, true, cirAmtTy.getWidth(),
2860 cirValTy.getWidth());
2861 } else {
2862 auto cirValVTy = mlir::cast<cir::VectorType>(op.getValue().getType());
2863 isUnsigned =
2864 mlir::cast<cir::IntType>(cirValVTy.getElementType()).isUnsigned();
2865 }
2866
2867 // Lower to the proper LLVM shift operation.
2868 if (op.getIsShiftleft()) {
2869 rewriter.replaceOpWithNewOp<mlir::LLVM::ShlOp>(op, llvmTy, val, amt);
2870 return mlir::success();
2871 }
2872
2873 if (isUnsigned)
2874 rewriter.replaceOpWithNewOp<mlir::LLVM::LShrOp>(op, llvmTy, val, amt);
2875 else
2876 rewriter.replaceOpWithNewOp<mlir::LLVM::AShrOp>(op, llvmTy, val, amt);
2877 return mlir::success();
2878 }
2879
2880 mlir::LogicalResult CIRToLLVMSelectOpLowering::matchAndRewrite(
2881 cir::SelectOp op, OpAdaptor adaptor,
2882 mlir::ConversionPatternRewriter &rewriter) const {
2883 auto getConstantBool = [](mlir::Value value) -> cir::BoolAttr {
2884 auto definingOp = value.getDefiningOp<cir::ConstantOp>();
2885 if (!definingOp)
2886 return {};
2887
2888 auto constValue = definingOp.getValueAttr<cir::BoolAttr>();
2889 if (!constValue)
2890 return {};
2891
2892 return constValue;
2893 };
2894
2895 // Two special cases in the LLVMIR codegen of select op:
2896 // - select %0, %1, false => and %0, %1
2897 // - select %0, true, %1 => or %0, %1
2898 if (mlir::isa<cir::BoolType>(op.getTrueValue().getType())) {
2899 cir::BoolAttr trueValue = getConstantBool(op.getTrueValue());
2900 cir::BoolAttr falseValue = getConstantBool(op.getFalseValue());
2901 if (falseValue && !falseValue.getValue()) {
2902 // select %0, %1, false => and %0, %1
2903 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(op, adaptor.getCondition(),
2904 adaptor.getTrueValue());
2905 return mlir::success();
2906 }
2907 if (trueValue && trueValue.getValue()) {
2908 // select %0, true, %1 => or %0, %1
2909 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(op, adaptor.getCondition(),
2910 adaptor.getFalseValue());
2911 return mlir::success();
2912 }
2913 }
2914
2915 mlir::Value llvmCondition = adaptor.getCondition();
2916 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(
2917 op, llvmCondition, adaptor.getTrueValue(), adaptor.getFalseValue());
2918
2919 return mlir::success();
2920 }
2921
2922 std::unique_ptr<cir::LowerModule> prepareLowerModule(mlir::ModuleOp module) {
2923 mlir::PatternRewriter rewriter{module->getContext()};
2924 // If the triple is not present, e.g. CIR modules parsed from text, we
2925 // cannot init LowerModule properly. This happens in some lowering tests,
2926 // but it should not happen in real compilation.
2927 assert(!cir::MissingFeatures::makeTripleAlwaysPresent());
2928 if (!module->hasAttr(cir::CIRDialect::getTripleAttrName()))
2929 return {};
2930 return cir::createLowerModule(module, rewriter);
2931 }
2932
2933 static void prepareTypeConverter(mlir::LLVMTypeConverter &converter,
2934 mlir::DataLayout &dataLayout,
2935 cir::LowerModule *lowerModule) {
2936 converter.addConversion([&](cir::PointerType type) -> mlir::Type {
2937 unsigned addrSpace =
2938 type.getAddrSpace() ? type.getAddrSpace().getValue().getUInt() : 0;
2939 return mlir::LLVM::LLVMPointerType::get(type.getContext(), addrSpace);
2940 });
2941 converter.addConversion([&](cir::VPtrType type) -> mlir::Type {
2942 assert(!cir::MissingFeatures::addressSpace());
2943 return mlir::LLVM::LLVMPointerType::get(type.getContext());
2944 });
2945 converter.addConversion([&](cir::ArrayType type) -> mlir::Type {
2946 mlir::Type ty =
2947 convertTypeForMemory(converter, dataLayout, type.getElementType());
2948 return mlir::LLVM::LLVMArrayType::get(ty, type.getSize());
2949 });
2950 converter.addConversion([&](cir::VectorType type) -> mlir::Type {
2951 const mlir::Type ty = converter.convertType(type.getElementType());
2952 return mlir::VectorType::get(type.getSize(), ty, {type.getIsScalable()});
2953 });
2954 converter.addConversion([&](cir::BoolType type) -> mlir::Type {
2955 return mlir::IntegerType::get(type.getContext(), 1,
2956 mlir::IntegerType::Signless);
2957 });
2958 converter.addConversion([&](cir::IntType type) -> mlir::Type {
2959 // LLVM doesn't work with signed types, so we drop the CIR signs here.
2960 return mlir::IntegerType::get(type.getContext(), type.getWidth());
2961 });
2962 converter.addConversion([&](cir::SingleType type) -> mlir::Type {
2963 return mlir::Float32Type::get(type.getContext());
2964 });
2965 converter.addConversion([&](cir::DoubleType type) -> mlir::Type {
2966 return mlir::Float64Type::get(type.getContext());
2967 });
2968 converter.addConversion([&](cir::FP80Type type) -> mlir::Type {
2969 return mlir::Float80Type::get(type.getContext());
2970 });
2971 converter.addConversion([&](cir::FP128Type type) -> mlir::Type {
2972 return mlir::Float128Type::get(type.getContext());
2973 });
2974 converter.addConversion([&](cir::LongDoubleType type) -> mlir::Type {
2975 return converter.convertType(type.getUnderlying());
2976 });
2977 converter.addConversion([&](cir::FP16Type type) -> mlir::Type {
2978 return mlir::Float16Type::get(type.getContext());
2979 });
2980 converter.addConversion([&](cir::BF16Type type) -> mlir::Type {
2981 return mlir::BFloat16Type::get(type.getContext());
2982 });
2983 converter.addConversion([&](cir::ComplexType type) -> mlir::Type {
2984 // A complex type is lowered to an LLVM struct that contains the real and
2985 // imaginary part as data fields.
2986 mlir::Type elementTy = converter.convertType(type.getElementType());
2987 mlir::Type structFields[2] = {elementTy, elementTy};
2988 return mlir::LLVM::LLVMStructType::getLiteral(type.getContext(),
2989 structFields);
2990 });
2991 converter.addConversion([&](cir::FuncType type) -> std::optional<mlir::Type> {
2992 auto result = converter.convertType(type.getReturnType());
2993 llvm::SmallVector<mlir::Type> arguments;
2994 arguments.reserve(type.getNumInputs());
2995 if (converter.convertTypes(type.getInputs(), arguments).failed())
2996 return std::nullopt;
2997 auto varArg = type.isVarArg();
2998 return mlir::LLVM::LLVMFunctionType::get(result, arguments, varArg);
2999 });
3000 converter.addConversion([&](cir::RecordType type) -> mlir::Type {
3001 // Convert struct members.
3002 llvm::SmallVector<mlir::Type> llvmMembers;
3003 switch (type.getKind()) {
3004 case cir::RecordType::Class:
3005 case cir::RecordType::Struct:
3006 for (mlir::Type ty : type.getMembers())
3007 llvmMembers.push_back(convertTypeForMemory(converter, dataLayout, ty));
3008 break;
3009 // Unions are lowered as only the largest member.
3010 case cir::RecordType::Union:
3011 if (type.getMembers().empty())
3012 break;
3013 if (auto largestMember = type.getLargestMember(dataLayout))
3014 llvmMembers.push_back(
3015 convertTypeForMemory(converter, dataLayout, largestMember));
3016 if (type.getPadded()) {
3017 auto last = *type.getMembers().rbegin();
3018 llvmMembers.push_back(
3019 convertTypeForMemory(converter, dataLayout, last));
3020 }
3021 break;
3022 }
3023
3024 // Record has a name: lower as an identified record.
3025 mlir::LLVM::LLVMStructType llvmStruct;
3026 if (type.getName()) {
3027 llvmStruct = mlir::LLVM::LLVMStructType::getIdentified(
3028 type.getContext(), type.getPrefixedName());
3029 if (llvmStruct.setBody(llvmMembers, type.getPacked()).failed())
3030 llvm_unreachable("Failed to set body of record");
3031 } else { // Record has no name: lower as literal record.
3032 llvmStruct = mlir::LLVM::LLVMStructType::getLiteral(
3033 type.getContext(), llvmMembers, type.getPacked());
3034 }
3035
3036 return llvmStruct;
3037 });
3038 converter.addConversion([&](cir::VoidType type) -> mlir::Type {
3039 return mlir::LLVM::LLVMVoidType::get(type.getContext());
3040 });
3041 }
3042
3043 static void buildCtorDtorList(
3044 mlir::ModuleOp module, StringRef globalXtorName, StringRef llvmXtorName,
3045 llvm::function_ref<std::pair<StringRef, int>(mlir::Attribute)> createXtor) {
3046 llvm::SmallVector<std::pair<StringRef, int>> globalXtors;
3047 for (const mlir::NamedAttribute namedAttr : module->getAttrs()) {
3048 if (namedAttr.getName() == globalXtorName) {
3049 for (auto attr : mlir::cast<mlir::ArrayAttr>(namedAttr.getValue()))
3050 globalXtors.emplace_back(createXtor(attr));
3051 break;
3052 }
3053 }
3054
3055 if (globalXtors.empty())
3056 return;
3057
3058 mlir::OpBuilder builder(module.getContext());
3059 builder.setInsertionPointToEnd(&module.getBodyRegion().back());
3060
3061 // Create a global array llvm.global_ctors with element type of
3062 // struct { i32, ptr, ptr }
3063 auto ctorPFTy = mlir::LLVM::LLVMPointerType::get(builder.getContext());
3064 llvm::SmallVector<mlir::Type> ctorStructFields;
3065 ctorStructFields.push_back(builder.getI32Type());
3066 ctorStructFields.push_back(ctorPFTy);
3067 ctorStructFields.push_back(ctorPFTy);
3068
3069 auto ctorStructTy = mlir::LLVM::LLVMStructType::getLiteral(
3070 builder.getContext(), ctorStructFields);
3071 auto ctorStructArrayTy =
3072 mlir::LLVM::LLVMArrayType::get(ctorStructTy, globalXtors.size());
3073
3074 mlir::Location loc = module.getLoc();
3075 auto newGlobalOp = mlir::LLVM::GlobalOp::create(
3076 builder, loc, ctorStructArrayTy, /*constant=*/false,
3077 mlir::LLVM::Linkage::Appending, llvmXtorName, mlir::Attribute());
3078
3079 builder.createBlock(&newGlobalOp.getRegion());
3080 builder.setInsertionPointToEnd(newGlobalOp.getInitializerBlock());
3081
3082 mlir::Value result =
3083 mlir::LLVM::UndefOp::create(builder, loc, ctorStructArrayTy);
3084
3085 for (auto [index, fn] : llvm::enumerate(globalXtors)) {
3086 mlir::Value structInit =
3087 mlir::LLVM::UndefOp::create(builder, loc, ctorStructTy);
3088 mlir::Value initPriority = mlir::LLVM::ConstantOp::create(
3089 builder, loc, ctorStructFields[0], fn.second);
3090 mlir::Value initFuncAddr = mlir::LLVM::AddressOfOp::create(
3091 builder, loc, ctorStructFields[1], fn.first);
3092 mlir::Value initAssociate =
3093 mlir::LLVM::ZeroOp::create(builder, loc, ctorStructFields[2]);
3094 // Literal zero makes the InsertValueOp::create ambiguous.
3095 llvm::SmallVector<int64_t> zero{0};
3096 structInit = mlir::LLVM::InsertValueOp::create(builder, loc, structInit,
3097 initPriority, zero);
3098 structInit = mlir::LLVM::InsertValueOp::create(builder, loc, structInit,
3099 initFuncAddr, 1);
3100 // TODO: handle associated data for initializers.
3101 structInit = mlir::LLVM::InsertValueOp::create(builder, loc, structInit,
3102 initAssociate, 2);
3103 result = mlir::LLVM::InsertValueOp::create(builder, loc, result, structInit,
3104 index);
3105 }
3106
3107 mlir::LLVM::ReturnOp::create(builder, loc, result);
3108 }
3109
3110 // The applyPartialConversion function traverses blocks in the dominance order,
3111 // so it does not lower and operations that are not reachachable from the
3112 // operations passed in as arguments. Since we do need to lower such code in
3113 // order to avoid verification errors occur, we cannot just pass the module op
3114 // to applyPartialConversion. We must build a set of unreachable ops and
3115 // explicitly add them, along with the module, to the vector we pass to
3116 // applyPartialConversion.
3117 //
3118 // For instance, this CIR code:
3119 //
3120 // cir.func @foo(%arg0: !s32i) -> !s32i {
3121 // %4 = cir.cast int_to_bool %arg0 : !s32i -> !cir.bool
3122 // cir.if %4 {
3123 // %5 = cir.const #cir.int<1> : !s32i
3124 // cir.return %5 : !s32i
3125 // } else {
3126 // %5 = cir.const #cir.int<0> : !s32i
3127 // cir.return %5 : !s32i
3128 // }
3129 // cir.return %arg0 : !s32i
3130 // }
3131 //
3132 // contains an unreachable return operation (the last one). After the flattening
3133 // pass it will be placed into the unreachable block. The possible error
3134 // after the lowering pass is: error: 'cir.return' op expects parent op to be
3135 // one of 'cir.func, cir.scope, cir.if ... The reason that this operation was
3136 // not lowered and the new parent is llvm.func.
3137 //
3138 // In the future we may want to get rid of this function and use a DCE pass or
3139 // something similar. But for now we need to guarantee the absence of the
3140 // dialect verification errors.
3141 static void collectUnreachable(mlir::Operation *parent,
3142 llvm::SmallVector<mlir::Operation *> &ops) {
3143
3144 llvm::SmallVector<mlir::Block *> unreachableBlocks;
3145 parent->walk([&](mlir::Block *blk) { // check
3146 if (blk->hasNoPredecessors() && !blk->isEntryBlock())
3147 unreachableBlocks.push_back(blk);
3148 });
3149
3150 std::set<mlir::Block *> visited;
3151 for (mlir::Block *root : unreachableBlocks) {
3152 // We create a work list for each unreachable block.
3153 // Thus we traverse operations in some order.
3154 std::deque<mlir::Block *> workList;
3155 workList.push_back(root);
3156
3157 while (!workList.empty()) {
3158 mlir::Block *blk = workList.back();
3159 workList.pop_back();
3160 if (visited.count(blk))
3161 continue;
3162 visited.emplace(blk);
3163
3164 for (mlir::Operation &op : *blk)
3165 ops.push_back(&op);
3166
3167 for (mlir::Block *succ : blk->getSuccessors())
3168 workList.push_back(succ);
3169 }
3170 }
3171 }
3172
3173 mlir::LogicalResult CIRToLLVMObjSizeOpLowering::matchAndRewrite(
3174 cir::ObjSizeOp op, OpAdaptor adaptor,
3175 mlir::ConversionPatternRewriter &rewriter) const {
3176 mlir::Type llvmResTy = getTypeConverter()->convertType(op.getType());
3177 mlir::Location loc = op->getLoc();
3178
3179 mlir::IntegerType i1Ty = rewriter.getI1Type();
3180
3181 auto i1Val = [&rewriter, &loc, &i1Ty](bool val) {
3182 return mlir::LLVM::ConstantOp::create(rewriter, loc, i1Ty, val);
3183 };
3184
3185 replaceOpWithCallLLVMIntrinsicOp(rewriter, op, "llvm.objectsize", llvmResTy,
3186 {
3187 adaptor.getPtr(),
3188 i1Val(op.getMin()),
3189 i1Val(op.getNullunknown()),
3190 i1Val(op.getDynamic()),
3191 });
3192
3193 return mlir::LogicalResult::success();
3194 }
3195
3196 void ConvertCIRToLLVMPass::processCIRAttrs(mlir::ModuleOp module) {
3197 // Lower the module attributes to LLVM equivalents.
3198 if (mlir::Attribute tripleAttr =
3199 module->getAttr(cir::CIRDialect::getTripleAttrName()))
3200 module->setAttr(mlir::LLVM::LLVMDialect::getTargetTripleAttrName(),
3201 tripleAttr);
3202
3203 if (mlir::Attribute asmAttr =
3204 module->getAttr(cir::CIRDialect::getModuleLevelAsmAttrName()))
3205 module->setAttr(mlir::LLVM::LLVMDialect::getModuleLevelAsmAttrName(),
3206 asmAttr);
3207 }
3208
3209 void ConvertCIRToLLVMPass::runOnOperation() {
3210 llvm::TimeTraceScope scope("Convert CIR to LLVM Pass");
3211
3212 mlir::ModuleOp module = getOperation();
3213 mlir::DataLayout dl(module);
3214 mlir::LLVMTypeConverter converter(&getContext());
3215 std::unique_ptr<cir::LowerModule> lowerModule = prepareLowerModule(module);
3216 prepareTypeConverter(converter, dl, lowerModule.get());
3217
3218 mlir::RewritePatternSet patterns(&getContext());
3219
3220 patterns.add<
3221 #define GET_LLVM_LOWERING_PATTERNS_LIST
3222 #include "clang/CIR/Dialect/IR/CIRLowering.inc"
3223 #undef GET_LLVM_LOWERING_PATTERNS_LIST
3224 >(converter, patterns.getContext(), lowerModule.get(), dl);
3225
3226 processCIRAttrs(module);
3227
3228 mlir::ConversionTarget target(getContext());
3229 target.addLegalOp<mlir::ModuleOp>();
3230 target.addLegalDialect<mlir::LLVM::LLVMDialect>();
3231 target.addIllegalDialect<mlir::BuiltinDialect, cir::CIRDialect,
3232 mlir::func::FuncDialect>();
3233
3234 llvm::SmallVector<mlir::Operation *> ops;
3235 ops.push_back(module);
3236 collectUnreachable(module, ops);
3237
3238 if (failed(applyPartialConversion(ops, target, std::move(patterns))))
3239 signalPassFailure();
3240
3241 // Emit the llvm.global_ctors array.
3242 buildCtorDtorList(module, cir::CIRDialect::getGlobalCtorsAttrName(),
3243 "llvm.global_ctors", [](mlir::Attribute attr) {
3244 auto ctorAttr = mlir::cast<cir::GlobalCtorAttr>(attr);
3245 return std::make_pair(ctorAttr.getName(),
3246 ctorAttr.getPriority());
3247 });
3248 // Emit the llvm.global_dtors array.
3249 buildCtorDtorList(module, cir::CIRDialect::getGlobalDtorsAttrName(),
3250 "llvm.global_dtors", [](mlir::Attribute attr) {
3251 auto dtorAttr = mlir::cast<cir::GlobalDtorAttr>(attr);
3252 return std::make_pair(dtorAttr.getName(),
3253 dtorAttr.getPriority());
3254 });
3255 }
3256
3257 mlir::LogicalResult CIRToLLVMBrOpLowering::matchAndRewrite(
3258 cir::BrOp op, OpAdaptor adaptor,
3259 mlir::ConversionPatternRewriter &rewriter) const {
3260 rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(op, adaptor.getOperands(),
3261 op.getDest());
3262 return mlir::LogicalResult::success();
3263 }
3264
3265 mlir::LogicalResult CIRToLLVMGetMemberOpLowering::matchAndRewrite(
3266 cir::GetMemberOp op, OpAdaptor adaptor,
3267 mlir::ConversionPatternRewriter &rewriter) const {
3268 mlir::Type llResTy = getTypeConverter()->convertType(op.getType());
3269 const auto recordTy =
3270 mlir::cast<cir::RecordType>(op.getAddrTy().getPointee());
3271 assert(recordTy && "expected record type");
3272
3273 switch (recordTy.getKind()) {
3274 case cir::RecordType::Class:
3275 case cir::RecordType::Struct: {
3276 // Since the base address is a pointer to an aggregate, the first offset
3277 // is always zero. The second offset tell us which member it will access.
3278 llvm::SmallVector<mlir::LLVM::GEPArg, 2> offset{0, op.getIndex()};
3279 const mlir::Type elementTy = getTypeConverter()->convertType(recordTy);
3280 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(op, llResTy, elementTy,
3281 adaptor.getAddr(), offset);
3282 return mlir::success();
3283 }
3284 case cir::RecordType::Union:
3285 // Union members share the address space, so we just need a bitcast to
3286 // conform to type-checking.
3287 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(op, llResTy,
3288 adaptor.getAddr());
3289 return mlir::success();
3290 }
3291 }
3292
3293 mlir::LogicalResult CIRToLLVMExtractMemberOpLowering::matchAndRewrite(
3294 cir::ExtractMemberOp op, OpAdaptor adaptor,
3295 mlir::ConversionPatternRewriter &rewriter) const {
3296 std::int64_t indices[1] = {static_cast<std::int64_t>(op.getIndex())};
3297
3298 mlir::Type recordTy = op.getRecord().getType();
3299 auto cirRecordTy = mlir::cast<cir::RecordType>(recordTy);
3300 switch (cirRecordTy.getKind()) {
3301 case cir::RecordType::Struct:
3302 case cir::RecordType::Class:
3303 rewriter.replaceOpWithNewOp<mlir::LLVM::ExtractValueOp>(
3304 op, adaptor.getRecord(), indices);
3305 return mlir::success();
3306
3307 case cir::RecordType::Union:
3308 op.emitError("cir.extract_member cannot extract member from a union");
3309 return mlir::failure();
3310 }
3311 llvm_unreachable("Unexpected record kind");
3312 }
3313
3314 mlir::LogicalResult CIRToLLVMUnreachableOpLowering::matchAndRewrite(
3315 cir::UnreachableOp op, OpAdaptor adaptor,
3316 mlir::ConversionPatternRewriter &rewriter) const {
3317 rewriter.replaceOpWithNewOp<mlir::LLVM::UnreachableOp>(op);
3318 return mlir::success();
3319 }
3320
3321 void createLLVMFuncOpIfNotExist(mlir::ConversionPatternRewriter &rewriter,
3322 mlir::Operation *srcOp, llvm::StringRef fnName,
3323 mlir::Type fnTy) {
3324 auto modOp = srcOp->getParentOfType<mlir::ModuleOp>();
3325 auto enclosingFnOp = srcOp->getParentOfType<mlir::LLVM::LLVMFuncOp>();
3326 mlir::Operation *sourceSymbol =
3327 mlir::SymbolTable::lookupSymbolIn(modOp, fnName);
3328 if (!sourceSymbol) {
3329 mlir::OpBuilder::InsertionGuard guard(rewriter);
3330 rewriter.setInsertionPoint(enclosingFnOp);
3331 mlir::LLVM::LLVMFuncOp::create(rewriter, srcOp->getLoc(), fnName, fnTy);
3332 }
3333 }
3334
3335 mlir::LogicalResult CIRToLLVMThrowOpLowering::matchAndRewrite(
3336 cir::ThrowOp op, OpAdaptor adaptor,
3337 mlir::ConversionPatternRewriter &rewriter) const {
3338 mlir::Location loc = op.getLoc();
3339 auto voidTy = mlir::LLVM::LLVMVoidType::get(getContext());
3340
3341 if (op.rethrows()) {
3342 auto funcTy = mlir::LLVM::LLVMFunctionType::get(voidTy, {});
3343
3344 // Get or create `declare void @__cxa_rethrow()`
3345 const llvm::StringRef functionName = "__cxa_rethrow";
3346 createLLVMFuncOpIfNotExist(rewriter, op, functionName, funcTy);
3347
3348 auto cxaRethrow = mlir::LLVM::CallOp::create(
3349 rewriter, loc, mlir::TypeRange{}, functionName);
3350
3351 rewriter.replaceOp(op, cxaRethrow);
3352 return mlir::success();
3353 }
3354
3355 auto llvmPtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
3356 auto fnTy = mlir::LLVM::LLVMFunctionType::get(
3357 voidTy, {llvmPtrTy, llvmPtrTy, llvmPtrTy});
3358
3359 // Get or create `declare void @__cxa_throw(ptr, ptr, ptr)`
3360 const llvm::StringRef fnName = "__cxa_throw";
3361 createLLVMFuncOpIfNotExist(rewriter, op, fnName, fnTy);
3362
3363 mlir::Value typeInfo = mlir::LLVM::AddressOfOp::create(
3364 rewriter, loc, mlir::LLVM::LLVMPointerType::get(rewriter.getContext()),
3365 adaptor.getTypeInfoAttr());
3366
3367 mlir::Value dtor;
3368 if (op.getDtor()) {
3369 dtor = mlir::LLVM::AddressOfOp::create(rewriter, loc, llvmPtrTy,
3370 adaptor.getDtorAttr());
3371 } else {
3372 dtor = mlir::LLVM::ZeroOp::create(rewriter, loc, llvmPtrTy);
3373 }
3374
3375 auto cxaThrowCall = mlir::LLVM::CallOp::create(
3376 rewriter, loc, mlir::TypeRange{}, fnName,
3377 mlir::ValueRange{adaptor.getExceptionPtr(), typeInfo, dtor});
3378
3379 rewriter.replaceOp(op, cxaThrowCall);
3380 return mlir::success();
3381 }
3382
3383 mlir::LogicalResult CIRToLLVMAllocExceptionOpLowering::matchAndRewrite(
3384 cir::AllocExceptionOp op, OpAdaptor adaptor,
3385 mlir::ConversionPatternRewriter &rewriter) const {
3386 // Get or create `declare ptr @__cxa_allocate_exception(i64)`
3387 StringRef fnName = "__cxa_allocate_exception";
3388 auto llvmPtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
3389 auto int64Ty = mlir::IntegerType::get(rewriter.getContext(), 64);
3390 auto fnTy = mlir::LLVM::LLVMFunctionType::get(llvmPtrTy, {int64Ty});
3391
3392 createLLVMFuncOpIfNotExist(rewriter, op, fnName, fnTy);
3393 auto exceptionSize = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
3394 adaptor.getSizeAttr());
3395
3396 auto allocaExceptionCall = mlir::LLVM::CallOp::create(
3397 rewriter, op.getLoc(), mlir::TypeRange{llvmPtrTy}, fnName,
3398 mlir::ValueRange{exceptionSize});
3399
3400 rewriter.replaceOp(op, allocaExceptionCall);
3401 return mlir::success();
3402 }
3403
3404 static mlir::LLVM::LLVMStructType
3405 getLLVMLandingPadStructTy(mlir::ConversionPatternRewriter &rewriter) {
3406 // Create the landing pad type: struct { ptr, i32 }
3407 mlir::MLIRContext *ctx = rewriter.getContext();
3408 auto llvmPtr = mlir::LLVM::LLVMPointerType::get(ctx);
3409 llvm::SmallVector<mlir::Type> structFields = {llvmPtr, rewriter.getI32Type()};
3410 return mlir::LLVM::LLVMStructType::getLiteral(ctx, structFields);
3411 }
3412
3413 mlir::LogicalResult CIRToLLVMEhInflightOpLowering::matchAndRewrite(
3414 cir::EhInflightOp op, OpAdaptor adaptor,
3415 mlir::ConversionPatternRewriter &rewriter) const {
3416 auto llvmFn = op->getParentOfType<mlir::LLVM::LLVMFuncOp>();
3417 assert(llvmFn && "expected LLVM function parent");
3418 mlir::Block *entryBlock = &llvmFn.getRegion().front();
3419 assert(entryBlock->isEntryBlock());
3420
3421 mlir::ArrayAttr catchListAttr = op.getCatchTypeListAttr();
3422 mlir::SmallVector<mlir::Value> catchSymAddrs;
3423
3424 auto llvmPtrTy = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
3425 mlir::Location loc = op.getLoc();
3426
3427 // %landingpad = landingpad { ptr, i32 }
3428 // Note that since llvm.landingpad has to be the first operation on the
3429 // block, any needed value for its operands has to be added somewhere else.
3430 if (catchListAttr) {
3431 // catch ptr @_ZTIi
3432 // catch ptr @_ZTIPKc
3433 for (mlir::Attribute catchAttr : catchListAttr) {
3434 auto symAttr = cast<mlir::FlatSymbolRefAttr>(catchAttr);
3435 // Generate `llvm.mlir.addressof` for each symbol, and place those
3436 // operations in the LLVM function entry basic block.
3437 mlir::OpBuilder::InsertionGuard guard(rewriter);
3438 rewriter.setInsertionPointToStart(entryBlock);
3439 mlir::Value addrOp = mlir::LLVM::AddressOfOp::create(
3440 rewriter, loc, llvmPtrTy, symAttr.getValue());
3441 catchSymAddrs.push_back(addrOp);
3442 }
3443 } else if (!op.getCleanup()) {
3444 // We need to emit catch-all only if cleanup is not set, because when we
3445 // have catch-all handler, there is no case when we set would unwind past
3446 // the handler
3447 mlir::OpBuilder::InsertionGuard guard(rewriter);
3448 rewriter.setInsertionPointToStart(entryBlock);
3449 mlir::Value nullOp = mlir::LLVM::ZeroOp::create(rewriter, loc, llvmPtrTy);
3450 catchSymAddrs.push_back(nullOp);
3451 }
3452
3453 // %slot = extractvalue { ptr, i32 } %x, 0
3454 // %selector = extractvalue { ptr, i32 } %x, 1
3455 mlir::LLVM::LLVMStructType llvmLandingPadStructTy =
3456 getLLVMLandingPadStructTy(rewriter);
3457 auto landingPadOp = mlir::LLVM::LandingpadOp::create(
3458 rewriter, loc, llvmLandingPadStructTy, catchSymAddrs);
3459
3460 if (op.getCleanup())
3461 landingPadOp.setCleanup(true);
3462
3463 mlir::Value slot =
3464 mlir::LLVM::ExtractValueOp::create(rewriter, loc, landingPadOp, 0);
3465 mlir::Value selector =
3466 mlir::LLVM::ExtractValueOp::create(rewriter, loc, landingPadOp, 1);
3467 rewriter.replaceOp(op, mlir::ValueRange{slot, selector});
3468
3469 return mlir::success();
3470 }
3471
3472 mlir::LogicalResult CIRToLLVMResumeFlatOpLowering::matchAndRewrite(
3473 cir::ResumeFlatOp op, OpAdaptor adaptor,
3474 mlir::ConversionPatternRewriter &rewriter) const {
3475 // %lpad.val = insertvalue { ptr, i32 } poison, ptr %exception_ptr, 0
3476 // %lpad.val2 = insertvalue { ptr, i32 } %lpad.val, i32 %selector, 1
3477 // resume { ptr, i32 } %lpad.val2
3478 mlir::Type llvmLandingPadStructTy = getLLVMLandingPadStructTy(rewriter);
3479 mlir::Value poison = mlir::LLVM::PoisonOp::create(rewriter, op.getLoc(),
3480 llvmLandingPadStructTy);
3481
3482 SmallVector<int64_t> slotIdx = {0};
3483 mlir::Value slot = mlir::LLVM::InsertValueOp::create(
3484 rewriter, op.getLoc(), poison, adaptor.getExceptionPtr(), slotIdx);
3485
3486 SmallVector<int64_t> selectorIdx = {1};
3487 mlir::Value selector = mlir::LLVM::InsertValueOp::create(
3488 rewriter, op.getLoc(), slot, adaptor.getTypeId(), selectorIdx);
3489
3490 rewriter.replaceOpWithNewOp<mlir::LLVM::ResumeOp>(op, selector);
3491 return mlir::success();
3492 }
3493
3494 mlir::LogicalResult CIRToLLVMEhTypeIdOpLowering::matchAndRewrite(
3495 cir::EhTypeIdOp op, OpAdaptor adaptor,
3496 mlir::ConversionPatternRewriter &rewriter) const {
3497 mlir::Value addrOp = mlir::LLVM::AddressOfOp::create(
3498 rewriter, op.getLoc(),
3499 mlir::LLVM::LLVMPointerType::get(rewriter.getContext()),
3500 op.getTypeSymAttr());
3501 rewriter.replaceOpWithNewOp<mlir::LLVM::EhTypeidForOp>(
3502 op, rewriter.getI32Type(), addrOp);
3503 return mlir::success();
3504 }
3505
3506 mlir::LogicalResult CIRToLLVMTrapOpLowering::matchAndRewrite(
3507 cir::TrapOp op, OpAdaptor adaptor,
3508 mlir::ConversionPatternRewriter &rewriter) const {
3509 mlir::Location loc = op->getLoc();
3510 rewriter.eraseOp(op);
3511
3512 mlir::LLVM::Trap::create(rewriter, loc);
3513
3514 // Note that the call to llvm.trap is not a terminator in LLVM dialect.
3515 // So we must emit an additional llvm.unreachable to terminate the current
3516 // block.
3517 mlir::LLVM::UnreachableOp::create(rewriter, loc);
3518
3519 return mlir::success();
3520 }
3521
3522 static mlir::Value
3523 getValueForVTableSymbol(mlir::Operation *op,
3524 mlir::ConversionPatternRewriter &rewriter,
3525 const mlir::TypeConverter *converter,
3526 mlir::FlatSymbolRefAttr nameAttr, mlir::Type &eltType) {
3527 auto module = op->getParentOfType<mlir::ModuleOp>();
3528 mlir::Operation *symbol = mlir::SymbolTable::lookupSymbolIn(module, nameAttr);
3529 if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(symbol)) {
3530 eltType = llvmSymbol.getType();
3531 } else if (auto cirSymbol = mlir::dyn_cast<cir::GlobalOp>(symbol)) {
3532 eltType = converter->convertType(cirSymbol.getSymType());
3533 } else {
3534 op->emitError() << "unexpected symbol type for " << symbol;
3535 return {};
3536 }
3537
3538 return mlir::LLVM::AddressOfOp::create(
3539 rewriter, op->getLoc(),
3540 mlir::LLVM::LLVMPointerType::get(op->getContext()), nameAttr.getValue());
3541 }
3542
3543 mlir::LogicalResult CIRToLLVMVTableAddrPointOpLowering::matchAndRewrite(
3544 cir::VTableAddrPointOp op, OpAdaptor adaptor,
3545 mlir::ConversionPatternRewriter &rewriter) const {
3546 const mlir::TypeConverter *converter = getTypeConverter();
3547 mlir::Type targetType = converter->convertType(op.getType());
3548 llvm::SmallVector<mlir::LLVM::GEPArg> offsets;
3549 mlir::Type eltType;
3550 mlir::Value symAddr = getValueForVTableSymbol(op, rewriter, converter,
3551 op.getNameAttr(), eltType);
3552 if (!symAddr)
3553 return op.emitError() << "Unable to get value for vtable symbol";
3554
3555 offsets = llvm::SmallVector<mlir::LLVM::GEPArg>{
3556 0, op.getAddressPointAttr().getIndex(),
3557 op.getAddressPointAttr().getOffset()};
3558
3559 assert(eltType && "Shouldn't ever be missing an eltType here");
3560 mlir::LLVM::GEPNoWrapFlags inboundsNuw =
3561 mlir::LLVM::GEPNoWrapFlags::inbounds | mlir::LLVM::GEPNoWrapFlags::nuw;
3562 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(op, targetType, eltType,
3563 symAddr, offsets, inboundsNuw);
3564 return mlir::success();
3565 }
3566
3567 mlir::LogicalResult CIRToLLVMVTableGetVPtrOpLowering::matchAndRewrite(
3568 cir::VTableGetVPtrOp op, OpAdaptor adaptor,
3569 mlir::ConversionPatternRewriter &rewriter) const {
3570 // cir.vtable.get_vptr is equivalent to a bitcast from the source object
3571 // pointer to the vptr type. Since the LLVM dialect uses opaque pointers
3572 // we can just replace uses of this operation with the original pointer.
3573 mlir::Value srcVal = adaptor.getSrc();
3574 rewriter.replaceOp(op, srcVal);
3575 return mlir::success();
3576 }
3577
3578 mlir::LogicalResult CIRToLLVMVTableGetVirtualFnAddrOpLowering::matchAndRewrite(
3579 cir::VTableGetVirtualFnAddrOp op, OpAdaptor adaptor,
3580 mlir::ConversionPatternRewriter &rewriter) const {
3581 mlir::Type targetType = getTypeConverter()->convertType(op.getType());
3582 auto eltType = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
3583 llvm::SmallVector<mlir::LLVM::GEPArg> offsets =
3584 llvm::SmallVector<mlir::LLVM::GEPArg>{op.getIndex()};
3585 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
3586 op, targetType, eltType, adaptor.getVptr(), offsets,
3587 mlir::LLVM::GEPNoWrapFlags::inbounds);
3588 return mlir::success();
3589 }
3590
3591 mlir::LogicalResult CIRToLLVMVTTAddrPointOpLowering::matchAndRewrite(
3592 cir::VTTAddrPointOp op, OpAdaptor adaptor,
3593 mlir::ConversionPatternRewriter &rewriter) const {
3594 const mlir::Type resultType = getTypeConverter()->convertType(op.getType());
3595 llvm::SmallVector<mlir::LLVM::GEPArg> offsets;
3596 mlir::Type eltType;
3597 mlir::Value llvmAddr = adaptor.getSymAddr();
3598
3599 if (op.getSymAddr()) {
3600 if (op.getOffset() == 0) {
3601 rewriter.replaceOp(op, {llvmAddr});
3602 return mlir::success();
3603 }
3604
3605 offsets.push_back(adaptor.getOffset());
3606 eltType = mlir::LLVM::LLVMPointerType::get(rewriter.getContext());
3607 } else {
3608 llvmAddr = getValueForVTableSymbol(op, rewriter, getTypeConverter(),
3609 op.getNameAttr(), eltType);
3610 assert(eltType && "Shouldn't ever be missing an eltType here");
3611 offsets.push_back(0);
3612 offsets.push_back(adaptor.getOffset());
3613 }
3614 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
3615 op, resultType, eltType, llvmAddr, offsets,
3616 mlir::LLVM::GEPNoWrapFlags::inbounds);
3617 return mlir::success();
3618 }
3619
3620 mlir::LogicalResult CIRToLLVMStackSaveOpLowering::matchAndRewrite(
3621 cir::StackSaveOp op, OpAdaptor adaptor,
3622 mlir::ConversionPatternRewriter &rewriter) const {
3623 const mlir::Type ptrTy = getTypeConverter()->convertType(op.getType());
3624 rewriter.replaceOpWithNewOp<mlir::LLVM::StackSaveOp>(op, ptrTy);
3625 return mlir::success();
3626 }
3627
3628 mlir::LogicalResult CIRToLLVMStackRestoreOpLowering::matchAndRewrite(
3629 cir::StackRestoreOp op, OpAdaptor adaptor,
3630 mlir::ConversionPatternRewriter &rewriter) const {
3631 rewriter.replaceOpWithNewOp<mlir::LLVM::StackRestoreOp>(op, adaptor.getPtr());
3632 return mlir::success();
3633 }
3634
3635 mlir::LogicalResult CIRToLLVMVecCreateOpLowering::matchAndRewrite(
3636 cir::VecCreateOp op, OpAdaptor adaptor,
3637 mlir::ConversionPatternRewriter &rewriter) const {
3638 // Start with an 'undef' value for the vector. Then 'insertelement' for
3639 // each of the vector elements.
3640 const auto vecTy = mlir::cast<cir::VectorType>(op.getType());
3641 const mlir::Type llvmTy = typeConverter->convertType(vecTy);
3642 const mlir::Location loc = op.getLoc();
3643 mlir::Value result = mlir::LLVM::PoisonOp::create(rewriter, loc, llvmTy);
3644 assert(vecTy.getSize() == op.getElements().size() &&
3645 "cir.vec.create op count doesn't match vector type elements count");
3646
3647 for (uint64_t i = 0; i < vecTy.getSize(); ++i) {
3648 const mlir::Value indexValue =
3649 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), i);
3650 result = mlir::LLVM::InsertElementOp::create(
3651 rewriter, loc, result, adaptor.getElements()[i], indexValue);
3652 }
3653
3654 rewriter.replaceOp(op, result);
3655 return mlir::success();
3656 }
3657
3658 mlir::LogicalResult CIRToLLVMVecExtractOpLowering::matchAndRewrite(
3659 cir::VecExtractOp op, OpAdaptor adaptor,
3660 mlir::ConversionPatternRewriter &rewriter) const {
3661 rewriter.replaceOpWithNewOp<mlir::LLVM::ExtractElementOp>(
3662 op, adaptor.getVec(), adaptor.getIndex());
3663 return mlir::success();
3664 }
3665
3666 mlir::LogicalResult CIRToLLVMVecInsertOpLowering::matchAndRewrite(
3667 cir::VecInsertOp op, OpAdaptor adaptor,
3668 mlir::ConversionPatternRewriter &rewriter) const {
3669 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertElementOp>(
3670 op, adaptor.getVec(), adaptor.getValue(), adaptor.getIndex());
3671 return mlir::success();
3672 }
3673
3674 mlir::LogicalResult CIRToLLVMVecCmpOpLowering::matchAndRewrite(
3675 cir::VecCmpOp op, OpAdaptor adaptor,
3676 mlir::ConversionPatternRewriter &rewriter) const {
3677 mlir::Type elementType = elementTypeIfVector(op.getLhs().getType());
3678 mlir::Value bitResult;
3679 if (auto intType = mlir::dyn_cast<cir::IntType>(elementType)) {
3680 bitResult = mlir::LLVM::ICmpOp::create(
3681 rewriter, op.getLoc(),
3682 convertCmpKindToICmpPredicate(op.getKind(), intType.isSigned()),
3683 adaptor.getLhs(), adaptor.getRhs());
3684 } else if (mlir::isa<cir::FPTypeInterface>(elementType)) {
3685 bitResult = mlir::LLVM::FCmpOp::create(
3686 rewriter, op.getLoc(), convertCmpKindToFCmpPredicate(op.getKind()),
3687 adaptor.getLhs(), adaptor.getRhs());
3688 } else {
3689 return op.emitError() << "unsupported type for VecCmpOp: " << elementType;
3690 }
3691
3692 // LLVM IR vector comparison returns a vector of i1. This one-bit vector
3693 // must be sign-extended to the correct result type, unless a vector of i1 is
3694 // the type we need.
3695 if (cast<cir::IntType>(cast<cir::VectorType>(op.getType()).getElementType())
3696 .getWidth() > 1)
3697 rewriter.replaceOpWithNewOp<mlir::LLVM::SExtOp>(
3698 op, typeConverter->convertType(op.getType()), bitResult);
3699 else
3700 rewriter.replaceOp(op, bitResult);
3701 return mlir::success();
3702 }
3703
3704 mlir::LogicalResult CIRToLLVMVecSplatOpLowering::matchAndRewrite(
3705 cir::VecSplatOp op, OpAdaptor adaptor,
3706 mlir::ConversionPatternRewriter &rewriter) const {
3707 // Vector splat can be implemented with an `insertelement` and a
3708 // `shufflevector`, which is better than an `insertelement` for each
3709 // element in the vector. Start with an undef vector. Insert the value into
3710 // the first element. Then use a `shufflevector` with a mask of all 0 to
3711 // fill out the entire vector with that value.
3712 cir::VectorType vecTy = op.getType();
3713 mlir::Type llvmTy = typeConverter->convertType(vecTy);
3714 mlir::Location loc = op.getLoc();
3715 mlir::Value poison = mlir::LLVM::PoisonOp::create(rewriter, loc, llvmTy);
3716
3717 mlir::Value elementValue = adaptor.getValue();
3718 if (elementValue.getDefiningOp<mlir::LLVM::PoisonOp>()) {
3719 // If the splat value is poison, then we can just use poison value
3720 // for the entire vector.
3721 rewriter.replaceOp(op, poison);
3722 return mlir::success();
3723 }
3724
3725 if (auto constValue = elementValue.getDefiningOp<mlir::LLVM::ConstantOp>()) {
3726 if (auto intAttr = dyn_cast<mlir::IntegerAttr>(constValue.getValue())) {
3727 mlir::DenseIntElementsAttr denseVec = mlir::DenseIntElementsAttr::get(
3728 mlir::cast<mlir::ShapedType>(llvmTy), intAttr.getValue());
3729 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
3730 op, denseVec.getType(), denseVec);
3731 return mlir::success();
3732 }
3733
3734 if (auto fpAttr = dyn_cast<mlir::FloatAttr>(constValue.getValue())) {
3735 mlir::DenseFPElementsAttr denseVec = mlir::DenseFPElementsAttr::get(
3736 mlir::cast<mlir::ShapedType>(llvmTy), fpAttr.getValue());
3737 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(
3738 op, denseVec.getType(), denseVec);
3739 return mlir::success();
3740 }
3741 }
3742
3743 mlir::Value indexValue =
3744 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), 0);
3745 mlir::Value oneElement = mlir::LLVM::InsertElementOp::create(
3746 rewriter, loc, poison, elementValue, indexValue);
3747 SmallVector<int32_t> zeroValues(vecTy.getSize(), 0);
3748 rewriter.replaceOpWithNewOp<mlir::LLVM::ShuffleVectorOp>(op, oneElement,
3749 poison, zeroValues);
3750 return mlir::success();
3751 }
3752
3753 mlir::LogicalResult CIRToLLVMVecShuffleOpLowering::matchAndRewrite(
3754 cir::VecShuffleOp op, OpAdaptor adaptor,
3755 mlir::ConversionPatternRewriter &rewriter) const {
3756 // LLVM::ShuffleVectorOp takes an ArrayRef of int for the list of indices.
3757 // Convert the ClangIR ArrayAttr of IntAttr constants into a
3758 // SmallVector<int>.
3759 SmallVector<int, 8> indices;
3760 std::transform(
3761 op.getIndices().begin(), op.getIndices().end(),
3762 std::back_inserter(indices), [](mlir::Attribute intAttr) {
3763 return mlir::cast<cir::IntAttr>(intAttr).getValue().getSExtValue();
3764 });
3765 rewriter.replaceOpWithNewOp<mlir::LLVM::ShuffleVectorOp>(
3766 op, adaptor.getVec1(), adaptor.getVec2(), indices);
3767 return mlir::success();
3768 }
3769
3770 mlir::LogicalResult CIRToLLVMVecShuffleDynamicOpLowering::matchAndRewrite(
3771 cir::VecShuffleDynamicOp op, OpAdaptor adaptor,
3772 mlir::ConversionPatternRewriter &rewriter) const {
3773 // LLVM IR does not have an operation that corresponds to this form of
3774 // the built-in.
3775 // __builtin_shufflevector(V, I)
3776 // is implemented as this pseudocode, where the for loop is unrolled
3777 // and N is the number of elements:
3778 //
3779 // result = undef
3780 // maskbits = NextPowerOf2(N - 1)
3781 // masked = I & maskbits
3782 // for (i in 0 <= i < N)
3783 // result[i] = V[masked[i]]
3784 mlir::Location loc = op.getLoc();
3785 mlir::Value input = adaptor.getVec();
3786 mlir::Type llvmIndexVecType =
3787 getTypeConverter()->convertType(op.getIndices().getType());
3788 mlir::Type llvmIndexType = getTypeConverter()->convertType(
3789 elementTypeIfVector(op.getIndices().getType()));
3790 uint64_t numElements =
3791 mlir::cast<cir::VectorType>(op.getVec().getType()).getSize();
3792
3793 uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3794 mlir::Value maskValue = mlir::LLVM::ConstantOp::create(
3795 rewriter, loc, llvmIndexType,
3796 rewriter.getIntegerAttr(llvmIndexType, maskBits));
3797 mlir::Value maskVector =
3798 mlir::LLVM::UndefOp::create(rewriter, loc, llvmIndexVecType);
3799
3800 for (uint64_t i = 0; i < numElements; ++i) {
3801 mlir::Value idxValue =
3802 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), i);
3803 maskVector = mlir::LLVM::InsertElementOp::create(rewriter, loc, maskVector,
3804 maskValue, idxValue);
3805 }
3806
3807 mlir::Value maskedIndices = mlir::LLVM::AndOp::create(
3808 rewriter, loc, llvmIndexVecType, adaptor.getIndices(), maskVector);
3809 mlir::Value result = mlir::LLVM::UndefOp::create(
3810 rewriter, loc, getTypeConverter()->convertType(op.getVec().getType()));
3811 for (uint64_t i = 0; i < numElements; ++i) {
3812 mlir::Value iValue =
3813 mlir::LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(), i);
3814 mlir::Value indexValue = mlir::LLVM::ExtractElementOp::create(
3815 rewriter, loc, maskedIndices, iValue);
3816 mlir::Value valueAtIndex =
3817 mlir::LLVM::ExtractElementOp::create(rewriter, loc, input, indexValue);
3818 result = mlir::LLVM::InsertElementOp::create(rewriter, loc, result,
3819 valueAtIndex, iValue);
3820 }
3821 rewriter.replaceOp(op, result);
3822 return mlir::success();
3823 }
3824
3825 mlir::LogicalResult CIRToLLVMVecTernaryOpLowering::matchAndRewrite(
3826 cir::VecTernaryOp op, OpAdaptor adaptor,
3827 mlir::ConversionPatternRewriter &rewriter) const {
3828 // Convert `cond` into a vector of i1, then use that in a `select` op.
3829 mlir::Value bitVec = mlir::LLVM::ICmpOp::create(
3830 rewriter, op.getLoc(), mlir::LLVM::ICmpPredicate::ne, adaptor.getCond(),
3831 mlir::LLVM::ZeroOp::create(
3832 rewriter, op.getCond().getLoc(),
3833 typeConverter->convertType(op.getCond().getType())));
3834 rewriter.replaceOpWithNewOp<mlir::LLVM::SelectOp>(
3835 op, bitVec, adaptor.getLhs(), adaptor.getRhs());
3836 return mlir::success();
3837 }
3838
3839 mlir::LogicalResult CIRToLLVMComplexAddOpLowering::matchAndRewrite(
3840 cir::ComplexAddOp op, OpAdaptor adaptor,
3841 mlir::ConversionPatternRewriter &rewriter) const {
3842 mlir::Value lhs = adaptor.getLhs();
3843 mlir::Value rhs = adaptor.getRhs();
3844 mlir::Location loc = op.getLoc();
3845
3846 auto complexType = mlir::cast<cir::ComplexType>(op.getLhs().getType());
3847 mlir::Type complexElemTy =
3848 getTypeConverter()->convertType(complexType.getElementType());
3849 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
3850 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
3851 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
3852 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
3853 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
3854 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
3855 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
3856 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
3857
3858 mlir::Value newReal;
3859 mlir::Value newImag;
3860 if (complexElemTy.isInteger()) {
3861 newReal = mlir::LLVM::AddOp::create(rewriter, loc, complexElemTy, lhsReal,
3862 rhsReal);
3863 newImag = mlir::LLVM::AddOp::create(rewriter, loc, complexElemTy, lhsImag,
3864 rhsImag);
3865 } else {
3866 assert(!cir::MissingFeatures::fastMathFlags());
3867 assert(!cir::MissingFeatures::fpConstraints());
3868 newReal = mlir::LLVM::FAddOp::create(rewriter, loc, complexElemTy, lhsReal,
3869 rhsReal);
3870 newImag = mlir::LLVM::FAddOp::create(rewriter, loc, complexElemTy, lhsImag,
3871 rhsImag);
3872 }
3873
3874 mlir::Type complexLLVMTy =
3875 getTypeConverter()->convertType(op.getResult().getType());
3876 auto initialComplex =
3877 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), complexLLVMTy);
3878
3879 auto realComplex = mlir::LLVM::InsertValueOp::create(
3880 rewriter, op->getLoc(), initialComplex, newReal, ArrayRef(int64_t{0}));
3881
3882 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
3883 op, realComplex, newImag, ArrayRef(int64_t{1}));
3884
3885 return mlir::success();
3886 }
3887
3888 mlir::LogicalResult CIRToLLVMComplexCreateOpLowering::matchAndRewrite(
3889 cir::ComplexCreateOp op, OpAdaptor adaptor,
3890 mlir::ConversionPatternRewriter &rewriter) const {
3891 mlir::Type complexLLVMTy =
3892 getTypeConverter()->convertType(op.getResult().getType());
3893 auto initialComplex =
3894 mlir::LLVM::UndefOp::create(rewriter, op->getLoc(), complexLLVMTy);
3895
3896 auto realComplex = mlir::LLVM::InsertValueOp::create(
3897 rewriter, op->getLoc(), initialComplex, adaptor.getReal(),
3898 ArrayRef(int64_t{0}));
3899
3900 auto complex = mlir::LLVM::InsertValueOp::create(
3901 rewriter, op->getLoc(), realComplex, adaptor.getImag(),
3902 ArrayRef(int64_t{1}));
3903
3904 rewriter.replaceOp(op, complex);
3905 return mlir::success();
3906 }
3907
3908 mlir::LogicalResult CIRToLLVMComplexRealOpLowering::matchAndRewrite(
3909 cir::ComplexRealOp op, OpAdaptor adaptor,
3910 mlir::ConversionPatternRewriter &rewriter) const {
3911 mlir::Type resultLLVMTy = getTypeConverter()->convertType(op.getType());
3912 mlir::Value operand = adaptor.getOperand();
3913 if (mlir::isa<cir::ComplexType>(op.getOperand().getType())) {
3914 operand = mlir::LLVM::ExtractValueOp::create(
3915 rewriter, op.getLoc(), resultLLVMTy, operand,
3916 llvm::ArrayRef<std::int64_t>{0});
3917 }
3918 rewriter.replaceOp(op, operand);
3919 return mlir::success();
3920 }
3921
3922 mlir::LogicalResult CIRToLLVMComplexSubOpLowering::matchAndRewrite(
3923 cir::ComplexSubOp op, OpAdaptor adaptor,
3924 mlir::ConversionPatternRewriter &rewriter) const {
3925 mlir::Value lhs = adaptor.getLhs();
3926 mlir::Value rhs = adaptor.getRhs();
3927 mlir::Location loc = op.getLoc();
3928
3929 auto complexType = mlir::cast<cir::ComplexType>(op.getLhs().getType());
3930 mlir::Type complexElemTy =
3931 getTypeConverter()->convertType(complexType.getElementType());
3932 auto lhsReal = mlir::LLVM::ExtractValueOp::create(
3933 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{0}));
3934 auto lhsImag = mlir::LLVM::ExtractValueOp::create(
3935 rewriter, loc, complexElemTy, lhs, ArrayRef(int64_t{1}));
3936 auto rhsReal = mlir::LLVM::ExtractValueOp::create(
3937 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{0}));
3938 auto rhsImag = mlir::LLVM::ExtractValueOp::create(
3939 rewriter, loc, complexElemTy, rhs, ArrayRef(int64_t{1}));
3940
3941 mlir::Value newReal;
3942 mlir::Value newImag;
3943 if (complexElemTy.isInteger()) {
3944 newReal = mlir::LLVM::SubOp::create(rewriter, loc, complexElemTy, lhsReal,
3945 rhsReal);
3946 newImag = mlir::LLVM::SubOp::create(rewriter, loc, complexElemTy, lhsImag,
3947 rhsImag);
3948 } else {
3949 assert(!cir::MissingFeatures::fastMathFlags());
3950 assert(!cir::MissingFeatures::fpConstraints());
3951 newReal = mlir::LLVM::FSubOp::create(rewriter, loc, complexElemTy, lhsReal,
3952 rhsReal);
3953 newImag = mlir::LLVM::FSubOp::create(rewriter, loc, complexElemTy, lhsImag,
3954 rhsImag);
3955 }
3956
3957 mlir::Type complexLLVMTy =
3958 getTypeConverter()->convertType(op.getResult().getType());
3959 auto initialComplex =
3960 mlir::LLVM::PoisonOp::create(rewriter, op->getLoc(), complexLLVMTy);
3961
3962 auto realComplex = mlir::LLVM::InsertValueOp::create(
3963 rewriter, op->getLoc(), initialComplex, newReal, ArrayRef(int64_t{0}));
3964
3965 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
3966 op, realComplex, newImag, ArrayRef(int64_t{1}));
3967
3968 return mlir::success();
3969 }
3970
3971 mlir::LogicalResult CIRToLLVMComplexImagOpLowering::matchAndRewrite(
3972 cir::ComplexImagOp op, OpAdaptor adaptor,
3973 mlir::ConversionPatternRewriter &rewriter) const {
3974 mlir::Type resultLLVMTy = getTypeConverter()->convertType(op.getType());
3975 mlir::Value operand = adaptor.getOperand();
3976 mlir::Location loc = op.getLoc();
3977
3978 if (mlir::isa<cir::ComplexType>(op.getOperand().getType())) {
3979 operand = mlir::LLVM::ExtractValueOp::create(
3980 rewriter, loc, resultLLVMTy, operand, llvm::ArrayRef<std::int64_t>{1});
3981 } else {
3982 mlir::TypedAttr zeroAttr = rewriter.getZeroAttr(resultLLVMTy);
3983 operand =
3984 mlir::LLVM::ConstantOp::create(rewriter, loc, resultLLVMTy, zeroAttr);
3985 }
3986
3987 rewriter.replaceOp(op, operand);
3988 return mlir::success();
3989 }
3990
3991 mlir::IntegerType computeBitfieldIntType(mlir::Type storageType,
3992 mlir::MLIRContext *context,
3993 unsigned &storageSize) {
3994 return TypeSwitch<mlir::Type, mlir::IntegerType>(storageType)
3995 .Case<cir::ArrayType>([&](cir::ArrayType atTy) {
3996 storageSize = atTy.getSize() * 8;
3997 return mlir::IntegerType::get(context, storageSize);
3998 })
3999 .Case<cir::IntType>([&](cir::IntType intTy) {
4000 storageSize = intTy.getWidth();
4001 return mlir::IntegerType::get(context, storageSize);
4002 })
4003 .Default([](mlir::Type) -> mlir::IntegerType {
4004 llvm_unreachable(
4005 "Either ArrayType or IntType expected for bitfields storage");
4006 });
4007 }
4008
4009 mlir::LogicalResult CIRToLLVMSetBitfieldOpLowering::matchAndRewrite(
4010 cir::SetBitfieldOp op, OpAdaptor adaptor,
4011 mlir::ConversionPatternRewriter &rewriter) const {
4012 mlir::OpBuilder::InsertionGuard guard(rewriter);
4013 rewriter.setInsertionPoint(op);
4014
4015 cir::BitfieldInfoAttr info = op.getBitfieldInfo();
4016 uint64_t size = info.getSize();
4017 uint64_t offset = info.getOffset();
4018 mlir::Type storageType = info.getStorageType();
4019 mlir::MLIRContext *context = storageType.getContext();
4020
4021 unsigned storageSize = 0;
4022
4023 mlir::IntegerType intType =
4024 computeBitfieldIntType(storageType, context, storageSize);
4025
4026 mlir::Value srcVal = createIntCast(rewriter, adaptor.getSrc(), intType);
4027 unsigned srcWidth = storageSize;
4028 mlir::Value resultVal = srcVal;
4029
4030 if (storageSize != size) {
4031 assert(storageSize > size && "Invalid bitfield size.");
4032
4033 mlir::Value val = mlir::LLVM::LoadOp::create(
4034 rewriter, op.getLoc(), intType, adaptor.getAddr(), op.getAlignment(),
4035 op.getIsVolatile());
4036
4037 srcVal =
4038 createAnd(rewriter, srcVal, llvm::APInt::getLowBitsSet(srcWidth, size));
4039 resultVal = srcVal;
4040 srcVal = createShL(rewriter, srcVal, offset);
4041
4042 // Mask out the original value.
4043 val = createAnd(rewriter, val,
4044 ~llvm::APInt::getBitsSet(srcWidth, offset, offset + size));
4045
4046 // Or together the unchanged values and the source value.
4047 srcVal = mlir::LLVM::OrOp::create(rewriter, op.getLoc(), val, srcVal);
4048 }
4049
4050 mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), srcVal, adaptor.getAddr(),
4051 op.getAlignment(), op.getIsVolatile());
4052
4053 mlir::Type resultTy = getTypeConverter()->convertType(op.getType());
4054
4055 if (info.getIsSigned()) {
4056 assert(size <= storageSize);
4057 unsigned highBits = storageSize - size;
4058
4059 if (highBits) {
4060 resultVal = createShL(rewriter, resultVal, highBits);
4061 resultVal = createAShR(rewriter, resultVal, highBits);
4062 }
4063 }
4064
4065 resultVal = createIntCast(rewriter, resultVal,
4066 mlir::cast<mlir::IntegerType>(resultTy),
4067 info.getIsSigned());
4068
4069 rewriter.replaceOp(op, resultVal);
4070 return mlir::success();
4071 }
4072
4073 mlir::LogicalResult CIRToLLVMComplexImagPtrOpLowering::matchAndRewrite(
4074 cir::ComplexImagPtrOp op, OpAdaptor adaptor,
4075 mlir::ConversionPatternRewriter &rewriter) const {
4076 cir::PointerType operandTy = op.getOperand().getType();
4077 mlir::Type resultLLVMTy = getTypeConverter()->convertType(op.getType());
4078 mlir::Type elementLLVMTy =
4079 getTypeConverter()->convertType(operandTy.getPointee());
4080
4081 mlir::LLVM::GEPArg gepIndices[2] = {{0}, {1}};
4082 mlir::LLVM::GEPNoWrapFlags inboundsNuw =
4083 mlir::LLVM::GEPNoWrapFlags::inbounds | mlir::LLVM::GEPNoWrapFlags::nuw;
4084 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
4085 op, resultLLVMTy, elementLLVMTy, adaptor.getOperand(), gepIndices,
4086 inboundsNuw);
4087 return mlir::success();
4088 }
4089
4090 mlir::LogicalResult CIRToLLVMComplexRealPtrOpLowering::matchAndRewrite(
4091 cir::ComplexRealPtrOp op, OpAdaptor adaptor,
4092 mlir::ConversionPatternRewriter &rewriter) const {
4093 cir::PointerType operandTy = op.getOperand().getType();
4094 mlir::Type resultLLVMTy = getTypeConverter()->convertType(op.getType());
4095 mlir::Type elementLLVMTy =
4096 getTypeConverter()->convertType(operandTy.getPointee());
4097
4098 mlir::LLVM::GEPArg gepIndices[2] = {0, 0};
4099 mlir::LLVM::GEPNoWrapFlags inboundsNuw =
4100 mlir::LLVM::GEPNoWrapFlags::inbounds | mlir::LLVM::GEPNoWrapFlags::nuw;
4101 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
4102 op, resultLLVMTy, elementLLVMTy, adaptor.getOperand(), gepIndices,
4103 inboundsNuw);
4104 return mlir::success();
4105 }
4106
4107 mlir::LogicalResult CIRToLLVMGetBitfieldOpLowering::matchAndRewrite(
4108 cir::GetBitfieldOp op, OpAdaptor adaptor,
4109 mlir::ConversionPatternRewriter &rewriter) const {
4110
4111 mlir::OpBuilder::InsertionGuard guard(rewriter);
4112 rewriter.setInsertionPoint(op);
4113
4114 cir::BitfieldInfoAttr info = op.getBitfieldInfo();
4115 uint64_t size = info.getSize();
4116 uint64_t offset = info.getOffset();
4117 mlir::Type storageType = info.getStorageType();
4118 mlir::MLIRContext *context = storageType.getContext();
4119 unsigned storageSize = 0;
4120
4121 mlir::IntegerType intType =
4122 computeBitfieldIntType(storageType, context, storageSize);
4123
4124 mlir::Value val = mlir::LLVM::LoadOp::create(
4125 rewriter, op.getLoc(), intType, adaptor.getAddr(), op.getAlignment(),
4126 op.getIsVolatile());
4127 val = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), intType, val);
4128
4129 if (info.getIsSigned()) {
4130 assert(static_cast<unsigned>(offset + size) <= storageSize);
4131 unsigned highBits = storageSize - offset - size;
4132 val = createShL(rewriter, val, highBits);
4133 val = createAShR(rewriter, val, offset + highBits);
4134 } else {
4135 val = createLShR(rewriter, val, offset);
4136
4137 if (static_cast<unsigned>(offset) + size < storageSize)
4138 val = createAnd(rewriter, val,
4139 llvm::APInt::getLowBitsSet(storageSize, size));
4140 }
4141
4142 mlir::Type resTy = getTypeConverter()->convertType(op.getType());
4143 mlir::Value newOp = createIntCast(
4144 rewriter, val, mlir::cast<mlir::IntegerType>(resTy), info.getIsSigned());
4145 rewriter.replaceOp(op, newOp);
4146 return mlir::success();
4147 }
4148
4149 mlir::LogicalResult CIRToLLVMIsConstantOpLowering::matchAndRewrite(
4150 cir::IsConstantOp op, OpAdaptor adaptor,
4151 mlir::ConversionPatternRewriter &rewriter) const {
4152 rewriter.replaceOpWithNewOp<mlir::LLVM::IsConstantOp>(op, adaptor.getVal());
4153 return mlir::success();
4154 }
4155
4156 mlir::LogicalResult CIRToLLVMInlineAsmOpLowering::matchAndRewrite(
4157 cir::InlineAsmOp op, OpAdaptor adaptor,
4158 mlir::ConversionPatternRewriter &rewriter) const {
4159 mlir::Type llResTy;
4160 if (op.getNumResults())
4161 llResTy = getTypeConverter()->convertType(op.getType(0));
4162
4163 cir::AsmFlavor dialect = op.getAsmFlavor();
4164 mlir::LLVM::AsmDialect llDialect = dialect == cir::AsmFlavor::x86_att
4165 ? mlir::LLVM::AsmDialect::AD_ATT
4166 : mlir::LLVM::AsmDialect::AD_Intel;
4167
4168 SmallVector<mlir::Attribute> opAttrs;
4169 StringRef llvmAttrName = mlir::LLVM::InlineAsmOp::getElementTypeAttrName();
4170
4171 // this is for the lowering to LLVM from LLVM dialect. Otherwise, if we
4172 // don't have the result (i.e. void type as a result of operation), the
4173 // element type attribute will be attached to the whole instruction, but not
4174 // to the operand
4175 if (!op.getNumResults())
4176 opAttrs.push_back(mlir::Attribute());
4177
4178 SmallVector<mlir::Value> llvmOperands;
4179 SmallVector<mlir::Value> cirOperands;
4180 for (auto const &[llvmOp, cirOp] :
4181 zip(adaptor.getAsmOperands(), op.getAsmOperands())) {
4182 append_range(llvmOperands, llvmOp);
4183 append_range(cirOperands, cirOp);
4184 }
4185
4186 // so far we infer the llvm dialect element type attr from
4187 // CIR operand type.
4188 for (auto const &[cirOpAttr, cirOp] :
4189 zip(op.getOperandAttrs(), cirOperands)) {
4190 if (!cirOpAttr) {
4191 opAttrs.push_back(mlir::Attribute());
4192 continue;
4193 }
4194
4195 llvm::SmallVector<mlir::NamedAttribute, 1> attrs;
4196 cir::PointerType typ = mlir::cast<cir::PointerType>(cirOp.getType());
4197 mlir::TypeAttr typAttr = mlir::TypeAttr::get(convertTypeForMemory(
4198 *getTypeConverter(), dataLayout, typ.getPointee()));
4199
4200 attrs.push_back(rewriter.getNamedAttr(llvmAttrName, typAttr));
4201 mlir::DictionaryAttr newDict = rewriter.getDictionaryAttr(attrs);
4202 opAttrs.push_back(newDict);
4203 }
4204
4205 rewriter.replaceOpWithNewOp<mlir::LLVM::InlineAsmOp>(
4206 op, llResTy, llvmOperands, op.getAsmStringAttr(), op.getConstraintsAttr(),
4207 op.getSideEffectsAttr(),
4208 /*is_align_stack*/ mlir::UnitAttr(),
4209 /*tail_call_kind*/
4210 mlir::LLVM::TailCallKindAttr::get(
4211 getContext(), mlir::LLVM::tailcallkind::TailCallKind::None),
4212 mlir::LLVM::AsmDialectAttr::get(getContext(), llDialect),
4213 rewriter.getArrayAttr(opAttrs));
4214
4215 return mlir::success();
4216 }
4217
4218 mlir::LogicalResult CIRToLLVMVAStartOpLowering::matchAndRewrite(
4219 cir::VAStartOp op, OpAdaptor adaptor,
4220 mlir::ConversionPatternRewriter &rewriter) const {
4221 auto opaquePtr = mlir::LLVM::LLVMPointerType::get(getContext());
4222 auto vaList = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), opaquePtr,
4223 adaptor.getArgList());
4224 rewriter.replaceOpWithNewOp<mlir::LLVM::VaStartOp>(op, vaList);
4225 return mlir::success();
4226 }
4227
4228 mlir::LogicalResult CIRToLLVMVAEndOpLowering::matchAndRewrite(
4229 cir::VAEndOp op, OpAdaptor adaptor,
4230 mlir::ConversionPatternRewriter &rewriter) const {
4231 auto opaquePtr = mlir::LLVM::LLVMPointerType::get(getContext());
4232 auto vaList = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), opaquePtr,
4233 adaptor.getArgList());
4234 rewriter.replaceOpWithNewOp<mlir::LLVM::VaEndOp>(op, vaList);
4235 return mlir::success();
4236 }
4237
4238 mlir::LogicalResult CIRToLLVMVACopyOpLowering::matchAndRewrite(
4239 cir::VACopyOp op, OpAdaptor adaptor,
4240 mlir::ConversionPatternRewriter &rewriter) const {
4241 auto opaquePtr = mlir::LLVM::LLVMPointerType::get(getContext());
4242 auto dstList = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), opaquePtr,
4243 adaptor.getDstList());
4244 auto srcList = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), opaquePtr,
4245 adaptor.getSrcList());
4246 rewriter.replaceOpWithNewOp<mlir::LLVM::VaCopyOp>(op, dstList, srcList);
4247 return mlir::success();
4248 }
4249
4250 mlir::LogicalResult CIRToLLVMVAArgOpLowering::matchAndRewrite(
4251 cir::VAArgOp op, OpAdaptor adaptor,
4252 mlir::ConversionPatternRewriter &rewriter) const {
4253 assert(!cir::MissingFeatures::vaArgABILowering());
4254 auto opaquePtr = mlir::LLVM::LLVMPointerType::get(getContext());
4255 auto vaList = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), opaquePtr,
4256 adaptor.getArgList());
4257
4258 mlir::Type llvmType =
4259 getTypeConverter()->convertType(op->getResultTypes().front());
4260 if (!llvmType)
4261 return mlir::failure();
4262
4263 rewriter.replaceOpWithNewOp<mlir::LLVM::VaArgOp>(op, llvmType, vaList);
4264 return mlir::success();
4265 }
4266
4267 mlir::LogicalResult CIRToLLVMBlockAddressOpLowering::matchAndRewrite(
4268 cir::BlockAddressOp op, OpAdaptor adaptor,
4269 mlir::ConversionPatternRewriter &rewriter) const {
4270 return mlir::failure();
4271 }
4272
4273 mlir::LogicalResult CIRToLLVMIndirectBrOpLowering::matchAndRewrite(
4274 cir::IndirectBrOp op, OpAdaptor adaptor,
4275 mlir::ConversionPatternRewriter &rewriter) const {
4276 return mlir::failure();
4277 }
4278
4279 mlir::LogicalResult CIRToLLVMAwaitOpLowering::matchAndRewrite(
4280 cir::AwaitOp op, OpAdaptor adaptor,
4281 mlir::ConversionPatternRewriter &rewriter) const {
4282 return mlir::failure();
4283 }
4284
4285 mlir::LogicalResult CIRToLLVMCpuIdOpLowering::matchAndRewrite(
4286 cir::CpuIdOp op, OpAdaptor adaptor,
4287 mlir::ConversionPatternRewriter &rewriter) const {
4288 mlir::Type i32Ty = rewriter.getI32Type();
4289 mlir::Type i64Ty = rewriter.getI64Type();
4290 mlir::Type i32PtrTy = mlir::LLVM::LLVMPointerType::get(i32Ty.getContext(), 0);
4291
4292 mlir::Type cpuidRetTy = mlir::LLVM::LLVMStructType::getLiteral(
4293 rewriter.getContext(), {i32Ty, i32Ty, i32Ty, i32Ty});
4294
4295 mlir::Value functionId = adaptor.getFunctionId();
4296 mlir::Value subFunctionId = adaptor.getSubFunctionId();
4297
4298 StringRef asmString, constraints;
4299 mlir::ModuleOp moduleOp = op->getParentOfType<mlir::ModuleOp>();
4300 llvm::Triple triple(
4301 mlir::cast<mlir::StringAttr>(
4302 moduleOp->getAttr(cir::CIRDialect::getTripleAttrName()))
4303 .getValue());
4304 if (triple.getArch() == llvm::Triple::x86) {
4305 asmString = "cpuid";
4306 constraints = "={ax},={bx},={cx},={dx},{ax},{cx}";
4307 } else {
4308 // x86-64 uses %rbx as the base register, so preserve it.
4309 asmString = "xchgq %rbx, ${1:q}\n"
4310 "cpuid\n"
4311 "xchgq %rbx, ${1:q}";
4312 constraints = "={ax},=r,={cx},={dx},0,2";
4313 }
4314
4315 mlir::Value inlineAsm =
4316 mlir::LLVM::InlineAsmOp::create(
4317 rewriter, op.getLoc(), cpuidRetTy, {functionId, subFunctionId},
4318 rewriter.getStringAttr(asmString),
4319 rewriter.getStringAttr(constraints),
4320 /*has_side_effects=*/mlir::UnitAttr{},
4321 /*is_align_stack=*/mlir::UnitAttr{},
4322 /*tail_call_kind=*/mlir::LLVM::TailCallKindAttr{},
4323 /*asm_dialect=*/mlir::LLVM::AsmDialectAttr{},
4324 /*operand_attrs=*/mlir::ArrayAttr{})
4325 .getResult(0);
4326
4327 mlir::Value basePtr = adaptor.getCpuInfo();
4328
4329 mlir::DataLayout layout(op->getParentOfType<mlir::ModuleOp>());
4330 unsigned alignment = layout.getTypeABIAlignment(i32Ty);
4331 for (unsigned i = 0; i < 4; i++) {
4332 mlir::Value extracted =
4333 mlir::LLVM::ExtractValueOp::create(rewriter, op.getLoc(), inlineAsm, i)
4334 .getResult();
4335 mlir::Value index = mlir::LLVM::ConstantOp::create(
4336 rewriter, op.getLoc(), i64Ty, rewriter.getI64IntegerAttr(i));
4337 llvm::SmallVector<mlir::Value, 1> gepIndices = {index};
4338 mlir::Value storePtr = mlir::LLVM::GEPOp::create(
4339 rewriter, op.getLoc(), i32PtrTy, i32Ty, basePtr,
4340 gepIndices, mlir::LLVM::GEPNoWrapFlags::none)
4341 .getResult();
4342 mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), extracted, storePtr,
4343 alignment);
4344 }
4345
4346 rewriter.eraseOp(op);
4347 return mlir::success();
4348 }
4349
4350 std::unique_ptr<mlir::Pass> createConvertCIRToLLVMPass() {
4351 return std::make_unique<ConvertCIRToLLVMPass>();
4352 }
4353
4354 void populateCIRToLLVMPasses(mlir::OpPassManager &pm) {
4355 mlir::populateCIRPreLoweringPasses(pm);
4356 pm.addPass(createConvertCIRToLLVMPass());
4357 }
4358
4359 std::unique_ptr<llvm::Module>
4360 lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp mlirModule, LLVMContext &llvmCtx) {
4361 llvm::TimeTraceScope scope("lower from CIR to LLVM directly");
4362
4363 mlir::MLIRContext *mlirCtx = mlirModule.getContext();
4364
4365 mlir::PassManager pm(mlirCtx);
4366 populateCIRToLLVMPasses(pm);
4367
4368 (void)mlir::applyPassManagerCLOptions(pm);
4369
4370 if (mlir::failed(pm.run(mlirModule))) {
4371 // FIXME: Handle any errors where they occurs and return a nullptr here.
4372 report_fatal_error(
4373 "The pass manager failed to lower CIR to LLVMIR dialect!");
4374 }
4375
4376 mlir::registerBuiltinDialectTranslation(*mlirCtx);
4377 mlir::registerLLVMDialectTranslation(*mlirCtx);
4378 mlir::registerCIRDialectTranslation(*mlirCtx);
4379
4380 llvm::TimeTraceScope translateScope("translateModuleToLLVMIR");
4381
4382 StringRef moduleName = mlirModule.getName().value_or("CIRToLLVMModule");
4383 std::unique_ptr<llvm::Module> llvmModule =
4384 mlir::translateModuleToLLVMIR(mlirModule, llvmCtx, moduleName);
4385
4386 if (!llvmModule) {
4387 // FIXME: Handle any errors where they occurs and return a nullptr here.
4388 report_fatal_error("Lowering from LLVMIR dialect to llvm IR failed!");
4389 }
4390
4391 return llvmModule;
4392 }
4393 } // namespace direct
4394 } // namespace cir