19#include "llvm/Support/Path.h"
27#define GEN_PASS_DEF_LOWERINGPREPARE
28#include "clang/CIR/Dialect/Passes.h.inc"
32 SmallString<128> fileName;
34 if (mlirModule.getSymName())
35 fileName = llvm::sys::path::filename(mlirModule.getSymName()->str());
40 for (
size_t i = 0; i < fileName.size(); ++i) {
52 mlir::SymbolRefAttr sym = llvm::dyn_cast_if_present<mlir::SymbolRefAttr>(
53 callOp.getCallableForCallee());
56 return dyn_cast_or_null<cir::FuncOp>(
57 mlir::SymbolTable::lookupNearestSymbolFrom(callOp, sym));
61struct LoweringPreparePass
62 :
public impl::LoweringPrepareBase<LoweringPreparePass> {
63 LoweringPreparePass() =
default;
64 void runOnOperation()
override;
66 void runOnOp(mlir::Operation *op);
67 void lowerCastOp(cir::CastOp op);
68 void lowerComplexDivOp(cir::ComplexDivOp op);
69 void lowerComplexMulOp(cir::ComplexMulOp op);
70 void lowerUnaryOp(cir::UnaryOp op);
71 void lowerGlobalOp(cir::GlobalOp op);
72 void lowerDynamicCastOp(cir::DynamicCastOp op);
73 void lowerArrayDtor(cir::ArrayDtor op);
74 void lowerArrayCtor(cir::ArrayCtor op);
77 cir::FuncOp buildCXXGlobalVarDeclInitFunc(cir::GlobalOp op);
80 void buildCXXGlobalInitFunc();
83 void buildGlobalCtorDtorList();
85 cir::FuncOp buildRuntimeFunction(
86 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
88 cir::GlobalLinkageKind linkage = cir::GlobalLinkageKind::ExternalLinkage);
90 cir::GlobalOp buildRuntimeVariable(
91 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
93 cir::GlobalLinkageKind linkage = cir::GlobalLinkageKind::ExternalLinkage,
94 cir::VisibilityKind visibility = cir::VisibilityKind::Default);
100 clang::ASTContext *astCtx;
103 std::shared_ptr<cir::LoweringPrepareCXXABI> cxxABI;
106 mlir::ModuleOp mlirModule;
109 llvm::StringMap<uint32_t> dynamicInitializerNames;
110 llvm::SmallVector<cir::FuncOp> dynamicInitializers;
113 llvm::SmallVector<std::pair<std::string, uint32_t>, 4> globalCtorList;
115 llvm::SmallVector<std::pair<std::string, uint32_t>, 4> globalDtorList;
117 void setASTContext(clang::ASTContext *
c) {
119 switch (
c->getCXXABIKind()) {
120 case clang::TargetCXXABI::GenericItanium:
126 case clang::TargetCXXABI::GenericAArch64:
127 case clang::TargetCXXABI::AppleARM64:
132 llvm_unreachable(
"NYI");
139cir::GlobalOp LoweringPreparePass::buildRuntimeVariable(
140 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
141 mlir::Type type, cir::GlobalLinkageKind linkage,
142 cir::VisibilityKind visibility) {
143 cir::GlobalOp g = dyn_cast_or_null<cir::GlobalOp>(
144 mlir::SymbolTable::lookupNearestSymbolFrom(
145 mlirModule, mlir::StringAttr::get(mlirModule->getContext(), name)));
147 g = cir::GlobalOp::create(builder, loc, name, type);
149 cir::GlobalLinkageKindAttr::get(builder.getContext(), linkage));
150 mlir::SymbolTable::setSymbolVisibility(
151 g, mlir::SymbolTable::Visibility::Private);
152 g.setGlobalVisibilityAttr(
153 cir::VisibilityAttr::get(builder.getContext(), visibility));
158cir::FuncOp LoweringPreparePass::buildRuntimeFunction(
159 mlir::OpBuilder &builder, llvm::StringRef name, mlir::Location loc,
160 cir::FuncType type, cir::GlobalLinkageKind linkage) {
161 cir::FuncOp f = dyn_cast_or_null<FuncOp>(SymbolTable::lookupNearestSymbolFrom(
162 mlirModule, StringAttr::get(mlirModule->getContext(), name)));
164 f = cir::FuncOp::create(builder, loc, name, type);
166 cir::GlobalLinkageKindAttr::get(builder.getContext(), linkage));
167 mlir::SymbolTable::setSymbolVisibility(
168 f, mlir::SymbolTable::Visibility::Private);
178 builder.setInsertionPoint(op);
180 mlir::Value src = op.getSrc();
181 mlir::Value imag = builder.
getNullValue(src.getType(), op.getLoc());
187 cir::CastKind elemToBoolKind) {
189 builder.setInsertionPoint(op);
191 mlir::Value src = op.getSrc();
192 if (!mlir::isa<cir::BoolType>(op.getType()))
199 cir::BoolType boolTy = builder.
getBoolTy();
200 mlir::Value srcRealToBool =
201 builder.
createCast(op.getLoc(), elemToBoolKind, srcReal, boolTy);
202 mlir::Value srcImagToBool =
203 builder.
createCast(op.getLoc(), elemToBoolKind, srcImag, boolTy);
204 return builder.
createLogicalOr(op.getLoc(), srcRealToBool, srcImagToBool);
209 cir::CastKind scalarCastKind) {
211 builder.setInsertionPoint(op);
213 mlir::Value src = op.getSrc();
214 auto dstComplexElemTy =
215 mlir::cast<cir::ComplexType>(op.getType()).getElementType();
220 mlir::Value dstReal = builder.
createCast(op.getLoc(), scalarCastKind, srcReal,
222 mlir::Value dstImag = builder.
createCast(op.getLoc(), scalarCastKind, srcImag,
227void LoweringPreparePass::lowerCastOp(cir::CastOp op) {
228 mlir::MLIRContext &ctx = getContext();
229 mlir::Value loweredValue = [&]() -> mlir::Value {
230 switch (op.getKind()) {
231 case cir::CastKind::float_to_complex:
232 case cir::CastKind::int_to_complex:
234 case cir::CastKind::float_complex_to_real:
235 case cir::CastKind::int_complex_to_real:
237 case cir::CastKind::float_complex_to_bool:
239 case cir::CastKind::int_complex_to_bool:
241 case cir::CastKind::float_complex:
243 case cir::CastKind::float_complex_to_int_complex:
245 case cir::CastKind::int_complex:
247 case cir::CastKind::int_complex_to_float_complex:
255 op.replaceAllUsesWith(loweredValue);
262 llvm::StringRef (*libFuncNameGetter)(llvm::APFloat::Semantics),
263 mlir::Location loc, cir::ComplexType ty, mlir::Value lhsReal,
264 mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag) {
265 cir::FPTypeInterface elementTy =
266 mlir::cast<cir::FPTypeInterface>(ty.getElementType());
268 llvm::StringRef libFuncName = libFuncNameGetter(
269 llvm::APFloat::SemanticsToEnum(elementTy.getFloatSemantics()));
272 cir::FuncType libFuncTy = cir::FuncType::get(libFuncInputTypes, ty);
278 mlir::OpBuilder::InsertionGuard ipGuard{builder};
279 builder.setInsertionPointToStart(pass.mlirModule.getBody());
280 libFunc = pass.buildRuntimeFunction(builder, libFuncName, loc, libFuncTy);
284 builder.
createCallOp(loc, libFunc, {lhsReal, lhsImag, rhsReal, rhsImag});
285 return call.getResult();
288static llvm::StringRef
291 case llvm::APFloat::S_IEEEhalf:
293 case llvm::APFloat::S_IEEEsingle:
295 case llvm::APFloat::S_IEEEdouble:
297 case llvm::APFloat::S_PPCDoubleDouble:
299 case llvm::APFloat::S_x87DoubleExtended:
301 case llvm::APFloat::S_IEEEquad:
304 llvm_unreachable(
"unsupported floating point type");
310 mlir::Value lhsReal, mlir::Value lhsImag,
311 mlir::Value rhsReal, mlir::Value rhsImag) {
313 mlir::Value &a = lhsReal;
314 mlir::Value &
b = lhsImag;
315 mlir::Value &
c = rhsReal;
316 mlir::Value &d = rhsImag;
318 mlir::Value ac = builder.
createBinop(loc, a, cir::BinOpKind::Mul,
c);
319 mlir::Value bd = builder.
createBinop(loc,
b, cir::BinOpKind::Mul, d);
320 mlir::Value cc = builder.
createBinop(loc,
c, cir::BinOpKind::Mul,
c);
321 mlir::Value dd = builder.
createBinop(loc, d, cir::BinOpKind::Mul, d);
323 builder.
createBinop(loc, ac, cir::BinOpKind::Add, bd);
325 builder.
createBinop(loc, cc, cir::BinOpKind::Add, dd);
326 mlir::Value resultReal =
327 builder.
createBinop(loc, acbd, cir::BinOpKind::Div, ccdd);
329 mlir::Value bc = builder.
createBinop(loc,
b, cir::BinOpKind::Mul,
c);
330 mlir::Value ad = builder.
createBinop(loc, a, cir::BinOpKind::Mul, d);
332 builder.
createBinop(loc, bc, cir::BinOpKind::Sub, ad);
333 mlir::Value resultImag =
334 builder.
createBinop(loc, bcad, cir::BinOpKind::Div, ccdd);
340 mlir::Value lhsReal, mlir::Value lhsImag,
341 mlir::Value rhsReal, mlir::Value rhsImag) {
362 mlir::Value &a = lhsReal;
363 mlir::Value &
b = lhsImag;
364 mlir::Value &
c = rhsReal;
365 mlir::Value &d = rhsImag;
367 auto trueBranchBuilder = [&](mlir::OpBuilder &, mlir::Location) {
368 mlir::Value r = builder.
createBinop(loc, d, cir::BinOpKind::Div,
370 mlir::Value rd = builder.
createBinop(loc, r, cir::BinOpKind::Mul, d);
371 mlir::Value tmp = builder.
createBinop(loc,
c, cir::BinOpKind::Add,
374 mlir::Value br = builder.
createBinop(loc,
b, cir::BinOpKind::Mul, r);
376 builder.
createBinop(loc, a, cir::BinOpKind::Add, br);
377 mlir::Value e = builder.
createBinop(loc, abr, cir::BinOpKind::Div, tmp);
379 mlir::Value ar = builder.
createBinop(loc, a, cir::BinOpKind::Mul, r);
382 mlir::Value f = builder.
createBinop(loc, bar, cir::BinOpKind::Div, tmp);
388 auto falseBranchBuilder = [&](mlir::OpBuilder &, mlir::Location) {
389 mlir::Value r = builder.
createBinop(loc,
c, cir::BinOpKind::Div,
391 mlir::Value rc = builder.
createBinop(loc, r, cir::BinOpKind::Mul,
c);
392 mlir::Value tmp = builder.
createBinop(loc, d, cir::BinOpKind::Add,
395 mlir::Value ar = builder.
createBinop(loc, a, cir::BinOpKind::Mul, r);
398 mlir::Value e = builder.
createBinop(loc, arb, cir::BinOpKind::Div, tmp);
400 mlir::Value br = builder.
createBinop(loc,
b, cir::BinOpKind::Mul, r);
402 builder.
createBinop(loc, br, cir::BinOpKind::Sub, a);
403 mlir::Value f = builder.
createBinop(loc, bra, cir::BinOpKind::Div, tmp);
409 auto cFabs = cir::FAbsOp::create(builder, loc,
c);
410 auto dFabs = cir::FAbsOp::create(builder, loc, d);
411 cir::CmpOp cmpResult =
412 builder.
createCompare(loc, cir::CmpOpKind::ge, cFabs, dFabs);
413 auto ternary = cir::TernaryOp::create(builder, loc, cmpResult,
414 trueBranchBuilder, falseBranchBuilder);
416 return ternary.getResult();
423 auto getHigherPrecisionFPType = [&context](mlir::Type type) -> mlir::Type {
424 if (mlir::isa<cir::FP16Type>(type))
425 return cir::SingleType::get(&context);
427 if (mlir::isa<cir::SingleType>(type) || mlir::isa<cir::BF16Type>(type))
428 return cir::DoubleType::get(&context);
430 if (mlir::isa<cir::DoubleType>(type))
431 return cir::LongDoubleType::get(&context, type);
436 auto getFloatTypeSemantics =
437 [&cc](mlir::Type type) ->
const llvm::fltSemantics & {
439 if (mlir::isa<cir::FP16Type>(type))
442 if (mlir::isa<cir::BF16Type>(type))
445 if (mlir::isa<cir::SingleType>(type))
448 if (mlir::isa<cir::DoubleType>(type))
451 if (mlir::isa<cir::LongDoubleType>(type)) {
453 llvm_unreachable(
"NYI Float type semantics with OpenMP");
457 if (mlir::isa<cir::FP128Type>(type)) {
459 llvm_unreachable(
"NYI Float type semantics with OpenMP");
463 assert(
false &&
"Unsupported float type semantics");
466 const mlir::Type higherElementType = getHigherPrecisionFPType(elementType);
467 const llvm::fltSemantics &elementTypeSemantics =
468 getFloatTypeSemantics(elementType);
469 const llvm::fltSemantics &higherElementTypeSemantics =
470 getFloatTypeSemantics(higherElementType);
479 if (llvm::APFloat::semanticsMaxExponent(elementTypeSemantics) * 2 + 1 <=
480 llvm::APFloat::semanticsMaxExponent(higherElementTypeSemantics)) {
481 return higherElementType;
491 mlir::Location loc, cir::ComplexDivOp op, mlir::Value lhsReal,
492 mlir::Value lhsImag, mlir::Value rhsReal, mlir::Value rhsImag,
494 cir::ComplexType complexTy = op.getType();
495 if (mlir::isa<cir::FPTypeInterface>(complexTy.getElementType())) {
496 cir::ComplexRangeKind range = op.getRange();
497 if (range == cir::ComplexRangeKind::Improved)
501 if (range == cir::ComplexRangeKind::Full)
503 loc, complexTy, lhsReal, lhsImag, rhsReal,
506 if (range == cir::ComplexRangeKind::Promoted) {
507 mlir::Type originalElementType = complexTy.getElementType();
508 mlir::Type higherPrecisionElementType =
510 originalElementType);
512 if (!higherPrecisionElementType)
516 cir::CastKind floatingCastKind = cir::CastKind::floating;
517 lhsReal = builder.
createCast(floatingCastKind, lhsReal,
518 higherPrecisionElementType);
519 lhsImag = builder.
createCast(floatingCastKind, lhsImag,
520 higherPrecisionElementType);
521 rhsReal = builder.
createCast(floatingCastKind, rhsReal,
522 higherPrecisionElementType);
523 rhsImag = builder.
createCast(floatingCastKind, rhsImag,
524 higherPrecisionElementType);
527 builder, loc, lhsReal, lhsImag, rhsReal, rhsImag);
532 mlir::Value finalReal =
533 builder.
createCast(floatingCastKind, resultReal, originalElementType);
534 mlir::Value finalImag =
535 builder.
createCast(floatingCastKind, resultImag, originalElementType);
544void LoweringPreparePass::lowerComplexDivOp(cir::ComplexDivOp op) {
545 cir::CIRBaseBuilderTy builder(getContext());
546 builder.setInsertionPointAfter(op);
547 mlir::Location loc = op.getLoc();
548 mlir::TypedValue<cir::ComplexType> lhs = op.getLhs();
549 mlir::TypedValue<cir::ComplexType> rhs = op.getRhs();
555 mlir::Value loweredResult =
557 rhsImag, getContext(), *astCtx);
558 op.replaceAllUsesWith(loweredResult);
562static llvm::StringRef
565 case llvm::APFloat::S_IEEEhalf:
567 case llvm::APFloat::S_IEEEsingle:
569 case llvm::APFloat::S_IEEEdouble:
571 case llvm::APFloat::S_PPCDoubleDouble:
573 case llvm::APFloat::S_x87DoubleExtended:
575 case llvm::APFloat::S_IEEEquad:
578 llvm_unreachable(
"unsupported floating point type");
584 mlir::Location loc, cir::ComplexMulOp op,
585 mlir::Value lhsReal, mlir::Value lhsImag,
586 mlir::Value rhsReal, mlir::Value rhsImag) {
588 mlir::Value resultRealLhs =
589 builder.
createBinop(loc, lhsReal, cir::BinOpKind::Mul, rhsReal);
590 mlir::Value resultRealRhs =
591 builder.
createBinop(loc, lhsImag, cir::BinOpKind::Mul, rhsImag);
592 mlir::Value resultImagLhs =
593 builder.
createBinop(loc, lhsReal, cir::BinOpKind::Mul, rhsImag);
594 mlir::Value resultImagRhs =
595 builder.
createBinop(loc, lhsImag, cir::BinOpKind::Mul, rhsReal);
597 loc, resultRealLhs, cir::BinOpKind::Sub, resultRealRhs);
599 loc, resultImagLhs, cir::BinOpKind::Add, resultImagRhs);
600 mlir::Value algebraicResult =
603 cir::ComplexType complexTy = op.getType();
604 cir::ComplexRangeKind rangeKind = op.getRange();
605 if (mlir::isa<cir::IntType>(complexTy.getElementType()) ||
606 rangeKind == cir::ComplexRangeKind::Basic ||
607 rangeKind == cir::ComplexRangeKind::Improved ||
608 rangeKind == cir::ComplexRangeKind::Promoted)
609 return algebraicResult;
616 mlir::Value resultRealIsNaN = builder.
createIsNaN(loc, resultReal);
617 mlir::Value resultImagIsNaN = builder.
createIsNaN(loc, resultImag);
618 mlir::Value resultRealAndImagAreNaN =
621 return cir::TernaryOp::create(
622 builder, loc, resultRealAndImagAreNaN,
623 [&](mlir::OpBuilder &, mlir::Location) {
626 lhsReal, lhsImag, rhsReal, rhsImag);
629 [&](mlir::OpBuilder &, mlir::Location) {
635void LoweringPreparePass::lowerComplexMulOp(cir::ComplexMulOp op) {
636 cir::CIRBaseBuilderTy builder(getContext());
637 builder.setInsertionPointAfter(op);
638 mlir::Location loc = op.getLoc();
639 mlir::TypedValue<cir::ComplexType> lhs = op.getLhs();
640 mlir::TypedValue<cir::ComplexType> rhs = op.getRhs();
645 mlir::Value loweredResult =
lowerComplexMul(*
this, builder, loc, op, lhsReal,
646 lhsImag, rhsReal, rhsImag);
647 op.replaceAllUsesWith(loweredResult);
651void LoweringPreparePass::lowerUnaryOp(cir::UnaryOp op) {
652 mlir::Type ty = op.getType();
653 if (!mlir::isa<cir::ComplexType>(ty))
656 mlir::Location loc = op.getLoc();
657 cir::UnaryOpKind opKind = op.getKind();
659 CIRBaseBuilderTy builder(getContext());
660 builder.setInsertionPointAfter(op);
662 mlir::Value operand = op.getInput();
666 mlir::Value resultReal;
667 mlir::Value resultImag;
670 case cir::UnaryOpKind::Inc:
671 case cir::UnaryOpKind::Dec:
672 resultReal = builder.
createUnaryOp(loc, opKind, operandReal);
673 resultImag = operandImag;
676 case cir::UnaryOpKind::Plus:
677 case cir::UnaryOpKind::Minus:
678 resultReal = builder.
createUnaryOp(loc, opKind, operandReal);
679 resultImag = builder.
createUnaryOp(loc, opKind, operandImag);
682 case cir::UnaryOpKind::Not:
683 resultReal = operandReal;
685 builder.
createUnaryOp(loc, cir::UnaryOpKind::Minus, operandImag);
690 op.replaceAllUsesWith(result);
695LoweringPreparePass::buildCXXGlobalVarDeclInitFunc(cir::GlobalOp op) {
698 SmallString<256> fnName(
"__cxx_global_var_init");
700 uint32_t cnt = dynamicInitializerNames[fnName]++;
702 fnName +=
"." + llvm::Twine(cnt).str();
705 CIRBaseBuilderTy builder(getContext());
706 builder.setInsertionPointAfter(op);
707 cir::VoidType voidTy = builder.
getVoidTy();
708 auto fnType = cir::FuncType::get({}, voidTy);
709 FuncOp f = buildRuntimeFunction(builder, fnName, op.getLoc(), fnType,
710 cir::GlobalLinkageKind::InternalLinkage);
713 mlir::Block *entryBB = f.addEntryBlock();
714 if (!op.getCtorRegion().empty()) {
715 mlir::Block &block = op.getCtorRegion().front();
716 entryBB->getOperations().splice(entryBB->begin(), block.getOperations(),
717 block.begin(), std::prev(block.end()));
721 mlir::Region &dtorRegion = op.getDtorRegion();
722 if (!dtorRegion.empty()) {
726 builder.setInsertionPointToStart(&mlirModule.getBodyRegion().front());
727 cir::GlobalOp handle = buildRuntimeVariable(
728 builder,
"__dso_handle", op.getLoc(), builder.getI8Type(),
729 cir::GlobalLinkageKind::ExternalLinkage, cir::VisibilityKind::Hidden);
732 mlir::Block &dtorBlock = dtorRegion.front();
733 cir::CallOp dtorCall;
734 for (
auto op : reverse(dtorBlock.getOps<cir::CallOp>())) {
738 assert(dtorCall &&
"Expected a dtor call");
740 assert(dtorFunc &&
"Expected a dtor call");
744 auto voidPtrTy = cir::PointerType::get(voidTy);
745 auto voidFnTy = cir::FuncType::get({voidPtrTy}, voidTy);
746 auto voidFnPtrTy = cir::PointerType::get(voidFnTy);
747 auto handlePtrTy = cir::PointerType::get(handle.getSymType());
749 cir::FuncType::get({voidFnPtrTy, voidPtrTy, handlePtrTy}, voidTy);
750 const char *nameAtExit =
"__cxa_atexit";
751 cir::FuncOp fnAtExit =
752 buildRuntimeFunction(builder, nameAtExit, op.getLoc(), fnAtExitType);
756 builder.setInsertionPointAfter(dtorCall);
758 auto dtorPtrTy = cir::PointerType::get(dtorFunc.getFunctionType());
760 args[0] = cir::GetGlobalOp::create(builder, dtorCall.getLoc(), dtorPtrTy,
761 dtorFunc.getSymName());
762 args[0] = cir::CastOp::create(builder, dtorCall.getLoc(), voidFnPtrTy,
763 cir::CastKind::bitcast, args[0]);
765 cir::CastOp::create(builder, dtorCall.getLoc(), voidPtrTy,
766 cir::CastKind::bitcast, dtorCall.getArgOperand(0));
767 args[2] = cir::GetGlobalOp::create(builder, handle.getLoc(), handlePtrTy,
768 handle.getSymName());
769 builder.
createCallOp(dtorCall.getLoc(), fnAtExit, args);
771 entryBB->getOperations().splice(entryBB->end(), dtorBlock.getOperations(),
773 std::prev(dtorBlock.end()));
777 builder.setInsertionPointToEnd(entryBB);
778 mlir::Operation *yieldOp =
nullptr;
779 if (!op.getCtorRegion().empty()) {
780 mlir::Block &block = op.getCtorRegion().front();
781 yieldOp = &block.getOperations().back();
783 assert(!dtorRegion.empty());
784 mlir::Block &block = dtorRegion.front();
785 yieldOp = &block.getOperations().back();
788 assert(isa<cir::YieldOp>(*yieldOp));
789 cir::ReturnOp::create(builder, yieldOp->getLoc());
793void LoweringPreparePass::lowerGlobalOp(GlobalOp op) {
794 mlir::Region &ctorRegion = op.getCtorRegion();
795 mlir::Region &dtorRegion = op.getDtorRegion();
797 if (!ctorRegion.empty() || !dtorRegion.empty()) {
800 cir::FuncOp f = buildCXXGlobalVarDeclInitFunc(op);
803 ctorRegion.getBlocks().clear();
804 dtorRegion.getBlocks().clear();
807 dynamicInitializers.push_back(f);
813template <
typename AttributeTy>
814static llvm::SmallVector<mlir::Attribute>
818 for (
const auto &[name, priority] : list)
819 attrs.push_back(AttributeTy::get(context, name, priority));
823void LoweringPreparePass::buildGlobalCtorDtorList() {
824 if (!globalCtorList.empty()) {
825 llvm::SmallVector<mlir::Attribute> globalCtors =
829 mlirModule->setAttr(cir::CIRDialect::getGlobalCtorsAttrName(),
830 mlir::ArrayAttr::get(&getContext(), globalCtors));
833 if (!globalDtorList.empty()) {
834 llvm::SmallVector<mlir::Attribute> globalDtors =
837 mlirModule->setAttr(cir::CIRDialect::getGlobalDtorsAttrName(),
838 mlir::ArrayAttr::get(&getContext(), globalDtors));
842void LoweringPreparePass::buildCXXGlobalInitFunc() {
843 if (dynamicInitializers.empty())
850 SmallString<256> fnName;
858 llvm::raw_svector_ostream
out(fnName);
859 std::unique_ptr<clang::MangleContext> mangleCtx(
861 cast<clang::ItaniumMangleContext>(*mangleCtx)
864 fnName +=
"_GLOBAL__sub_I_";
868 CIRBaseBuilderTy builder(getContext());
869 builder.setInsertionPointToEnd(&mlirModule.getBodyRegion().back());
870 auto fnType = cir::FuncType::get({}, builder.
getVoidTy());
872 buildRuntimeFunction(builder, fnName, mlirModule.getLoc(), fnType,
873 cir::GlobalLinkageKind::ExternalLinkage);
874 builder.setInsertionPointToStart(f.addEntryBlock());
875 for (cir::FuncOp &f : dynamicInitializers)
879 globalCtorList.emplace_back(fnName,
880 cir::GlobalCtorAttr::getDefaultPriority());
882 cir::ReturnOp::create(builder, f.getLoc());
885void LoweringPreparePass::lowerDynamicCastOp(DynamicCastOp op) {
886 CIRBaseBuilderTy builder(getContext());
887 builder.setInsertionPointAfter(op);
889 assert(astCtx &&
"AST context is not available during lowering prepare");
890 auto loweredValue = cxxABI->lowerDynamicCast(builder, *astCtx, op);
892 op.replaceAllUsesWith(loweredValue);
898 mlir::Operation *op, mlir::Type eltTy,
899 mlir::Value arrayAddr, uint64_t arrayLen,
902 mlir::Location loc = op->getLoc();
906 const unsigned sizeTypeSize =
908 uint64_t endOffset = isCtor ? arrayLen : arrayLen - 1;
909 mlir::Value endOffsetVal =
912 auto begin = cir::CastOp::create(builder, loc, eltTy,
913 cir::CastKind::array_to_ptrdecay, arrayAddr);
915 cir::PtrStrideOp::create(builder, loc, eltTy, begin, endOffsetVal);
916 mlir::Value start = isCtor ? begin : end;
917 mlir::Value stop = isCtor ? end : begin;
927 [&](mlir::OpBuilder &
b, mlir::Location loc) {
928 auto currentElement = cir::LoadOp::create(
b, loc, eltTy, tmpAddr);
929 mlir::Type boolTy = cir::BoolType::get(
b.getContext());
930 auto cmp = cir::CmpOp::create(builder, loc, boolTy, cir::CmpOpKind::ne,
931 currentElement, stop);
935 [&](mlir::OpBuilder &
b, mlir::Location loc) {
936 auto currentElement = cir::LoadOp::create(
b, loc, eltTy, tmpAddr);
938 cir::CallOp ctorCall;
939 op->walk([&](cir::CallOp
c) { ctorCall =
c; });
940 assert(ctorCall &&
"expected ctor call");
949 ctorCall->moveBefore(stride.getDefiningOp());
950 ctorCall->setOperand(0, currentElement);
951 auto nextElement = cir::PtrStrideOp::create(builder, loc, eltTy,
952 currentElement, stride);
959 op->replaceAllUsesWith(loop);
963void LoweringPreparePass::lowerArrayDtor(cir::ArrayDtor op) {
964 CIRBaseBuilderTy builder(getContext());
965 builder.setInsertionPointAfter(op.getOperation());
967 mlir::Type eltTy = op->getRegion(0).getArgument(0).getType();
970 mlir::cast<cir::ArrayType>(op.getAddr().getType().getPointee()).getSize();
975void LoweringPreparePass::lowerArrayCtor(cir::ArrayCtor op) {
976 cir::CIRBaseBuilderTy builder(getContext());
977 builder.setInsertionPointAfter(op.getOperation());
979 mlir::Type eltTy = op->getRegion(0).getArgument(0).getType();
982 mlir::cast<cir::ArrayType>(op.getAddr().getType().getPointee()).getSize();
987void LoweringPreparePass::runOnOp(mlir::Operation *op) {
988 if (
auto arrayCtor = dyn_cast<cir::ArrayCtor>(op)) {
989 lowerArrayCtor(arrayCtor);
990 }
else if (
auto arrayDtor = dyn_cast<cir::ArrayDtor>(op)) {
991 lowerArrayDtor(arrayDtor);
992 }
else if (
auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
994 }
else if (
auto complexDiv = mlir::dyn_cast<cir::ComplexDivOp>(op)) {
995 lowerComplexDivOp(complexDiv);
996 }
else if (
auto complexMul = mlir::dyn_cast<cir::ComplexMulOp>(op)) {
997 lowerComplexMulOp(complexMul);
998 }
else if (
auto glob = mlir::dyn_cast<cir::GlobalOp>(op)) {
1000 }
else if (
auto dynamicCast = mlir::dyn_cast<cir::DynamicCastOp>(op)) {
1001 lowerDynamicCastOp(dynamicCast);
1002 }
else if (
auto unary = mlir::dyn_cast<cir::UnaryOp>(op)) {
1003 lowerUnaryOp(unary);
1004 }
else if (
auto fnOp = dyn_cast<cir::FuncOp>(op)) {
1005 if (
auto globalCtor = fnOp.getGlobalCtorPriority())
1006 globalCtorList.emplace_back(fnOp.getName(), globalCtor.value());
1007 else if (
auto globalDtor = fnOp.getGlobalDtorPriority())
1008 globalDtorList.emplace_back(fnOp.getName(), globalDtor.value());
1012void LoweringPreparePass::runOnOperation() {
1013 mlir::Operation *op = getOperation();
1014 if (isa<::mlir::ModuleOp>(op))
1015 mlirModule = cast<::mlir::ModuleOp>(op);
1017 llvm::SmallVector<mlir::Operation *> opsToTransform;
1019 op->walk([&](mlir::Operation *op) {
1020 if (mlir::isa<cir::ArrayCtor, cir::ArrayDtor, cir::CastOp,
1021 cir::ComplexMulOp, cir::ComplexDivOp, cir::DynamicCastOp,
1022 cir::FuncOp, cir::GlobalOp, cir::UnaryOp>(op))
1023 opsToTransform.push_back(op);
1026 for (mlir::Operation *o : opsToTransform)
1029 buildCXXGlobalInitFunc();
1030 buildGlobalCtorDtorList();
1034 return std::make_unique<LoweringPreparePass>();
1037std::unique_ptr<Pass>
1039 auto pass = std::make_unique<LoweringPreparePass>();
1040 pass->setASTContext(astCtx);
1041 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::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::StoreOp createStore(mlir::Location loc, mlir::Value val, mlir::Value dst, bool isVolatile=false, mlir::IntegerAttr align={}, cir::MemOrderAttr order={})
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::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)
static LoweringPrepareCXXABI * createItaniumABI()
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 loweringPrepareX86CXXABI()
static bool opFuncExtraAttrs()
static bool fastMathFlags()
static bool loweringPrepareAArch64XXABI()
static bool astVarDeclInterface()