10#include "mlir/IR/Attributes.h"
20#include "llvm/Support/Path.h"
28#define GEN_PASS_DEF_LOWERINGPREPARE
29#include "clang/CIR/Dialect/Passes.h.inc"
33 SmallString<128> fileName;
35 if (mlirModule.getSymName())
36 fileName = llvm::sys::path::filename(mlirModule.getSymName()->str());
41 for (
size_t i = 0; i < fileName.size(); ++i) {
53 mlir::SymbolRefAttr sym = llvm::dyn_cast_if_present<mlir::SymbolRefAttr>(
54 callOp.getCallableForCallee());
57 return dyn_cast_or_null<cir::FuncOp>(
58 mlir::SymbolTable::lookupNearestSymbolFrom(callOp, sym));
62struct LoweringPreparePass
63 :
public impl::LoweringPrepareBase<LoweringPreparePass> {
64 LoweringPreparePass() =
default;
65 void runOnOperation()
override;
67 void runOnOp(mlir::Operation *op);
68 void lowerCastOp(cir::CastOp op);
69 void lowerComplexDivOp(cir::ComplexDivOp op);
70 void lowerComplexMulOp(cir::ComplexMulOp op);
71 void lowerUnaryOp(cir::UnaryOp op);
72 void lowerGlobalOp(cir::GlobalOp op);
73 void lowerArrayDtor(cir::ArrayDtor op);
74 void lowerArrayCtor(cir::ArrayCtor op);
75 void lowerTrivialCopyCall(cir::CallOp op);
78 cir::FuncOp buildCXXGlobalVarDeclInitFunc(cir::GlobalOp op);
81 cir::FuncOp getOrCreateDtorFunc(CIRBaseBuilderTy &builder, cir::GlobalOp op,
82 mlir::Region &dtorRegion,
83 cir::CallOp &dtorCall);
86 void buildCXXGlobalInitFunc();
89 void buildGlobalCtorDtorList();
91 cir::FuncOp buildRuntimeFunction(
92 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
94 cir::GlobalLinkageKind linkage = cir::GlobalLinkageKind::ExternalLinkage);
96 cir::GlobalOp buildRuntimeVariable(
97 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
99 cir::GlobalLinkageKind linkage = cir::GlobalLinkageKind::ExternalLinkage,
100 cir::VisibilityKind visibility = cir::VisibilityKind::Default);
106 clang::ASTContext *astCtx;
109 mlir::ModuleOp mlirModule;
112 llvm::StringMap<uint32_t> dynamicInitializerNames;
113 llvm::SmallVector<cir::FuncOp> dynamicInitializers;
116 llvm::SmallVector<std::pair<std::string, uint32_t>, 4> globalCtorList;
118 llvm::SmallVector<std::pair<std::string, uint32_t>, 4> globalDtorList;
120 void setASTContext(clang::ASTContext *
c) { astCtx =
c; }
125cir::GlobalOp LoweringPreparePass::buildRuntimeVariable(
126 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
127 mlir::Type type, cir::GlobalLinkageKind linkage,
128 cir::VisibilityKind visibility) {
129 cir::GlobalOp g = dyn_cast_or_null<cir::GlobalOp>(
130 mlir::SymbolTable::lookupNearestSymbolFrom(
131 mlirModule, mlir::StringAttr::get(mlirModule->getContext(), name)));
133 g = cir::GlobalOp::create(builder, loc, name, type);
135 cir::GlobalLinkageKindAttr::get(builder.getContext(), linkage));
136 mlir::SymbolTable::setSymbolVisibility(
137 g, mlir::SymbolTable::Visibility::Private);
138 g.setGlobalVisibilityAttr(
139 cir::VisibilityAttr::get(builder.getContext(), visibility));
144cir::FuncOp LoweringPreparePass::buildRuntimeFunction(
145 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
146 cir::FuncType type, cir::GlobalLinkageKind linkage) {
147 cir::FuncOp f = dyn_cast_or_null<FuncOp>(SymbolTable::lookupNearestSymbolFrom(
148 mlirModule, StringAttr::get(mlirModule->getContext(), name)));
150 f = cir::FuncOp::create(builder, loc, name, type);
152 cir::GlobalLinkageKindAttr::get(builder.getContext(), linkage));
153 mlir::SymbolTable::setSymbolVisibility(
154 f, mlir::SymbolTable::Visibility::Private);
164 builder.setInsertionPoint(op);
166 mlir::Value src = op.getSrc();
167 mlir::Value imag = builder.
getNullValue(src.getType(), op.getLoc());
173 cir::CastKind elemToBoolKind) {
175 builder.setInsertionPoint(op);
177 mlir::Value src = op.getSrc();
178 if (!mlir::isa<cir::BoolType>(op.getType()))
185 cir::BoolType boolTy = builder.
getBoolTy();
186 mlir::Value srcRealToBool =
187 builder.
createCast(op.getLoc(), elemToBoolKind, srcReal, boolTy);
188 mlir::Value srcImagToBool =
189 builder.
createCast(op.getLoc(), elemToBoolKind, srcImag, boolTy);
190 return builder.
createLogicalOr(op.getLoc(), srcRealToBool, srcImagToBool);
195 cir::CastKind scalarCastKind) {
197 builder.setInsertionPoint(op);
199 mlir::Value src = op.getSrc();
200 auto dstComplexElemTy =
201 mlir::cast<cir::ComplexType>(op.getType()).getElementType();
206 mlir::Value dstReal = builder.
createCast(op.getLoc(), scalarCastKind, srcReal,
208 mlir::Value dstImag = builder.
createCast(op.getLoc(), scalarCastKind, srcImag,
213void LoweringPreparePass::lowerCastOp(cir::CastOp op) {
214 mlir::MLIRContext &ctx = getContext();
215 mlir::Value loweredValue = [&]() -> mlir::Value {
216 switch (op.getKind()) {
217 case cir::CastKind::float_to_complex:
218 case cir::CastKind::int_to_complex:
220 case cir::CastKind::float_complex_to_real:
221 case cir::CastKind::int_complex_to_real:
223 case cir::CastKind::float_complex_to_bool:
225 case cir::CastKind::int_complex_to_bool:
227 case cir::CastKind::float_complex:
229 case cir::CastKind::float_complex_to_int_complex:
231 case cir::CastKind::int_complex:
233 case cir::CastKind::int_complex_to_float_complex:
241 op.replaceAllUsesWith(loweredValue);
248 llvm::StringRef (*libFuncNameGetter)(llvm::APFloat::Semantics),
249 mlir::Location loc, cir::ComplexType ty, mlir::Value lhsReal,
250 mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag) {
251 cir::FPTypeInterface elementTy =
252 mlir::cast<cir::FPTypeInterface>(ty.getElementType());
254 llvm::StringRef libFuncName = libFuncNameGetter(
255 llvm::APFloat::SemanticsToEnum(elementTy.getFloatSemantics()));
258 cir::FuncType libFuncTy = cir::FuncType::get(libFuncInputTypes, ty);
264 mlir::OpBuilder::InsertionGuard ipGuard{builder};
265 builder.setInsertionPointToStart(pass.mlirModule.getBody());
266 libFunc = pass.buildRuntimeFunction(builder, libFuncName, loc, libFuncTy);
270 builder.
createCallOp(loc, libFunc, {lhsReal, lhsImag, rhsReal, rhsImag});
271 return call.getResult();
274static llvm::StringRef
277 case llvm::APFloat::S_IEEEhalf:
279 case llvm::APFloat::S_IEEEsingle:
281 case llvm::APFloat::S_IEEEdouble:
283 case llvm::APFloat::S_PPCDoubleDouble:
285 case llvm::APFloat::S_x87DoubleExtended:
287 case llvm::APFloat::S_IEEEquad:
290 llvm_unreachable(
"unsupported floating point type");
296 mlir::Value lhsReal, mlir::Value lhsImag,
297 mlir::Value rhsReal, mlir::Value rhsImag) {
299 mlir::Value &a = lhsReal;
300 mlir::Value &
b = lhsImag;
301 mlir::Value &
c = rhsReal;
302 mlir::Value &d = rhsImag;
304 mlir::Value ac = builder.
createBinop(loc, a, cir::BinOpKind::Mul,
c);
305 mlir::Value bd = builder.
createBinop(loc,
b, cir::BinOpKind::Mul, d);
306 mlir::Value cc = builder.
createBinop(loc,
c, cir::BinOpKind::Mul,
c);
307 mlir::Value dd = builder.
createBinop(loc, d, cir::BinOpKind::Mul, d);
309 builder.
createBinop(loc, ac, cir::BinOpKind::Add, bd);
311 builder.
createBinop(loc, cc, cir::BinOpKind::Add, dd);
312 mlir::Value resultReal =
313 builder.
createBinop(loc, acbd, cir::BinOpKind::Div, ccdd);
315 mlir::Value bc = builder.
createBinop(loc,
b, cir::BinOpKind::Mul,
c);
316 mlir::Value ad = builder.
createBinop(loc, a, cir::BinOpKind::Mul, d);
318 builder.
createBinop(loc, bc, cir::BinOpKind::Sub, ad);
319 mlir::Value resultImag =
320 builder.
createBinop(loc, bcad, cir::BinOpKind::Div, ccdd);
326 mlir::Value lhsReal, mlir::Value lhsImag,
327 mlir::Value rhsReal, mlir::Value rhsImag) {
348 mlir::Value &a = lhsReal;
349 mlir::Value &
b = lhsImag;
350 mlir::Value &
c = rhsReal;
351 mlir::Value &d = rhsImag;
353 auto trueBranchBuilder = [&](mlir::OpBuilder &, mlir::Location) {
354 mlir::Value r = builder.
createBinop(loc, d, cir::BinOpKind::Div,
356 mlir::Value rd = builder.
createBinop(loc, r, cir::BinOpKind::Mul, d);
357 mlir::Value tmp = builder.
createBinop(loc,
c, cir::BinOpKind::Add,
360 mlir::Value br = builder.
createBinop(loc,
b, cir::BinOpKind::Mul, r);
362 builder.
createBinop(loc, a, cir::BinOpKind::Add, br);
363 mlir::Value e = builder.
createBinop(loc, abr, cir::BinOpKind::Div, tmp);
365 mlir::Value ar = builder.
createBinop(loc, a, cir::BinOpKind::Mul, r);
368 mlir::Value f = builder.
createBinop(loc, bar, cir::BinOpKind::Div, tmp);
374 auto falseBranchBuilder = [&](mlir::OpBuilder &, mlir::Location) {
375 mlir::Value r = builder.
createBinop(loc,
c, cir::BinOpKind::Div,
377 mlir::Value rc = builder.
createBinop(loc, r, cir::BinOpKind::Mul,
c);
378 mlir::Value tmp = builder.
createBinop(loc, d, cir::BinOpKind::Add,
381 mlir::Value ar = builder.
createBinop(loc, a, cir::BinOpKind::Mul, r);
384 mlir::Value e = builder.
createBinop(loc, arb, cir::BinOpKind::Div, tmp);
386 mlir::Value br = builder.
createBinop(loc,
b, cir::BinOpKind::Mul, r);
388 builder.
createBinop(loc, br, cir::BinOpKind::Sub, a);
389 mlir::Value f = builder.
createBinop(loc, bra, cir::BinOpKind::Div, tmp);
395 auto cFabs = cir::FAbsOp::create(builder, loc,
c);
396 auto dFabs = cir::FAbsOp::create(builder, loc, d);
397 cir::CmpOp cmpResult =
398 builder.
createCompare(loc, cir::CmpOpKind::ge, cFabs, dFabs);
399 auto ternary = cir::TernaryOp::create(builder, loc, cmpResult,
400 trueBranchBuilder, falseBranchBuilder);
402 return ternary.getResult();
409 auto getHigherPrecisionFPType = [&context](mlir::Type type) -> mlir::Type {
410 if (mlir::isa<cir::FP16Type>(type))
411 return cir::SingleType::get(&context);
413 if (mlir::isa<cir::SingleType>(type) || mlir::isa<cir::BF16Type>(type))
414 return cir::DoubleType::get(&context);
416 if (mlir::isa<cir::DoubleType>(type))
417 return cir::LongDoubleType::get(&context, type);
422 auto getFloatTypeSemantics =
423 [&cc](mlir::Type type) ->
const llvm::fltSemantics & {
425 if (mlir::isa<cir::FP16Type>(type))
428 if (mlir::isa<cir::BF16Type>(type))
431 if (mlir::isa<cir::SingleType>(type))
434 if (mlir::isa<cir::DoubleType>(type))
437 if (mlir::isa<cir::LongDoubleType>(type)) {
439 llvm_unreachable(
"NYI Float type semantics with OpenMP");
443 if (mlir::isa<cir::FP128Type>(type)) {
445 llvm_unreachable(
"NYI Float type semantics with OpenMP");
449 llvm_unreachable(
"Unsupported float type semantics");
452 const mlir::Type higherElementType = getHigherPrecisionFPType(elementType);
453 const llvm::fltSemantics &elementTypeSemantics =
454 getFloatTypeSemantics(elementType);
455 const llvm::fltSemantics &higherElementTypeSemantics =
456 getFloatTypeSemantics(higherElementType);
465 if (llvm::APFloat::semanticsMaxExponent(elementTypeSemantics) * 2 + 1 <=
466 llvm::APFloat::semanticsMaxExponent(higherElementTypeSemantics)) {
467 return higherElementType;
477 mlir::Location loc, cir::ComplexDivOp op, mlir::Value lhsReal,
478 mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag,
480 cir::ComplexType complexTy = op.getType();
481 if (mlir::isa<cir::FPTypeInterface>(complexTy.getElementType())) {
482 cir::ComplexRangeKind range = op.getRange();
483 if (range == cir::ComplexRangeKind::Improved)
487 if (range == cir::ComplexRangeKind::Full)
489 loc, complexTy, lhsReal, lhsImag, rhsReal,
492 if (range == cir::ComplexRangeKind::Promoted) {
493 mlir::Type originalElementType = complexTy.getElementType();
494 mlir::Type higherPrecisionElementType =
496 originalElementType);
498 if (!higherPrecisionElementType)
502 cir::CastKind floatingCastKind = cir::CastKind::floating;
503 lhsReal = builder.
createCast(floatingCastKind, lhsReal,
504 higherPrecisionElementType);
505 lhsImag = builder.
createCast(floatingCastKind, lhsImag,
506 higherPrecisionElementType);
507 rhsReal = builder.
createCast(floatingCastKind, rhsReal,
508 higherPrecisionElementType);
509 rhsImag = builder.
createCast(floatingCastKind, rhsImag,
510 higherPrecisionElementType);
513 builder, loc, lhsReal, lhsImag, rhsReal, rhsImag);
518 mlir::Value finalReal =
519 builder.
createCast(floatingCastKind, resultReal, originalElementType);
520 mlir::Value finalImag =
521 builder.
createCast(floatingCastKind, resultImag, originalElementType);
530void LoweringPreparePass::lowerComplexDivOp(cir::ComplexDivOp op) {
531 cir::CIRBaseBuilderTy builder(getContext());
532 builder.setInsertionPointAfter(op);
533 mlir::Location loc = op.getLoc();
534 mlir::TypedValue<cir::ComplexType> lhs = op.getLhs();
535 mlir::TypedValue<cir::ComplexType> rhs = op.getRhs();
541 mlir::Value loweredResult =
543 rhsImag, getContext(), *astCtx);
544 op.replaceAllUsesWith(loweredResult);
548static llvm::StringRef
551 case llvm::APFloat::S_IEEEhalf:
553 case llvm::APFloat::S_IEEEsingle:
555 case llvm::APFloat::S_IEEEdouble:
557 case llvm::APFloat::S_PPCDoubleDouble:
559 case llvm::APFloat::S_x87DoubleExtended:
561 case llvm::APFloat::S_IEEEquad:
564 llvm_unreachable(
"unsupported floating point type");
570 mlir::Location loc, cir::ComplexMulOp op,
571 mlir::Value lhsReal, mlir::Value lhsImag,
572 mlir::Value rhsReal, mlir::Value rhsImag) {
574 mlir::Value resultRealLhs =
575 builder.
createBinop(loc, lhsReal, cir::BinOpKind::Mul, rhsReal);
576 mlir::Value resultRealRhs =
577 builder.
createBinop(loc, lhsImag, cir::BinOpKind::Mul, rhsImag);
578 mlir::Value resultImagLhs =
579 builder.
createBinop(loc, lhsReal, cir::BinOpKind::Mul, rhsImag);
580 mlir::Value resultImagRhs =
581 builder.
createBinop(loc, lhsImag, cir::BinOpKind::Mul, rhsReal);
583 loc, resultRealLhs, cir::BinOpKind::Sub, resultRealRhs);
585 loc, resultImagLhs, cir::BinOpKind::Add, resultImagRhs);
586 mlir::Value algebraicResult =
589 cir::ComplexType complexTy = op.getType();
590 cir::ComplexRangeKind rangeKind = op.getRange();
591 if (mlir::isa<cir::IntType>(complexTy.getElementType()) ||
592 rangeKind == cir::ComplexRangeKind::Basic ||
593 rangeKind == cir::ComplexRangeKind::Improved ||
594 rangeKind == cir::ComplexRangeKind::Promoted)
595 return algebraicResult;
602 mlir::Value resultRealIsNaN = builder.
createIsNaN(loc, resultReal);
603 mlir::Value resultImagIsNaN = builder.
createIsNaN(loc, resultImag);
604 mlir::Value resultRealAndImagAreNaN =
607 return cir::TernaryOp::create(
608 builder, loc, resultRealAndImagAreNaN,
609 [&](mlir::OpBuilder &, mlir::Location) {
612 lhsReal, lhsImag, rhsReal, rhsImag);
615 [&](mlir::OpBuilder &, mlir::Location) {
621void LoweringPreparePass::lowerComplexMulOp(cir::ComplexMulOp op) {
622 cir::CIRBaseBuilderTy builder(getContext());
623 builder.setInsertionPointAfter(op);
624 mlir::Location loc = op.getLoc();
625 mlir::TypedValue<cir::ComplexType> lhs = op.getLhs();
626 mlir::TypedValue<cir::ComplexType> rhs = op.getRhs();
631 mlir::Value loweredResult =
lowerComplexMul(*
this, builder, loc, op, lhsReal,
632 lhsImag, rhsReal, rhsImag);
633 op.replaceAllUsesWith(loweredResult);
637void LoweringPreparePass::lowerUnaryOp(cir::UnaryOp op) {
638 mlir::Type ty = op.getType();
639 if (!mlir::isa<cir::ComplexType>(ty))
642 mlir::Location loc = op.getLoc();
643 cir::UnaryOpKind opKind = op.getKind();
645 CIRBaseBuilderTy builder(getContext());
646 builder.setInsertionPointAfter(op);
648 mlir::Value operand = op.getInput();
652 mlir::Value resultReal;
653 mlir::Value resultImag;
656 case cir::UnaryOpKind::Inc:
657 case cir::UnaryOpKind::Dec:
658 resultReal = builder.
createUnaryOp(loc, opKind, operandReal);
659 resultImag = operandImag;
662 case cir::UnaryOpKind::Plus:
663 case cir::UnaryOpKind::Minus:
664 resultReal = builder.
createUnaryOp(loc, opKind, operandReal);
665 resultImag = builder.
createUnaryOp(loc, opKind, operandImag);
668 case cir::UnaryOpKind::Not:
669 resultReal = operandReal;
671 builder.
createUnaryOp(loc, cir::UnaryOpKind::Minus, operandImag);
676 op.replaceAllUsesWith(result);
680cir::FuncOp LoweringPreparePass::getOrCreateDtorFunc(CIRBaseBuilderTy &builder,
682 mlir::Region &dtorRegion,
683 cir::CallOp &dtorCall) {
684 mlir::OpBuilder::InsertionGuard guard(builder);
688 cir::VoidType voidTy = builder.
getVoidTy();
689 auto voidPtrTy = cir::PointerType::get(voidTy);
692 mlir::Block &dtorBlock = dtorRegion.front();
696 auto opIt = dtorBlock.getOperations().begin();
697 cir::GetGlobalOp ggop = mlir::cast<cir::GetGlobalOp>(*opIt);
708 if (dtorBlock.getOperations().size() == 3) {
709 auto callOp = mlir::dyn_cast<cir::CallOp>(&*(++opIt));
710 auto yieldOp = mlir::dyn_cast<cir::YieldOp>(&*(++opIt));
711 if (yieldOp && callOp && callOp.getNumOperands() == 1 &&
712 callOp.getArgOperand(0) == ggop) {
721 builder.setInsertionPointAfter(op);
722 SmallString<256> fnName(
"__cxx_global_array_dtor");
723 uint32_t cnt = dynamicInitializerNames[fnName]++;
725 fnName +=
"." + std::to_string(cnt);
728 auto fnType = cir::FuncType::get({voidPtrTy}, voidTy);
729 cir::FuncOp dtorFunc =
730 buildRuntimeFunction(builder, fnName, op.getLoc(), fnType,
731 cir::GlobalLinkageKind::InternalLinkage);
732 mlir::Block *entryBB = dtorFunc.addEntryBlock();
735 entryBB->getOperations().splice(entryBB->begin(), dtorBlock.getOperations(),
736 dtorBlock.begin(), dtorBlock.end());
739 cir::GetGlobalOp dtorGGop =
740 mlir::cast<cir::GetGlobalOp>(entryBB->getOperations().front());
741 builder.setInsertionPointToStart(&dtorBlock);
742 builder.clone(*dtorGGop.getOperation());
746 mlir::Value dtorArg = entryBB->getArgument(0);
747 dtorGGop.replaceAllUsesWith(dtorArg);
751 mlir::Block &finalBlock = dtorFunc.getBody().back();
752 auto yieldOp = cast<cir::YieldOp>(finalBlock.getTerminator());
753 builder.setInsertionPoint(yieldOp);
754 cir::ReturnOp::create(builder, yieldOp->getLoc());
759 cir::GetGlobalOp origGGop =
760 mlir::cast<cir::GetGlobalOp>(dtorBlock.getOperations().front());
761 builder.setInsertionPointAfter(origGGop);
762 mlir::Value ggopResult = origGGop.getResult();
763 dtorCall = builder.
createCallOp(op.getLoc(), dtorFunc, ggopResult);
766 auto finalYield = cir::YieldOp::create(builder, op.getLoc());
769 dtorBlock.getOperations().erase(std::next(mlir::Block::iterator(finalYield)),
771 dtorRegion.getBlocks().erase(std::next(dtorRegion.begin()), dtorRegion.end());
777LoweringPreparePass::buildCXXGlobalVarDeclInitFunc(cir::GlobalOp op) {
780 SmallString<256> fnName(
"__cxx_global_var_init");
782 uint32_t cnt = dynamicInitializerNames[fnName]++;
784 fnName +=
"." + std::to_string(cnt);
787 CIRBaseBuilderTy builder(getContext());
788 builder.setInsertionPointAfter(op);
789 cir::VoidType voidTy = builder.
getVoidTy();
790 auto fnType = cir::FuncType::get({}, voidTy);
791 FuncOp f = buildRuntimeFunction(builder, fnName, op.getLoc(), fnType,
792 cir::GlobalLinkageKind::InternalLinkage);
795 mlir::Block *entryBB = f.addEntryBlock();
796 if (!op.getCtorRegion().empty()) {
797 mlir::Block &block = op.getCtorRegion().front();
798 entryBB->getOperations().splice(entryBB->begin(), block.getOperations(),
799 block.begin(), std::prev(block.end()));
803 mlir::Region &dtorRegion = op.getDtorRegion();
804 if (!dtorRegion.empty()) {
809 builder.setInsertionPointToStart(&mlirModule.getBodyRegion().front());
810 cir::GlobalOp handle = buildRuntimeVariable(
811 builder,
"__dso_handle", op.getLoc(), builder.getI8Type(),
812 cir::GlobalLinkageKind::ExternalLinkage, cir::VisibilityKind::Hidden);
818 cir::CallOp dtorCall;
819 cir::FuncOp dtorFunc =
820 getOrCreateDtorFunc(builder, op, dtorRegion, dtorCall);
824 auto voidPtrTy = cir::PointerType::get(voidTy);
825 auto voidFnTy = cir::FuncType::get({voidPtrTy}, voidTy);
826 auto voidFnPtrTy = cir::PointerType::get(voidFnTy);
827 auto handlePtrTy = cir::PointerType::get(handle.getSymType());
829 cir::FuncType::get({voidFnPtrTy, voidPtrTy, handlePtrTy}, voidTy);
830 const char *nameAtExit =
"__cxa_atexit";
831 cir::FuncOp fnAtExit =
832 buildRuntimeFunction(builder, nameAtExit, op.getLoc(), fnAtExitType);
836 builder.setInsertionPointAfter(dtorCall);
838 auto dtorPtrTy = cir::PointerType::get(dtorFunc.getFunctionType());
840 args[0] = cir::GetGlobalOp::create(builder, dtorCall.getLoc(), dtorPtrTy,
841 dtorFunc.getSymName());
842 args[0] = cir::CastOp::create(builder, dtorCall.getLoc(), voidFnPtrTy,
843 cir::CastKind::bitcast, args[0]);
845 cir::CastOp::create(builder, dtorCall.getLoc(), voidPtrTy,
846 cir::CastKind::bitcast, dtorCall.getArgOperand(0));
847 args[2] = cir::GetGlobalOp::create(builder, handle.getLoc(), handlePtrTy,
848 handle.getSymName());
849 builder.
createCallOp(dtorCall.getLoc(), fnAtExit, args);
851 mlir::Block &dtorBlock = dtorRegion.front();
852 entryBB->getOperations().splice(entryBB->end(), dtorBlock.getOperations(),
854 std::prev(dtorBlock.end()));
858 builder.setInsertionPointToEnd(entryBB);
859 mlir::Operation *yieldOp =
nullptr;
860 if (!op.getCtorRegion().empty()) {
861 mlir::Block &block = op.getCtorRegion().front();
862 yieldOp = &block.getOperations().back();
864 assert(!dtorRegion.empty());
865 mlir::Block &block = dtorRegion.front();
866 yieldOp = &block.getOperations().back();
869 assert(isa<cir::YieldOp>(*yieldOp));
870 cir::ReturnOp::create(builder, yieldOp->getLoc());
874void LoweringPreparePass::lowerGlobalOp(GlobalOp op) {
875 mlir::Region &ctorRegion = op.getCtorRegion();
876 mlir::Region &dtorRegion = op.getDtorRegion();
878 if (!ctorRegion.empty() || !dtorRegion.empty()) {
881 cir::FuncOp f = buildCXXGlobalVarDeclInitFunc(op);
884 ctorRegion.getBlocks().clear();
885 dtorRegion.getBlocks().clear();
888 dynamicInitializers.push_back(f);
894template <
typename AttributeTy>
895static llvm::SmallVector<mlir::Attribute>
899 for (
const auto &[name, priority] : list)
900 attrs.push_back(AttributeTy::get(context, name, priority));
904void LoweringPreparePass::buildGlobalCtorDtorList() {
905 if (!globalCtorList.empty()) {
906 llvm::SmallVector<mlir::Attribute> globalCtors =
910 mlirModule->setAttr(cir::CIRDialect::getGlobalCtorsAttrName(),
911 mlir::ArrayAttr::get(&getContext(), globalCtors));
914 if (!globalDtorList.empty()) {
915 llvm::SmallVector<mlir::Attribute> globalDtors =
918 mlirModule->setAttr(cir::CIRDialect::getGlobalDtorsAttrName(),
919 mlir::ArrayAttr::get(&getContext(), globalDtors));
923void LoweringPreparePass::buildCXXGlobalInitFunc() {
924 if (dynamicInitializers.empty())
931 SmallString<256> fnName;
939 llvm::raw_svector_ostream
out(fnName);
940 std::unique_ptr<clang::MangleContext> mangleCtx(
942 cast<clang::ItaniumMangleContext>(*mangleCtx)
945 fnName +=
"_GLOBAL__sub_I_";
949 CIRBaseBuilderTy builder(getContext());
950 builder.setInsertionPointToEnd(&mlirModule.getBodyRegion().back());
951 auto fnType = cir::FuncType::get({}, builder.
getVoidTy());
953 buildRuntimeFunction(builder, fnName, mlirModule.getLoc(), fnType,
954 cir::GlobalLinkageKind::ExternalLinkage);
955 builder.setInsertionPointToStart(f.addEntryBlock());
956 for (cir::FuncOp &f : dynamicInitializers)
960 globalCtorList.emplace_back(fnName,
961 cir::GlobalCtorAttr::getDefaultPriority());
963 cir::ReturnOp::create(builder, f.getLoc());
968 mlir::Operation *op, mlir::Type eltTy,
969 mlir::Value arrayAddr, uint64_t arrayLen,
972 mlir::Location loc = op->getLoc();
976 const unsigned sizeTypeSize =
978 uint64_t endOffset = isCtor ? arrayLen : arrayLen - 1;
979 mlir::Value endOffsetVal =
982 auto begin = cir::CastOp::create(builder, loc, eltTy,
983 cir::CastKind::array_to_ptrdecay, arrayAddr);
985 cir::PtrStrideOp::create(builder, loc, eltTy, begin, endOffsetVal);
986 mlir::Value start = isCtor ? begin : end;
987 mlir::Value stop = isCtor ? end : begin;
997 [&](mlir::OpBuilder &
b, mlir::Location loc) {
998 auto currentElement = cir::LoadOp::create(
b, loc, eltTy, tmpAddr);
999 auto cmp = cir::CmpOp::create(builder, loc, cir::CmpOpKind::ne,
1000 currentElement, stop);
1004 [&](mlir::OpBuilder &
b, mlir::Location loc) {
1005 auto currentElement = cir::LoadOp::create(
b, loc, eltTy, tmpAddr);
1007 cir::CallOp ctorCall;
1008 op->walk([&](cir::CallOp
c) { ctorCall =
c; });
1009 assert(ctorCall &&
"expected ctor call");
1018 ctorCall->moveBefore(stride.getDefiningOp());
1019 ctorCall->setOperand(0, currentElement);
1020 auto nextElement = cir::PtrStrideOp::create(builder, loc, eltTy,
1021 currentElement, stride);
1028 op->replaceAllUsesWith(loop);
1032void LoweringPreparePass::lowerArrayDtor(cir::ArrayDtor op) {
1033 CIRBaseBuilderTy builder(getContext());
1034 builder.setInsertionPointAfter(op.getOperation());
1036 mlir::Type eltTy = op->getRegion(0).getArgument(0).getType();
1039 mlir::cast<cir::ArrayType>(op.getAddr().getType().getPointee()).getSize();
1044void LoweringPreparePass::lowerArrayCtor(cir::ArrayCtor op) {
1045 cir::CIRBaseBuilderTy builder(getContext());
1046 builder.setInsertionPointAfter(op.getOperation());
1048 mlir::Type eltTy = op->getRegion(0).getArgument(0).getType();
1051 mlir::cast<cir::ArrayType>(op.getAddr().getType().getPointee()).getSize();
1056void LoweringPreparePass::lowerTrivialCopyCall(cir::CallOp op) {
1061 std::optional<cir::CtorKind> ctorKind = funcOp.getCxxConstructorKind();
1062 if (ctorKind && *ctorKind == cir::CtorKind::Copy &&
1063 funcOp.isCxxTrivialMemberFunction()) {
1065 CIRBaseBuilderTy builder(getContext());
1066 mlir::ValueRange operands = op.getOperands();
1067 mlir::Value dest = operands[0];
1068 mlir::Value src = operands[1];
1069 builder.setInsertionPoint(op);
1075void LoweringPreparePass::runOnOp(mlir::Operation *op) {
1076 if (
auto arrayCtor = dyn_cast<cir::ArrayCtor>(op)) {
1077 lowerArrayCtor(arrayCtor);
1078 }
else if (
auto arrayDtor = dyn_cast<cir::ArrayDtor>(op)) {
1079 lowerArrayDtor(arrayDtor);
1080 }
else if (
auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
1082 }
else if (
auto complexDiv = mlir::dyn_cast<cir::ComplexDivOp>(op)) {
1083 lowerComplexDivOp(complexDiv);
1084 }
else if (
auto complexMul = mlir::dyn_cast<cir::ComplexMulOp>(op)) {
1085 lowerComplexMulOp(complexMul);
1086 }
else if (
auto glob = mlir::dyn_cast<cir::GlobalOp>(op)) {
1087 lowerGlobalOp(glob);
1088 }
else if (
auto unary = mlir::dyn_cast<cir::UnaryOp>(op)) {
1089 lowerUnaryOp(unary);
1090 }
else if (
auto callOp = dyn_cast<cir::CallOp>(op)) {
1091 lowerTrivialCopyCall(callOp);
1092 }
else if (
auto fnOp = dyn_cast<cir::FuncOp>(op)) {
1093 if (
auto globalCtor = fnOp.getGlobalCtorPriority())
1094 globalCtorList.emplace_back(fnOp.getName(), globalCtor.value());
1095 else if (
auto globalDtor = fnOp.getGlobalDtorPriority())
1096 globalDtorList.emplace_back(fnOp.getName(), globalDtor.value());
1100void LoweringPreparePass::runOnOperation() {
1101 mlir::Operation *op = getOperation();
1102 if (isa<::mlir::ModuleOp>(op))
1103 mlirModule = cast<::mlir::ModuleOp>(op);
1105 llvm::SmallVector<mlir::Operation *> opsToTransform;
1107 op->walk([&](mlir::Operation *op) {
1108 if (mlir::isa<cir::ArrayCtor, cir::ArrayDtor, cir::CastOp,
1109 cir::ComplexMulOp, cir::ComplexDivOp, cir::DynamicCastOp,
1110 cir::FuncOp, cir::CallOp, cir::GlobalOp, cir::UnaryOp>(op))
1111 opsToTransform.push_back(op);
1114 for (mlir::Operation *o : opsToTransform)
1117 buildCXXGlobalInitFunc();
1118 buildGlobalCtorDtorList();
1122 return std::make_unique<LoweringPreparePass>();
1125std::unique_ptr<Pass>
1127 auto pass = std::make_unique<LoweringPreparePass>();
1128 pass->setASTContext(astCtx);
1129 return std::move(pass);
Defines the clang::ASTContext interface.
static mlir::Value buildRangeReductionComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc, mlir::Value lhsReal, mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag)
static void lowerArrayDtorCtorIntoLoop(cir::CIRBaseBuilderTy &builder, clang::ASTContext *astCtx, mlir::Operation *op, mlir::Type eltTy, mlir::Value arrayAddr, uint64_t arrayLen, bool isCtor)
static llvm::StringRef getComplexDivLibCallName(llvm::APFloat::Semantics semantics)
static llvm::SmallVector< mlir::Attribute > prepareCtorDtorAttrList(mlir::MLIRContext *context, llvm::ArrayRef< std::pair< std::string, uint32_t > > list)
static llvm::StringRef getComplexMulLibCallName(llvm::APFloat::Semantics semantics)
static mlir::Value buildComplexBinOpLibCall(LoweringPreparePass &pass, CIRBaseBuilderTy &builder, llvm::StringRef(*libFuncNameGetter)(llvm::APFloat::Semantics), mlir::Location loc, cir::ComplexType ty, mlir::Value lhsReal, mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag)
static mlir::Value lowerComplexMul(LoweringPreparePass &pass, CIRBaseBuilderTy &builder, mlir::Location loc, cir::ComplexMulOp op, mlir::Value lhsReal, mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag)
static SmallString< 128 > getTransformedFileName(mlir::ModuleOp mlirModule)
static mlir::Value lowerComplexToComplexCast(mlir::MLIRContext &ctx, cir::CastOp op, cir::CastKind scalarCastKind)
static mlir::Value lowerComplexToScalarCast(mlir::MLIRContext &ctx, cir::CastOp op, cir::CastKind elemToBoolKind)
static mlir::Value buildAlgebraicComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc, mlir::Value lhsReal, mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag)
static cir::FuncOp getCalledFunction(cir::CallOp callOp)
Return the FuncOp called by callOp.
static mlir::Type higherPrecisionElementTypeForComplexArithmetic(mlir::MLIRContext &context, clang::ASTContext &cc, CIRBaseBuilderTy &builder, mlir::Type elementType)
static mlir::Value lowerScalarToComplexCast(mlir::MLIRContext &ctx, cir::CastOp op)
static mlir::Value lowerComplexDiv(LoweringPreparePass &pass, CIRBaseBuilderTy &builder, mlir::Location loc, cir::ComplexDivOp op, mlir::Value lhsReal, mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag, mlir::MLIRContext &mlirCx, clang::ASTContext &cc)
Defines the clang::Module class, which describes a module in the source code.
__device__ __2f16 float c
mlir::Value createLogicalOr(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::ConditionOp createCondition(mlir::Value condition)
Create a loop condition.
cir::VoidType getVoidTy()
cir::ConstantOp getNullValue(mlir::Type ty, mlir::Location loc)
mlir::Value createCast(mlir::Location loc, cir::CastKind kind, mlir::Value src, mlir::Type newTy)
cir::PointerType getPointerTo(mlir::Type ty)
mlir::Value createComplexImag(mlir::Location loc, mlir::Value operand)
cir::DoWhileOp createDoWhile(mlir::Location loc, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> condBuilder, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> bodyBuilder)
Create a do-while operation.
cir::CopyOp createCopy(mlir::Value dst, mlir::Value src, bool isVolatile=false)
Create a copy with inferred length.
cir::CallOp createCallOp(mlir::Location loc, mlir::SymbolRefAttr callee, mlir::Type returnType, mlir::ValueRange operands, llvm::ArrayRef< mlir::NamedAttribute > attrs={})
mlir::Value getSignedInt(mlir::Location loc, int64_t val, unsigned numBits)
cir::CmpOp createCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
mlir::IntegerAttr getAlignmentAttr(clang::CharUnits alignment)
mlir::Value createBinop(mlir::Location loc, mlir::Value lhs, cir::BinOpKind kind, mlir::Value rhs)
mlir::Value createComplexCreate(mlir::Location loc, mlir::Value real, mlir::Value imag)
mlir::Value createIsNaN(mlir::Location loc, mlir::Value operand)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, mlir::Value dst, bool isVolatile=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
mlir::Value createLogicalAnd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createUnaryOp(mlir::Location loc, cir::UnaryOpKind kind, mlir::Value operand)
mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType, mlir::Type type, llvm::StringRef name, mlir::IntegerAttr alignment, mlir::Value dynAllocSize)
cir::BoolType getBoolTy()
mlir::Value getUnsignedInt(mlir::Location loc, uint64_t val, unsigned numBits)
mlir::Value createComplexReal(mlir::Location loc, mlir::Value operand)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
const LangOptions & getLangOpts() const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
const TargetInfo & getTargetInfo() const
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
bool isModuleImplementation() const
Is this a module implementation.
Exposes information about the current target.
const llvm::fltSemantics & getDoubleFormat() const
const llvm::fltSemantics & getHalfFormat() const
const llvm::fltSemantics & getBFloat16Format() const
const llvm::fltSemantics & getLongDoubleFormat() const
const llvm::fltSemantics & getFloatFormat() const
const llvm::fltSemantics & getFloat128Format() const
Defines the clang::TargetInfo interface.
LLVM_READONLY bool isPreprocessingNumberBody(unsigned char c)
Return true if this is the body character of a C preprocessing number, which is [a-zA-Z0-9_.
std::unique_ptr< Pass > createLoweringPreparePass()
static bool opGlobalThreadLocal()
static bool opGlobalAnnotations()
static bool opGlobalCtorPriority()
static bool opFuncExtraAttrs()
static bool fastMathFlags()
static bool astVarDeclInterface()