1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/GenericValue.h"
4 #include "llvm/ExecutionEngine/MCJIT.h"
5 #include "llvm/Passes/PassBuilder.h"
6 #include "llvm/IR/Argument.h"
7 #include "llvm/IR/Attributes.h"
8 #include "llvm/IR/BasicBlock.h"
9 #include "llvm/IR/Constants.h"
10 #include "llvm/IR/DerivedTypes.h"
11 #include "llvm/IR/Function.h"
12 #include "llvm/IR/IRBuilder.h"
13 #include "llvm/IR/Instructions.h"
14 #include "llvm/IR/Intrinsics.h"
15 #include "llvm/Analysis/Passes.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/Type.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/TargetSelect.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/ADT/APFloat.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/IR/Verifier.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ExecutionEngine/ObjectCache.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Path.h"
37 #include <symengine/llvm_double.h>
44 #if (LLVM_VERSION_MAJOR >= 10)
45 using std::make_unique;
47 using llvm::make_unique;
49 #if (LLVM_VERSION_MAJOR < 18)
50 using CodeGenOptLevel = llvm::CodeGenOpt::Level;
52 using CodeGenOptLevel = llvm::CodeGenOptLevel;
59 LLVMVisitor::LLVMVisitor() =
default;
60 LLVMVisitor::~LLVMVisitor() =
default;
62 llvm::Value *LLVMVisitor::apply(
const Basic &b)
68 void LLVMVisitor::init(
const vec_basic &x,
const Basic &b,
bool symbolic_cse,
71 init(x, {b.rcp_from_this()}, symbolic_cse, opt_level);
74 llvm::Function *LLVMVisitor::get_function_type(llvm::LLVMContext *context)
77 for (
int i = 0; i < 2; i++) {
78 inp.
push_back(llvm::PointerType::get(get_float_type(context), 0));
80 llvm::FunctionType *function_type = llvm::FunctionType::get(
81 llvm::Type::getVoidTy(*context), inp,
false);
82 auto F = llvm::Function::Create(function_type,
83 llvm::Function::InternalLinkage,
"",
mod);
84 F->setCallingConv(llvm::CallingConv::C);
85 #if (LLVM_VERSION_MAJOR < 5)
87 llvm::SmallVector<llvm::AttributeSet, 4> attrs;
88 llvm::AttributeSet PAS;
91 B.addAttribute(llvm::Attribute::ReadOnly);
92 B.addAttribute(llvm::Attribute::NoCapture);
93 PAS = llvm::AttributeSet::get(
mod->getContext(), 1U, B);
99 B.addAttribute(llvm::Attribute::NoCapture);
100 PAS = llvm::AttributeSet::get(
mod->getContext(), 2U, B);
103 attrs.push_back(PAS);
106 B.addAttribute(llvm::Attribute::NoUnwind);
107 B.addAttribute(llvm::Attribute::UWTable);
108 PAS = llvm::AttributeSet::get(
mod->getContext(), ~0U, B);
111 attrs.push_back(PAS);
113 F->setAttributes(llvm::AttributeSet::get(
mod->getContext(), attrs));
116 F->addParamAttr(0, llvm::Attribute::ReadOnly);
117 F->addParamAttr(0, llvm::Attribute::NoCapture);
118 F->addParamAttr(1, llvm::Attribute::NoCapture);
119 F->addFnAttr(llvm::Attribute::NoUnwind);
120 #if (LLVM_VERSION_MAJOR < 15)
121 F->addFnAttr(llvm::Attribute::UWTable);
123 F->addFnAttr(llvm::Attribute::getWithUWTableKind(
124 *context, llvm::UWTableKind::Default));
130 void LLVMVisitor::init(
const vec_basic &inputs,
const vec_basic &outputs,
131 const bool symbolic_cse,
unsigned opt_level)
133 executionengine.reset();
134 llvm::InitializeNativeTarget();
135 llvm::InitializeNativeTargetAsmPrinter();
136 llvm::InitializeNativeTargetAsmParser();
137 context = make_unique<llvm::LLVMContext>();
142 = make_unique<llvm::Module>(
"SymEngine", *context.get());
143 module->setDataLayout(
"");
146 auto F = get_function_type(context.get());
151 llvm::BasicBlock *BB = llvm::BasicBlock::Create(*context,
"EntryBlock", F);
156 llvm::IRBuilder<> _builder(BB);
157 builder =
reinterpret_cast<IRBuilder *
>(&_builder);
158 builder->SetInsertPoint(BB);
159 auto fmf = llvm::FastMathFlags();
161 builder->setFastMathFlags(fmf);
164 auto input_arg = &(*(F->args().begin()));
165 for (
unsigned i = 0; i < inputs.size(); i++) {
166 if (not is_a<Symbol>(*inputs[i])) {
167 throw SymEngineException(
"Input contains a non-symbol.");
170 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*context), i);
171 auto ptr = builder->CreateGEP(get_float_type(context.get()), input_arg,
173 result_ = builder->CreateLoad(get_float_type(context.get()), ptr);
174 symbol_ptrs.push_back(result_);
177 auto it = F->args().begin();
178 #if (LLVM_VERSION_MAJOR < 5)
179 auto out = &(*(++it));
181 auto out = &(*(it + 1));
186 vec_basic reduced_exprs;
187 vec_pair replacements;
189 SymEngine::cse(replacements, reduced_exprs, outputs);
190 for (
auto &rep : replacements) {
192 replacement_symbol_ptrs[rep.first] = apply(*(rep.second));
195 for (
unsigned i = 0; i < outputs.size(); i++) {
196 output_vals.
push_back(apply(*reduced_exprs[i]));
200 for (
unsigned i = 0; i < outputs.size(); i++) {
201 output_vals.
push_back(apply(*outputs[i]));
206 for (
unsigned i = 0; i < outputs.size(); i++) {
208 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*context), i);
210 = builder->CreateGEP(get_float_type(context.get()), out, index);
211 builder->CreateStore(output_vals[i], ptr);
215 builder->CreateRetVoid();
218 llvm::verifyFunction(*F, &llvm::outs());
231 #if (LLVM_VERSION_MAJOR < 14)
232 using OptimizationLevel = llvm::PassBuilder::OptimizationLevel;
234 using OptimizationLevel = llvm::OptimizationLevel;
236 llvm::PassBuilder PB;
237 llvm::ModuleAnalysisManager MAM;
238 llvm::CGSCCAnalysisManager CGAM;
239 llvm::FunctionAnalysisManager FAM;
240 llvm::LoopAnalysisManager LAM;
241 PB.registerModuleAnalyses(MAM);
242 PB.registerCGSCCAnalyses(CGAM);
243 PB.registerFunctionAnalyses(FAM);
244 PB.registerLoopAnalyses(LAM);
245 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
246 llvm::FunctionPassManager FPM;
247 OptimizationLevel pb_opt_level{OptimizationLevel::O3};
248 if (opt_level == 0) {
249 pb_opt_level = OptimizationLevel::O0;
250 }
else if (opt_level == 1) {
251 pb_opt_level = OptimizationLevel::O1;
252 }
else if (opt_level == 2) {
253 pb_opt_level = OptimizationLevel::O2;
255 #if (LLVM_VERSION_MAJOR < 6)
256 FPM = PB.buildFunctionSimplificationPipeline(pb_opt_level);
257 #elif (LLVM_VERSION_MAJOR < 12)
258 FPM = PB.buildFunctionSimplificationPipeline(
259 pb_opt_level, llvm::PassBuilder::ThinLTOPhase::None);
261 FPM = PB.buildFunctionSimplificationPipeline(
262 pb_opt_level, llvm::ThinOrFullLTOPhase::None);
273 .setEngineKind(llvm::EngineKind::Kind::JIT)
274 .setOptLevel(
static_cast<CodeGenOptLevel
>(opt_level))
279 class MemoryBufferRefCallback :
public llvm::ObjectCache
283 MemoryBufferRefCallback(
std::string &ss) : ss_(ss) {}
285 void notifyObjectCompiled(
const llvm::Module *M,
286 llvm::MemoryBufferRef obj)
override
288 const char *c = obj.getBufferStart();
290 ss_.
assign(c, obj.getBufferSize());
294 getObject(
const llvm::Module *M)
override
300 MemoryBufferRefCallback callback(membuffer);
301 executionengine->setObjectCache(&callback);
303 executionengine->finalizeObject();
306 func = (intptr_t)executionengine->getPointerToFunction(F);
308 replacement_symbol_ptrs.clear();
312 LLVMDoubleVisitor::LLVMDoubleVisitor() =
default;
313 LLVMDoubleVisitor::~LLVMDoubleVisitor() =
default;
318 ((double (*)(
const double *,
double *))func)(vec.
data(), &ret);
322 void LLVMDoubleVisitor::call(
double *outs,
const double *inps)
const
324 ((double (*)(
const double *,
double *))func)(inps, outs);
327 #ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
332 ((
long double (*)(
const long double *,
long double *))func)(vec.
data(),
337 void LLVMLongDoubleVisitor::call(
long double *outs,
338 const long double *inps)
const
340 ((
long double (*)(
const long double *,
long double *))func)(inps, outs);
344 LLVMFloatVisitor::LLVMFloatVisitor() =
default;
345 LLVMFloatVisitor::~LLVMFloatVisitor() =
default;
350 ((float (*)(
const float *,
float *))func)(vec.
data(), &ret);
354 void LLVMFloatVisitor::call(
float *outs,
const float *inps)
const
356 ((float (*)(
const float *,
float *))func)(inps, outs);
359 void LLVMVisitor::set_double(
double d)
361 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()), d);
364 void LLVMVisitor::bvisit(
const Integer &x)
366 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()),
367 mp_get_d(x.as_integer_class()));
370 #ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
372 LLVMLongDoubleVisitor::LLVMLongDoubleVisitor() =
default;
373 LLVMLongDoubleVisitor::~LLVMLongDoubleVisitor() =
default;
375 void LLVMLongDoubleVisitor::convert_from_mpfr(
const Basic &x)
377 #ifndef HAVE_SYMENGINE_MPFR
378 throw NotImplementedError(
"Cannot convert to long double without MPFR");
380 RCP<const Basic> m = evalf(x, 128, EvalfDomain::Real);
381 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()),
386 void LLVMLongDoubleVisitor::visit(
const Integer &x)
388 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()),
393 void LLVMVisitor::bvisit(
const Rational &x)
395 set_double(mp_get_d(x.as_rational_class()));
398 #ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
399 void LLVMLongDoubleVisitor::visit(
const Rational &x)
401 convert_from_mpfr(x);
405 void LLVMVisitor::bvisit(
const RealDouble &x)
410 #ifdef HAVE_SYMENGINE_MPFR
411 void LLVMVisitor::bvisit(
const RealMPFR &x)
413 set_double(mpfr_get_d(x.i.get_mpfr_t(), MPFR_RNDN));
415 #ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
416 void LLVMLongDoubleVisitor::visit(
const RealMPFR &x)
418 convert_from_mpfr(x);
423 void LLVMVisitor::bvisit(
const Add &x)
425 llvm::Value *tmp, *tmp1, *tmp2;
426 auto it = x.get_dict().begin();
428 if (
eq(*x.get_coef(), *zero)) {
430 if (
eq(*one, *(it->second))) {
431 tmp = apply(*(it->first));
433 tmp1 = apply(*(it->first));
434 tmp2 = apply(*(it->second));
435 tmp = builder->CreateFMul(tmp1, tmp2);
439 tmp = apply(*x.get_coef());
442 for (; it != x.get_dict().
end(); ++it) {
443 if (
eq(*one, *(it->second))) {
444 tmp1 = apply(*(it->first));
445 tmp = builder->CreateFAdd(tmp, tmp1);
452 tmp1 = apply(*(it->first));
453 tmp2 = apply(*(it->second));
454 tmp = builder->CreateFAdd(tmp, builder->CreateFMul(tmp1, tmp2));
460 void LLVMVisitor::bvisit(
const Mul &x)
462 llvm::Value *tmp =
nullptr;
464 for (
const auto &p : x.get_args()) {
468 tmp = builder->CreateFMul(tmp, apply(*p));
475 llvm::Function *LLVMVisitor::get_powi()
479 #if (LLVM_VERSION_MAJOR > 12)
480 arg_type.
push_back(llvm::Type::getInt32Ty(
mod->getContext()));
482 return llvm::Intrinsic::getDeclaration(
mod, llvm::Intrinsic::powi,
486 llvm::Function *get_float_intrinsic(llvm::Type *type, llvm::Intrinsic::ID
id,
487 unsigned n, llvm::Module *
mod)
490 return llvm::Intrinsic::getDeclaration(
mod,
id, arg_type);
493 void LLVMVisitor::bvisit(
const Pow &x)
497 if (
eq(*(x.get_base()), *E)) {
499 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
500 llvm::Intrinsic::exp, 1,
mod);
502 }
else if (
eq(*(x.get_base()), *
integer(2))) {
504 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
505 llvm::Intrinsic::exp2, 1,
mod);
508 if (is_a<Integer>(*x.get_exp())) {
510 llvm::Value *tmp = apply(*x.get_base());
511 result_ = builder->CreateFMul(tmp, tmp);
515 int d = numeric_cast<int>(
516 mp_get_si(
static_cast<const Integer &
>(*x.get_exp())
517 .as_integer_class()));
518 result_ = llvm::ConstantInt::get(
519 llvm::Type::getInt32Ty(
mod->getContext()), d,
true);
526 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
527 llvm::Intrinsic::pow, 1,
mod);
530 auto r = builder->CreateCall(fun, args);
531 r->setTailCall(
true);
535 void LLVMVisitor::bvisit(
const Sin &x)
540 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
541 llvm::Intrinsic::sin, 1,
mod);
542 auto r = builder->CreateCall(fun, args);
543 r->setTailCall(
true);
547 void LLVMVisitor::bvisit(
const Cos &x)
552 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
553 llvm::Intrinsic::cos, 1,
mod);
554 auto r = builder->CreateCall(fun, args);
555 r->setTailCall(
true);
559 void LLVMVisitor::bvisit(
const Piecewise &x)
563 RCP<const Piecewise> pw = x.rcp_from_this_cast<
const Piecewise>();
565 if (
neq(*pw->get_vec().back().second, *boolTrue)) {
566 throw SymEngineException(
567 "LLVMDouble requires a (Expr, True) at the end of Piecewise");
570 if (pw->get_vec().size() > 2) {
571 PiecewiseVec rest = pw->get_vec();
572 rest.
erase(rest.begin());
573 auto rest_pw = piecewise(
std::move(rest));
575 new_pw.
push_back(*pw->get_vec().begin());
576 new_pw.push_back({rest_pw, pw->get_vec().back().second});
578 ->rcp_from_this_cast<
const Piecewise>();
579 }
else if (pw->get_vec().size() < 2) {
580 throw SymEngineException(
"Invalid Piecewise object");
583 auto cond_basic = pw->get_vec().front().second;
584 llvm::Value *cond = apply(*cond_basic);
586 cond = builder->CreateFCmpONE(
587 cond, llvm::ConstantFP::get(get_float_type(&
mod->getContext()), 0.0),
589 llvm::Function *
function = builder->GetInsertBlock()->getParent();
593 llvm::BasicBlock *then_bb
594 = llvm::BasicBlock::Create(
mod->getContext(),
"then",
function);
595 llvm::BasicBlock *else_bb
596 = llvm::BasicBlock::Create(
mod->getContext(),
"else");
597 llvm::BasicBlock *merge_bb
598 = llvm::BasicBlock::Create(
mod->getContext(),
"ifcont");
599 builder->CreateCondBr(cond, then_bb, else_bb);
602 builder->SetInsertPoint(then_bb);
603 llvm::Value *then_value = apply(*pw->get_vec().front().first);
604 builder->CreateBr(merge_bb);
608 then_bb = builder->GetInsertBlock();
611 #if (LLVM_VERSION_MAJOR < 16)
612 function->getBasicBlockList().push_back(else_bb);
614 function->insert(function->end(), else_bb);
616 builder->SetInsertPoint(else_bb);
617 llvm::Value *else_value = apply(*pw->get_vec().back().first);
618 builder->CreateBr(merge_bb);
622 else_bb = builder->GetInsertBlock();
625 #if (LLVM_VERSION_MAJOR < 16)
626 function->getBasicBlockList().push_back(merge_bb);
628 function->insert(function->end(), merge_bb);
630 builder->SetInsertPoint(merge_bb);
631 llvm::PHINode *phi_node
632 = builder->CreatePHI(get_float_type(&
mod->getContext()), 2);
634 phi_node->addIncoming(then_value, then_bb);
635 phi_node->addIncoming(else_value, else_bb);
639 void LLVMVisitor::bvisit(
const Sign &x)
641 const auto x2 = x.get_arg();
643 new_pw.
push_back({real_double(0.0),
Eq(x2, real_double(0.0))});
644 new_pw.push_back({real_double(-1.0),
Lt(x2, real_double(0.0))});
645 new_pw.push_back({real_double(1.0), boolTrue});
646 auto pw = rcp_static_cast<const Piecewise>(piecewise(
std::move(new_pw)));
650 void LLVMVisitor::bvisit(
const Contains &cts)
652 llvm::Value *expr = apply(*cts.get_expr());
653 const auto set = cts.get_set();
654 if (is_a<Interval>(*set)) {
655 const auto &interv = down_cast<const Interval &>(*set);
656 llvm::Value *start = apply(*interv.get_start());
657 llvm::Value *
end = apply(*interv.get_end());
658 const bool left_open = interv.get_left_open();
659 const bool right_open = interv.get_right_open();
660 llvm::Value *left_ok;
661 llvm::Value *right_ok;
662 left_ok = (left_open) ? builder->CreateFCmpOLT(start, expr)
663 : builder->CreateFCmpOLE(start, expr);
664 right_ok = (right_open) ? builder->CreateFCmpOLT(expr, end)
665 : builder->CreateFCmpOLE(expr, end);
666 result_ = builder->CreateAnd(left_ok, right_ok);
667 result_ = builder->CreateUIToFP(result_,
668 get_float_type(&
mod->getContext()));
670 throw SymEngineException(
"LLVMVisitor: only ``Interval`` "
671 "implemented for ``Contains``.");
675 void LLVMVisitor::bvisit(
const Infty &x)
677 if (x.is_negative_infinity()) {
678 result_ = llvm::ConstantFP::getInfinity(
679 get_float_type(&
mod->getContext()),
true);
680 }
else if (x.is_positive_infinity()) {
681 result_ = llvm::ConstantFP::getInfinity(
682 get_float_type(&
mod->getContext()),
false);
684 throw SymEngineException(
685 "LLVMDouble can only represent real valued infinity");
689 void LLVMVisitor::bvisit(
const NaN &x)
691 result_ = llvm::ConstantFP::getNaN(get_float_type(&
mod->getContext()),
695 void LLVMVisitor::bvisit(
const BooleanAtom &x)
697 const bool val = x.get_val();
698 set_double(val ? 1.0 : 0.0);
701 void LLVMVisitor::bvisit(
const Log &x)
706 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
707 llvm::Intrinsic::log, 1,
mod);
708 auto r = builder->CreateCall(fun, args);
709 r->setTailCall(
true);
713 #define SYMENGINE_LOGIC_FUNCTION(Class, method) \
714 void LLVMVisitor::bvisit(const Class &x) \
716 llvm::Value *value = nullptr; \
719 llvm::Value *zero_val = result_; \
720 for (auto &p : x.get_container()) { \
721 tmp = builder->CreateFCmpONE(apply(*p), zero_val); \
722 if (value == nullptr) { \
725 value = builder->method(value, tmp); \
728 result_ = builder->CreateUIToFP(value, \
729 get_float_type(&mod->getContext())); \
732 SYMENGINE_LOGIC_FUNCTION(And, CreateAnd);
733 SYMENGINE_LOGIC_FUNCTION(Or, CreateOr);
734 SYMENGINE_LOGIC_FUNCTION(Xor, CreateXor);
736 void LLVMVisitor::bvisit(
const Not &x)
738 builder->CreateNot(apply(*x.get_arg()));
741 #define SYMENGINE_RELATIONAL_FUNCTION(Class, method) \
742 void LLVMVisitor::bvisit(const Class &x) \
744 llvm::Value *left = apply(*x.get_arg1()); \
745 llvm::Value *right = apply(*x.get_arg2()); \
746 result_ = builder->method(left, right); \
747 result_ = builder->CreateUIToFP(result_, \
748 get_float_type(&mod->getContext())); \
751 SYMENGINE_RELATIONAL_FUNCTION(Equality, CreateFCmpOEQ);
752 SYMENGINE_RELATIONAL_FUNCTION(Unequality, CreateFCmpONE);
753 SYMENGINE_RELATIONAL_FUNCTION(LessThan, CreateFCmpOLE);
754 SYMENGINE_RELATIONAL_FUNCTION(StrictLessThan, CreateFCmpOLT);
756 #define _SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
757 void LLVMDoubleVisitor::visit(const Class &x) \
759 vec_basic basic_args = x.get_args(); \
760 llvm::Function *func = get_external_function(#ext, basic_args.size()); \
761 std::vector<llvm::Value *> args; \
762 for (const auto &arg : basic_args) { \
763 args.push_back(apply(*arg)); \
765 auto r = builder->CreateCall(func, args); \
766 r->setTailCall(true); \
769 void LLVMFloatVisitor::visit(const Class &x) \
771 vec_basic basic_args = x.get_args(); \
772 llvm::Function *func = get_external_function(#ext + std::string("f"), \
773 basic_args.size()); \
774 std::vector<llvm::Value *> args; \
775 for (const auto &arg : basic_args) { \
776 args.push_back(apply(*arg)); \
778 auto r = builder->CreateCall(func, args); \
779 r->setTailCall(true); \
783 #ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
784 #define SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
785 _SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
786 void LLVMLongDoubleVisitor::visit(const Class &x) \
788 vec_basic basic_args = x.get_args(); \
789 llvm::Function *func = get_external_function(#ext + std::string("l"), \
790 basic_args.size()); \
791 std::vector<llvm::Value *> args; \
792 for (const auto &arg : basic_args) { \
793 args.push_back(apply(*arg)); \
795 auto r = builder->CreateCall(func, args); \
796 r->setTailCall(true); \
800 #define SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
801 _SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext)
804 SYMENGINE_MACRO_EXTERNAL_FUNCTION(Tan,
tan)
805 SYMENGINE_MACRO_EXTERNAL_FUNCTION(ASin,
asin)
806 SYMENGINE_MACRO_EXTERNAL_FUNCTION(ACos,
acos)
807 SYMENGINE_MACRO_EXTERNAL_FUNCTION(ATan,
atan)
808 SYMENGINE_MACRO_EXTERNAL_FUNCTION(ATan2,
atan2)
809 SYMENGINE_MACRO_EXTERNAL_FUNCTION(Sinh,
sinh)
810 SYMENGINE_MACRO_EXTERNAL_FUNCTION(Cosh,
cosh)
811 SYMENGINE_MACRO_EXTERNAL_FUNCTION(Tanh,
tanh)
812 SYMENGINE_MACRO_EXTERNAL_FUNCTION(ASinh,
asinh)
813 SYMENGINE_MACRO_EXTERNAL_FUNCTION(ACosh,
acosh)
814 SYMENGINE_MACRO_EXTERNAL_FUNCTION(ATanh,
atanh)
815 SYMENGINE_MACRO_EXTERNAL_FUNCTION(Gamma, tgamma)
816 SYMENGINE_MACRO_EXTERNAL_FUNCTION(LogGamma, lgamma)
817 SYMENGINE_MACRO_EXTERNAL_FUNCTION(Erf,
erf)
818 SYMENGINE_MACRO_EXTERNAL_FUNCTION(Erfc,
erfc)
820 void LLVMVisitor::bvisit(
const Abs &x)
825 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
826 llvm::Intrinsic::fabs, 1,
mod);
827 auto r = builder->CreateCall(fun, args);
828 r->setTailCall(
true);
832 void LLVMVisitor::bvisit(
const Min &x)
834 llvm::Value *value =
nullptr;
836 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
837 llvm::Intrinsic::minnum, 1,
mod);
838 for (
auto &arg : x.get_vec()) {
839 if (value !=
nullptr) {
843 auto r = builder->CreateCall(fun, args);
844 r->setTailCall(
true);
853 void LLVMVisitor::bvisit(
const Max &x)
855 llvm::Value *value =
nullptr;
857 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
858 llvm::Intrinsic::maxnum, 1,
mod);
859 for (
auto &arg : x.get_vec()) {
860 if (value !=
nullptr) {
864 auto r = builder->CreateCall(fun, args);
865 r->setTailCall(
true);
874 void LLVMVisitor::bvisit(
const Symbol &x)
877 for (
auto &symb : symbols) {
879 result_ = symbol_ptrs[i];
884 auto it = replacement_symbol_ptrs.find(x.rcp_from_this());
885 if (it != replacement_symbol_ptrs.end()) {
886 result_ = it->second;
890 throw SymEngineException(
"Symbol " + x.__str__()
891 +
" not in the symbols vector.");
894 llvm::Function *LLVMVisitor::get_external_function(
const std::string &name,
898 get_float_type(&
mod->getContext()));
899 llvm::FunctionType *func_type = llvm::FunctionType::get(
900 get_float_type(&
mod->getContext()), func_args,
false);
902 llvm::Function *func =
mod->getFunction(name);
904 func = llvm::Function::Create(
905 func_type, llvm::GlobalValue::ExternalLinkage, name,
mod);
906 func->setCallingConv(llvm::CallingConv::C);
908 #if (LLVM_VERSION_MAJOR < 5)
909 llvm::AttributeSet func_attr_set;
911 llvm::SmallVector<llvm::AttributeSet, 4> attrs;
912 llvm::AttributeSet attr_set;
914 llvm::AttrBuilder attr_builder;
915 attr_builder.addAttribute(llvm::Attribute::NoUnwind);
917 = llvm::AttributeSet::get(
mod->getContext(), ~0U, attr_builder);
920 attrs.push_back(attr_set);
921 func_attr_set = llvm::AttributeSet::get(
mod->getContext(), attrs);
923 func->setAttributes(func_attr_set);
925 func->addFnAttr(llvm::Attribute::NoUnwind);
930 void LLVMVisitor::bvisit(
const Constant &x)
932 set_double(eval_double(x));
935 #ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
936 void LLVMLongDoubleVisitor::visit(
const Constant &x)
938 convert_from_mpfr(x);
942 void LLVMVisitor::bvisit(
const Basic &x)
944 throw NotImplementedError(x.__str__());
955 llvm::InitializeNativeTarget();
956 llvm::InitializeNativeTargetAsmPrinter();
957 llvm::InitializeNativeTargetAsmParser();
958 context = make_unique<llvm::LLVMContext>();
962 = make_unique<llvm::Module>(
"SymEngine", *context);
963 module->setDataLayout(
"");
970 auto F = get_function_type(context.get());
975 .setEngineKind(llvm::EngineKind::Kind::JIT)
976 .setOptLevel(CodeGenOptLevel::Aggressive)
980 class MCJITObjectLoader :
public llvm::ObjectCache
986 void notifyObjectCompiled(
const llvm::Module *M,
987 llvm::MemoryBufferRef obj)
override
994 getObject(
const llvm::Module *M)
override
996 return llvm::MemoryBuffer::getMemBufferCopy(llvm::StringRef(s_));
1000 MCJITObjectLoader loader(s);
1001 executionengine->setObjectCache(&loader);
1002 executionengine->finalizeObject();
1004 func = (intptr_t)executionengine->getPointerToFunction(F);
1007 void LLVMVisitor::bvisit(
const Floor &x)
1010 llvm::Function *fun;
1012 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
1013 llvm::Intrinsic::floor, 1,
mod);
1014 auto r = builder->CreateCall(fun, args);
1015 r->setTailCall(
true);
1019 void LLVMVisitor::bvisit(
const Ceiling &x)
1022 llvm::Function *fun;
1024 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
1025 llvm::Intrinsic::ceil, 1,
mod);
1026 auto r = builder->CreateCall(fun, args);
1027 r->setTailCall(
true);
1031 void LLVMVisitor::bvisit(
const UnevaluatedExpr &x)
1033 apply(*x.get_arg());
1036 void LLVMVisitor::bvisit(
const Truncate &x)
1039 llvm::Function *fun;
1041 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
1042 llvm::Intrinsic::trunc, 1,
mod);
1043 auto r = builder->CreateCall(fun, args);
1044 r->setTailCall(
true);
1048 llvm::Type *LLVMDoubleVisitor::get_float_type(llvm::LLVMContext *context)
1050 return llvm::Type::getDoubleTy(*context);
1053 llvm::Type *LLVMFloatVisitor::get_float_type(llvm::LLVMContext *context)
1055 return llvm::Type::getFloatTy(*context);
1058 #if defined(SYMENGINE_HAVE_LLVM_LONG_DOUBLE)
1059 llvm::Type *LLVMLongDoubleVisitor::get_float_type(llvm::LLVMContext *context)
1061 return llvm::Type::getX86_FP80Ty(*context);
The lowest unit of symbolic representation.
Main namespace for SymEngine package.
RCP< const Basic > acos(const RCP< const Basic > &arg)
Canonicalize ACos:
std::enable_if< std::is_integral< T >::value, RCP< const Integer > >::type integer(T i)
bool eq(const Basic &a, const Basic &b)
Checks equality for a and b
RCP< const Boolean > Lt(const RCP< const Basic > &lhs, const RCP< const Basic > &rhs)
Returns the canonicalized StrictLessThan object from the arguments.
RCP< const Integer > mod(const Integer &n, const Integer &d)
modulo round toward zero
RCP< const Basic > atan2(const RCP< const Basic > &num, const RCP< const Basic > &den)
Canonicalize ATan2:
RCP< const Basic > asin(const RCP< const Basic > &arg)
Canonicalize ASin:
RCP< const Basic > tan(const RCP< const Basic > &arg)
Canonicalize Tan:
RCP< const Basic > cosh(const RCP< const Basic > &arg)
Canonicalize Cosh:
RCP< const Basic > atan(const RCP< const Basic > &arg)
Canonicalize ATan:
RCP< const Basic > asinh(const RCP< const Basic > &arg)
Canonicalize ASinh:
RCP< const Basic > tanh(const RCP< const Basic > &arg)
Canonicalize Tanh:
RCP< const Basic > atanh(const RCP< const Basic > &arg)
Canonicalize ATanh:
RCP< const Basic > erfc(const RCP< const Basic > &arg)
Canonicalize Erfc:
RCP< const Basic > acosh(const RCP< const Basic > &arg)
Canonicalize ACosh:
RCP< const Boolean > Eq(const RCP< const Basic > &lhs)
Returns the canonicalized Equality object from a single argument.
bool neq(const Basic &a, const Basic &b)
Checks inequality for a and b
RCP< const Basic > erf(const RCP< const Basic > &arg)
Canonicalize Erf:
RCP< const Basic > sinh(const RCP< const Basic > &arg)
Canonicalize Sinh: