1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
|
#include "gen/inlineir.h"
#include "dmd/declaration.h"
#include "dmd/errors.h"
#include "dmd/expression.h"
#include "dmd/identifier.h"
#include "dmd/mtype.h"
#include "dmd/template.h"
#include "gen/attributes.h"
#include "gen/irstate.h"
#include "gen/llvmhelpers.h"
#include "gen/logger.h"
#include "gen/tollvm.h"
#include "gen/to_string.h"
#include "llvm/AsmParser/Parser.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
namespace {
/// Sets LLVMContext::setDiscardValueNames(false) upon construction and restores
/// the previous value upon destruction.
struct TempDisableDiscardValueNames {
llvm::LLVMContext &ctx;
bool previousValue;
TempDisableDiscardValueNames(llvm::LLVMContext &context)
: ctx(context), previousValue(context.shouldDiscardValueNames()) {
ctx.setDiscardValueNames(false);
}
~TempDisableDiscardValueNames() { ctx.setDiscardValueNames(previousValue); }
};
/// Adds the idol's function attributes to the wannabe
/// Note: don't add function _parameter_ attributes
void copyFnAttributes(llvm::Function *wannabe, llvm::Function *idol) {
auto attrSet = idol->getAttributes();
#if LDC_LLVM_VER >= 1400
auto fnAttrSet = attrSet.getFnAttrs();
wannabe->addFnAttrs(llvm::AttrBuilder(getGlobalContext(), fnAttrSet));
#else
auto fnAttrSet = attrSet.getFnAttributes();
wannabe->addAttributes(LLAttributeList::FunctionIndex, fnAttrSet);
#endif
}
llvm::StringRef exprToString(StringExp *strexp) {
assert(strexp);
auto str = strexp->peekString();
return {str.ptr, str.length};
}
} // anonymous namespace
void DtoCheckInlineIRPragma(Identifier *ident, Dsymbol *s) {
assert(ident != nullptr);
assert(s != nullptr);
if (TemplateDeclaration *td = s->isTemplateDeclaration()) {
Dsymbol *member = td->onemember;
if (!member) {
error(s->loc, "the `%s` pragma template must have exactly one member",
ident->toChars());
fatal();
}
FuncDeclaration *fun = member->isFuncDeclaration();
if (!fun) {
error(
s->loc,
"the `%s` pragma template's member must be a function declaration",
ident->toChars());
fatal();
}
// The magic inlineIR template is one of
// pragma(LDC_inline_ir)
// R inlineIR(string code, R, P...)(P);
// pragma(LDC_inline_ir)
// R inlineIREx(string prefix, string code, string suffix, R, P...)(P);
TemplateParameters ¶ms = *td->parameters;
bool valid_params = (params.length == 3 || params.length == 5) &&
params[params.length - 2]->isTemplateTypeParameter() &&
params[params.length - 1]->isTemplateTupleParameter();
if (valid_params) {
for (d_size_t i = 0; i < (params.length - 2); ++i) {
TemplateValueParameter *p0 = params[i]->isTemplateValueParameter();
valid_params = valid_params && p0 && p0->valType == Type::tstring;
}
}
if (!valid_params) {
error(s->loc,
"the `%s` pragma template must have three "
"(string, type and type tuple) or "
"five (string, string, string, type and type tuple) parameters",
ident->toChars());
fatal();
}
} else {
error(s->loc, "the `%s` pragma is only allowed on template declarations",
ident->toChars());
fatal();
}
}
DValue *DtoInlineIRExpr(const Loc &loc, FuncDeclaration *fdecl,
Expressions *arguments, LLValue *sretPointer) {
IF_LOG Logger::println("DtoInlineIRExpr @ %s", loc.toChars());
LOG_SCOPE;
// LLVM can't read textual IR with a Context that discards named Values, so
// temporarily disable value name discarding.
TempDisableDiscardValueNames tempDisable(gIR->context());
// Generate a random new function name. Because the inlineIR function is
// always inlined, this name does not escape the current compiled module; not
// even at -O0.
static size_t namecounter = 0;
std::string mangled_name = "inline.ir." + ldc::to_string(namecounter++);
TemplateInstance *tinst = fdecl->parent->isTemplateInstance();
assert(tinst);
// 1. Define the inline function (define a new function for each call)
{
// The magic inlineIR template is one of
// pragma(LDC_inline_ir)
// R inlineIR(string code, R, P...)(P);
// pragma(LDC_inline_ir)
// R inlineIREx(string prefix, string code, string suffix, R, P...)(P);
Objects &objs = tinst->tdtypes;
assert(objs.length == 3 || objs.length == 5);
const bool isExtended = (objs.length == 5);
llvm::StringRef prefix, code, suffix;
if (isExtended) {
Expression *a0 = isExpression(objs[0]);
assert(a0);
StringExp *prefexp = a0->toStringExp();
Expression *a1 = isExpression(objs[1]);
assert(a1);
StringExp *strexp = a1->toStringExp();
Expression *a2 = isExpression(objs[2]);
assert(a2);
StringExp *suffexp = a2->toStringExp();
prefix = exprToString(prefexp);
code = exprToString(strexp);
suffix = exprToString(suffexp);
} else {
Expression *a0 = isExpression(objs[0]);
assert(a0);
StringExp *strexp = a0->toStringExp();
code = exprToString(strexp);
}
Type *ret = isType(objs[isExtended ? 3 : 1]);
assert(ret);
Tuple *args = isTuple(objs[isExtended ? 4 : 2]);
assert(args);
Objects &arg_types = args->objects;
std::string str;
llvm::raw_string_ostream stream(str);
if (!prefix.empty()) {
stream << prefix << "\n";
}
stream << "define " << *DtoType(ret) << " @" << mangled_name << "(";
for (size_t i = 0; i < arg_types.length; ++i) {
Type *ty = isType(arg_types[i]);
if (!ty) {
error(tinst->loc,
"All parameters of a template defined with pragma "
"`LDC_inline_ir`, except for the first one or the first three"
", should be types");
fatal();
}
if (i != 0)
stream << ", ";
stream << *DtoType(ty);
}
stream << ")\n{\n" << code;
if (ret->ty == TY::Tvoid) {
stream << "\nret void";
}
stream << "\n}";
if (!suffix.empty()) {
stream << "\n" << suffix;
}
llvm::SMDiagnostic err;
std::unique_ptr<llvm::Module> m =
llvm::parseAssemblyString(stream.str().c_str(), err, gIR->context());
std::string errstr(err.getMessage());
if (!errstr.empty()) {
error(tinst->loc,
"can't parse inline LLVM IR:\n`%s`\n%s\n%s\nThe input string "
"was:\n`%s`",
err.getLineContents().str().c_str(),
(std::string(err.getColumnNo(), ' ') + '^').c_str(), errstr.c_str(),
stream.str().c_str());
fatal();
}
m->setDataLayout(gIR->module.getDataLayout());
llvm::Linker(gIR->module).linkInModule(std::move(m));
}
// 2. Call the function that was just defined and return the returnvalue
{
llvm::Function *fun = gIR->module.getFunction(mangled_name);
// Apply some parent function attributes to the inlineIR function too. This
// is needed e.g. when the parent function has "unsafe-fp-math"="true"
// applied.
{
assert(!gIR->funcGenStates.empty() && "Inline ir outside function");
auto enclosingFunc = gIR->topfunc();
assert(enclosingFunc);
copyFnAttributes(fun, enclosingFunc);
}
fun->setLinkage(llvm::GlobalValue::PrivateLinkage);
fun->removeFnAttr(llvm::Attribute::NoInline);
fun->addFnAttr(llvm::Attribute::AlwaysInline);
fun->setCallingConv(llvm::CallingConv::C);
// Build the runtime arguments
llvm::SmallVector<llvm::Value *, 8> args;
args.reserve(arguments->length);
for (auto arg : *arguments) {
args.push_back(DtoRVal(arg));
}
llvm::Value *rv = gIR->ir->CreateCall(fun, args);
Type *type = fdecl->type->nextOf();
if (sretPointer) {
DtoStore(rv, DtoBitCast(sretPointer, getPtrToType(rv->getType())));
return new DLValue(type, sretPointer);
}
// dump struct and static array return values to memory
if (DtoIsInMemoryOnly(type->toBasetype())) {
LLValue *lval = DtoAllocaDump(rv, type, ".__ir_ret");
return new DLValue(type, lval);
}
// return call as im value
return new DImValue(type, rv);
}
}
|