Newer
Older
dub_jkp / source / dub / compilers / ldc.d
  1. /**
  2. LDC compiler support.
  3.  
  4. Copyright: © 2013-2013 rejectedsoftware e.K.
  5. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  6. Authors: Sönke Ludwig
  7. */
  8. module dub.compilers.ldc;
  9.  
  10. import dub.compilers.compiler;
  11. import dub.compilers.utils;
  12. import dub.internal.utils;
  13. import dub.internal.vibecompat.core.file;
  14. import dub.internal.vibecompat.inet.path;
  15. import dub.internal.logging;
  16.  
  17. import std.algorithm;
  18. import std.array;
  19. import std.exception;
  20. import std.typecons;
  21.  
  22.  
  23. class LDCCompiler : Compiler {
  24. private static immutable s_options = [
  25. tuple(BuildOption.debugMode, ["-d-debug"]),
  26. tuple(BuildOption.releaseMode, ["-release"]),
  27. tuple(BuildOption.coverage, ["-cov"]),
  28. tuple(BuildOption.coverageCTFE, ["-cov=ctfe"]),
  29. tuple(BuildOption.debugInfo, ["-g"]),
  30. tuple(BuildOption.debugInfoC, ["-gc"]),
  31. tuple(BuildOption.alwaysStackFrame, ["-disable-fp-elim"]),
  32. //tuple(BuildOption.stackStomping, ["-?"]),
  33. tuple(BuildOption.inline, ["-enable-inlining", "-Hkeep-all-bodies"]),
  34. tuple(BuildOption.noBoundsCheck, ["-boundscheck=off"]),
  35. tuple(BuildOption.optimize, ["-O3"]),
  36. tuple(BuildOption.profile, ["-fdmd-trace-functions"]),
  37. tuple(BuildOption.unittests, ["-unittest"]),
  38. tuple(BuildOption.verbose, ["-v"]),
  39. tuple(BuildOption.ignoreUnknownPragmas, ["-ignore"]),
  40. tuple(BuildOption.syntaxOnly, ["-o-"]),
  41. tuple(BuildOption.warnings, ["-wi"]),
  42. tuple(BuildOption.warningsAsErrors, ["-w"]),
  43. tuple(BuildOption.ignoreDeprecations, ["-d"]),
  44. tuple(BuildOption.deprecationWarnings, ["-dw"]),
  45. tuple(BuildOption.deprecationErrors, ["-de"]),
  46. tuple(BuildOption.property, ["-property"]),
  47. //tuple(BuildOption.profileGC, ["-?"]),
  48. tuple(BuildOption.betterC, ["-betterC"]),
  49. tuple(BuildOption.lowmem, ["-lowmem"]),
  50. tuple(BuildOption.color, ["-enable-color"]),
  51.  
  52. tuple(BuildOption._docs, ["-Dd=docs"]),
  53. tuple(BuildOption._ddox, ["-Xf=docs.json", "-Dd=__dummy_docs"]),
  54. ];
  55.  
  56. @property string name() const { return "ldc"; }
  57.  
  58. enum ldcVersionRe = `^version\s+v?(\d+\.\d+\.\d+[A-Za-z0-9.+-]*)`;
  59.  
  60. unittest {
  61. import std.regex : matchFirst, regex;
  62. auto probe = `
  63. binary /usr/bin/ldc2
  64. version 1.11.0 (DMD v2.081.2, LLVM 6.0.1)
  65. config /etc/ldc2.conf (x86_64-pc-linux-gnu)
  66. `;
  67. auto re = regex(ldcVersionRe, "m");
  68. auto c = matchFirst(probe, re);
  69. assert(c && c.length > 1 && c[1] == "1.11.0");
  70. }
  71.  
  72. string determineVersion(string compiler_binary, string verboseOutput)
  73. {
  74. import std.regex : matchFirst, regex;
  75. auto ver = matchFirst(verboseOutput, regex(ldcVersionRe, "m"));
  76. return ver && ver.length > 1 ? ver[1] : null;
  77. }
  78.  
  79. BuildPlatform determinePlatform(ref BuildSettings settings, string compiler_binary, string arch_override)
  80. {
  81. string[] arch_flags;
  82. switch (arch_override) {
  83. case "": break;
  84. case "x86": arch_flags = ["-march=x86"]; break;
  85. case "x86_mscoff": arch_flags = ["-march=x86"]; break;
  86. case "x86_64": arch_flags = ["-march=x86-64"]; break;
  87. case "aarch64": arch_flags = ["-march=aarch64"]; break;
  88. case "powerpc64": arch_flags = ["-march=powerpc64"]; break;
  89. default:
  90. if (arch_override.canFind('-'))
  91. arch_flags = ["-mtriple="~arch_override];
  92. else
  93. throw new UnsupportedArchitectureException(arch_override);
  94. break;
  95. }
  96. settings.addDFlags(arch_flags);
  97.  
  98. return probePlatform(
  99. compiler_binary,
  100. arch_flags ~ ["-c", "-o-", "-v"],
  101. arch_override
  102. );
  103. }
  104.  
  105. void prepareBuildSettings(ref BuildSettings settings, const scope ref BuildPlatform platform, BuildSetting fields = BuildSetting.all) const
  106. {
  107. import std.format : format;
  108. enforceBuildRequirements(settings);
  109.  
  110. if (!(fields & BuildSetting.options)) {
  111. foreach (t; s_options)
  112. if (settings.options & t[0])
  113. settings.addDFlags(t[1]);
  114. }
  115.  
  116. // since LDC always outputs multiple object files, avoid conflicts by default
  117. settings.addDFlags("--oq", format("-od=%s/obj", settings.targetPath));
  118.  
  119. if (!(fields & BuildSetting.versions)) {
  120. settings.addDFlags(settings.versions.map!(s => "-d-version="~s)().array());
  121. settings.versions = null;
  122. }
  123.  
  124. if (!(fields & BuildSetting.debugVersions)) {
  125. settings.addDFlags(settings.debugVersions.map!(s => "-d-debug="~s)().array());
  126. settings.debugVersions = null;
  127. }
  128.  
  129. if (!(fields & BuildSetting.importPaths)) {
  130. settings.addDFlags(settings.importPaths.map!(s => "-I"~s)().array());
  131. settings.importPaths = null;
  132. }
  133.  
  134. if (!(fields & BuildSetting.cImportPaths)) {
  135. settings.addDFlags(settings.cImportPaths.map!(s => "-I"~s)().array());
  136. settings.cImportPaths = null;
  137. }
  138.  
  139. if (!(fields & BuildSetting.stringImportPaths)) {
  140. settings.addDFlags(settings.stringImportPaths.map!(s => "-J"~s)().array());
  141. settings.stringImportPaths = null;
  142. }
  143.  
  144. if (!(fields & BuildSetting.sourceFiles)) {
  145. settings.addDFlags(settings.sourceFiles);
  146. settings.sourceFiles = null;
  147. }
  148.  
  149. if (!(fields & BuildSetting.libs)) {
  150. resolveLibs(settings, platform);
  151. settings.addLFlags(settings.libs.map!(l => "-l"~l)().array());
  152. }
  153.  
  154. if (!(fields & BuildSetting.lflags)) {
  155. settings.addDFlags(lflagsToDFlags(settings.lflags));
  156. settings.lflags = null;
  157. }
  158.  
  159. if (settings.options & BuildOption.pic) {
  160. if (platform.isWindows()) {
  161. /* This has nothing to do with PIC, but as the PIC option is exclusively
  162. * set internally for code that ends up in a dynamic library, explicitly
  163. * specify what `-shared` defaults to (`-shared` can't be used when
  164. * compiling only, without linking).
  165. * *Pre*pending the flags enables the user to override them.
  166. */
  167. settings.prependDFlags("-fvisibility=public", "-dllimport=all");
  168. } else {
  169. settings.addDFlags("-relocation-model=pic");
  170. }
  171. }
  172.  
  173. assert(fields & BuildSetting.dflags);
  174. assert(fields & BuildSetting.copyFiles);
  175. }
  176.  
  177. void extractBuildOptions(ref BuildSettings settings) const
  178. {
  179. Appender!(string[]) newflags;
  180. next_flag: foreach (f; settings.dflags) {
  181. foreach (t; s_options)
  182. if (t[1].canFind(f)) {
  183. settings.options |= t[0];
  184. continue next_flag;
  185. }
  186. if (f.startsWith("-d-version=")) settings.addVersions(f[11 .. $]);
  187. else if (f.startsWith("-d-debug=")) settings.addDebugVersions(f[9 .. $]);
  188. else newflags ~= f;
  189. }
  190. settings.dflags = newflags.data;
  191. }
  192.  
  193. string getTargetFileName(in BuildSettings settings, in BuildPlatform platform)
  194. const {
  195. assert(settings.targetName.length > 0, "No target name set.");
  196.  
  197. const p = platform.platform;
  198. final switch (settings.targetType) {
  199. case TargetType.autodetect: assert(false, "Configurations must have a concrete target type.");
  200. case TargetType.none: return null;
  201. case TargetType.sourceLibrary: return null;
  202. case TargetType.executable:
  203. if (p.canFind("windows"))
  204. return settings.targetName ~ ".exe";
  205. else if (p.canFind("wasm"))
  206. return settings.targetName ~ ".wasm";
  207. else return settings.targetName.idup;
  208. case TargetType.library:
  209. case TargetType.staticLibrary:
  210. if (p.canFind("windows") && !p.canFind("mingw"))
  211. return settings.targetName ~ ".lib";
  212. else return "lib" ~ settings.targetName ~ ".a";
  213. case TargetType.dynamicLibrary:
  214. if (p.canFind("windows"))
  215. return settings.targetName ~ ".dll";
  216. else if (p.canFind("darwin"))
  217. return "lib" ~ settings.targetName ~ ".dylib";
  218. else return "lib" ~ settings.targetName ~ ".so";
  219. case TargetType.object:
  220. if (p.canFind("windows"))
  221. return settings.targetName ~ ".obj";
  222. else return settings.targetName ~ ".o";
  223. }
  224. }
  225.  
  226. void setTarget(ref BuildSettings settings, in BuildPlatform platform, string tpath = null) const
  227. {
  228. const targetFileName = getTargetFileName(settings, platform);
  229.  
  230. final switch (settings.targetType) {
  231. case TargetType.autodetect: assert(false, "Invalid target type: autodetect");
  232. case TargetType.none: assert(false, "Invalid target type: none");
  233. case TargetType.sourceLibrary: assert(false, "Invalid target type: sourceLibrary");
  234. case TargetType.executable: break;
  235. case TargetType.library:
  236. case TargetType.staticLibrary:
  237. settings.addDFlags("-lib");
  238. break;
  239. case TargetType.dynamicLibrary:
  240. settings.addDFlags("-shared");
  241. addDynamicLibName(settings, platform, targetFileName);
  242. break;
  243. case TargetType.object:
  244. settings.addDFlags("-c");
  245. break;
  246. }
  247.  
  248. if (tpath is null)
  249. tpath = (NativePath(settings.targetPath) ~ targetFileName).toNativeString();
  250. settings.addDFlags("-of"~tpath);
  251. }
  252.  
  253. void invoke(in BuildSettings settings, in BuildPlatform platform, void delegate(int, string) output_callback, NativePath cwd)
  254. {
  255. auto res_file = getTempFile("dub-build", ".rsp");
  256. const(string)[] args = settings.dflags;
  257. if (platform.frontendVersion >= 2066) args ~= "-vcolumns";
  258. writeFile(res_file, escapeArgs(args).join("\n"));
  259.  
  260. logDiagnostic("%s %s", platform.compilerBinary, escapeArgs(args).join(" "));
  261. string[string] env;
  262. foreach (aa; [settings.environments, settings.buildEnvironments])
  263. foreach (k, v; aa)
  264. env[k] = v;
  265. invokeTool([platform.compilerBinary, "@"~res_file.toNativeString()], output_callback, cwd, env);
  266. }
  267.  
  268. void invokeLinker(in BuildSettings settings, in BuildPlatform platform, string[] objects, void delegate(int, string) output_callback, NativePath cwd)
  269. {
  270. import std.string;
  271. auto tpath = NativePath(settings.targetPath) ~ getTargetFileName(settings, platform);
  272. auto args = ["-of"~tpath.toNativeString()];
  273. args ~= objects;
  274. args ~= settings.sourceFiles;
  275. if (platform.platform.canFind("linux"))
  276. args ~= "-L--no-as-needed"; // avoids linker errors due to libraries being specified in the wrong order
  277. args ~= lflagsToDFlags(settings.lflags);
  278. args ~= settings.dflags.filter!(f => isLinkerDFlag(f)).array;
  279.  
  280. auto res_file = getTempFile("dub-build", ".lnk");
  281. writeFile(res_file, escapeArgs(args).join("\n"));
  282.  
  283. logDiagnostic("%s %s", platform.compilerBinary, escapeArgs(args).join(" "));
  284. string[string] env;
  285. foreach (aa; [settings.environments, settings.buildEnvironments])
  286. foreach (k, v; aa)
  287. env[k] = v;
  288. invokeTool([platform.compilerBinary, "@"~res_file.toNativeString()], output_callback, cwd, env);
  289. }
  290.  
  291. string[] lflagsToDFlags(const string[] lflags) const
  292. {
  293. return map!(f => "-L"~f)(lflags.filter!(f => f != "")()).array();
  294. }
  295.  
  296. private auto escapeArgs(in string[] args)
  297. {
  298. return args.map!(s => s.canFind(' ') ? "\""~s~"\"" : s);
  299. }
  300.  
  301. static bool isLinkerDFlag(string arg)
  302. {
  303. if (arg.length > 2 && arg.startsWith("--"))
  304. arg = arg[1 .. $]; // normalize to 1 leading hyphen
  305.  
  306. switch (arg) {
  307. case "-g", "-gc", "-m32", "-m64", "-shared", "-lib",
  308. "-betterC", "-disable-linker-strip-dead", "-static":
  309. return true;
  310. default:
  311. return arg.startsWith("-L")
  312. || arg.startsWith("-Xcc=")
  313. || arg.startsWith("-defaultlib=")
  314. || arg.startsWith("-platformlib=")
  315. || arg.startsWith("-flto")
  316. || arg.startsWith("-fsanitize=")
  317. || arg.startsWith("-gcc=")
  318. || arg.startsWith("-link-")
  319. || arg.startsWith("-linker=")
  320. || arg.startsWith("-march=")
  321. || arg.startsWith("-mscrtlib=")
  322. || arg.startsWith("-mtriple=");
  323. }
  324. }
  325. }