clang 17.0.0git
Flang.cpp
Go to the documentation of this file.
1//===-- Flang.cpp - Flang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9
10#include "Flang.h"
11#include "CommonArgs.h"
12
14
15#include <cassert>
16
17using namespace clang::driver;
18using namespace clang::driver::tools;
19using namespace clang;
20using namespace llvm::opt;
21
22/// Add -x lang to \p CmdArgs for \p Input.
23static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
24 ArgStringList &CmdArgs) {
25 CmdArgs.push_back("-x");
26 // Map the driver type to the frontend type.
27 CmdArgs.push_back(types::getTypeName(Input.getType()));
28}
29
30void Flang::addFortranDialectOptions(const ArgList &Args,
31 ArgStringList &CmdArgs) const {
32 Args.AddAllArgs(
33 CmdArgs, {options::OPT_ffixed_form, options::OPT_ffree_form,
34 options::OPT_ffixed_line_length_EQ, options::OPT_fopenmp,
35 options::OPT_fopenacc, options::OPT_finput_charset_EQ,
36 options::OPT_fimplicit_none, options::OPT_fno_implicit_none,
37 options::OPT_fbackslash, options::OPT_fno_backslash,
38 options::OPT_flogical_abbreviations,
39 options::OPT_fno_logical_abbreviations,
40 options::OPT_fxor_operator, options::OPT_fno_xor_operator,
41 options::OPT_falternative_parameter_statement,
42 options::OPT_fdefault_real_8, options::OPT_fdefault_integer_8,
43 options::OPT_fdefault_double_8, options::OPT_flarge_sizes,
44 options::OPT_fno_automatic});
45}
46
47void Flang::addPreprocessingOptions(const ArgList &Args,
48 ArgStringList &CmdArgs) const {
49 Args.AddAllArgs(CmdArgs,
50 {options::OPT_P, options::OPT_D, options::OPT_U,
51 options::OPT_I, options::OPT_cpp, options::OPT_nocpp});
52}
53
54void Flang::addOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
55 Args.AddAllArgs(CmdArgs,
56 {options::OPT_module_dir, options::OPT_fdebug_module_writer,
57 options::OPT_fintrinsic_modules_path, options::OPT_pedantic,
58 options::OPT_std_EQ, options::OPT_W_Joined,
59 options::OPT_fconvert_EQ, options::OPT_fpass_plugin_EQ,
60 options::OPT_funderscoring, options::OPT_fno_underscoring});
61
62 Arg *stackArrays =
63 Args.getLastArg(options::OPT_Ofast, options::OPT_fstack_arrays,
64 options::OPT_fno_stack_arrays);
65 if (stackArrays &&
66 !stackArrays->getOption().matches(options::OPT_fno_stack_arrays))
67 CmdArgs.push_back("-fstack-arrays");
68}
69
70void Flang::addPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
71 // ParsePICArgs parses -fPIC/-fPIE and their variants and returns a tuple of
72 // (RelocationModel, PICLevel, IsPIE).
73 llvm::Reloc::Model RelocationModel;
74 unsigned PICLevel;
75 bool IsPIE;
76 std::tie(RelocationModel, PICLevel, IsPIE) =
78
79 if (auto *RMName = RelocationModelName(RelocationModel)) {
80 CmdArgs.push_back("-mrelocation-model");
81 CmdArgs.push_back(RMName);
82 }
83 if (PICLevel > 0) {
84 CmdArgs.push_back("-pic-level");
85 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
86 if (IsPIE)
87 CmdArgs.push_back("-pic-is-pie");
88 }
89}
90
91void Flang::addTargetOptions(const ArgList &Args,
92 ArgStringList &CmdArgs) const {
93 const ToolChain &TC = getToolChain();
94 const llvm::Triple &Triple = TC.getEffectiveTriple();
95 const Driver &D = TC.getDriver();
96
97 std::string CPU = getCPUName(D, Args, Triple);
98 if (!CPU.empty()) {
99 CmdArgs.push_back("-target-cpu");
100 CmdArgs.push_back(Args.MakeArgString(CPU));
101 }
102
103 // Add the target features.
104 switch (TC.getArch()) {
105 default:
106 break;
107 case llvm::Triple::aarch64:
108 case llvm::Triple::riscv64:
109 case llvm::Triple::x86_64:
110 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
111 break;
112 }
113
114 // TODO: Add target specific flags, ABI, mtune option etc.
115}
116
117void Flang::addOffloadOptions(Compilation &C, const InputInfoList &Inputs,
118 const JobAction &JA, const ArgList &Args,
119 ArgStringList &CmdArgs) const {
120 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
121 bool IsHostOffloadingAction = JA.isHostOffloading(Action::OFK_OpenMP) ||
122 JA.isHostOffloading(C.getActiveOffloadKinds());
123
124 // Skips the primary input file, which is the input file that the compilation
125 // proccess will be executed upon (e.g. the host bitcode file) and
126 // adds the other secondary input (e.g. device bitcode files for embedding)
127 // to the embed offload object. This is condensed logic from the Clang driver
128 // for embedding offload objects during HostOffloading.
129 if (IsHostOffloadingAction) {
130 for (size_t i = 1; i < Inputs.size(); ++i) {
131 if (Inputs[i].getType() != types::TY_Nothing)
132 CmdArgs.push_back(
133 Args.MakeArgString("-fembed-offload-object=" +
134 getToolChain().getInputFilename(Inputs[i])));
135 }
136 }
137
138 if (IsOpenMPDevice) {
139 // -fopenmp-is-device is passed along to tell the frontend that it is
140 // generating code for a device, so that only the relevant code is
141 // emitted.
142 CmdArgs.push_back("-fopenmp-is-device");
143 }
144}
145
146static void addFloatingPointOptions(const Driver &D, const ArgList &Args,
147 ArgStringList &CmdArgs) {
148 StringRef FPContract;
149 bool HonorINFs = true;
150 bool HonorNaNs = true;
151 bool ApproxFunc = false;
152 bool SignedZeros = true;
153 bool AssociativeMath = false;
154 bool ReciprocalMath = false;
155
156 if (const Arg *A = Args.getLastArg(options::OPT_ffp_contract)) {
157 const StringRef Val = A->getValue();
158 if (Val == "fast" || Val == "off") {
159 FPContract = Val;
160 } else if (Val == "on") {
161 // Warn instead of error because users might have makefiles written for
162 // gfortran (which accepts -ffp-contract=on)
163 D.Diag(diag::warn_drv_unsupported_option_for_flang)
164 << Val << A->getOption().getName() << "off";
165 FPContract = "off";
166 } else
167 // Clang's "fast-honor-pragmas" option is not supported because it is
168 // non-standard
169 D.Diag(diag::err_drv_unsupported_option_argument)
170 << A->getSpelling() << Val;
171 }
172
173 for (const Arg *A : Args) {
174 auto optId = A->getOption().getID();
175 switch (optId) {
176 // if this isn't an FP option, skip the claim below
177 default:
178 continue;
179
180 case options::OPT_fhonor_infinities:
181 HonorINFs = true;
182 break;
183 case options::OPT_fno_honor_infinities:
184 HonorINFs = false;
185 break;
186 case options::OPT_fhonor_nans:
187 HonorNaNs = true;
188 break;
189 case options::OPT_fno_honor_nans:
190 HonorNaNs = false;
191 break;
192 case options::OPT_fapprox_func:
193 ApproxFunc = true;
194 break;
195 case options::OPT_fno_approx_func:
196 ApproxFunc = false;
197 break;
198 case options::OPT_fsigned_zeros:
199 SignedZeros = true;
200 break;
201 case options::OPT_fno_signed_zeros:
202 SignedZeros = false;
203 break;
204 case options::OPT_fassociative_math:
205 AssociativeMath = true;
206 break;
207 case options::OPT_fno_associative_math:
208 AssociativeMath = false;
209 break;
210 case options::OPT_freciprocal_math:
211 ReciprocalMath = true;
212 break;
213 case options::OPT_fno_reciprocal_math:
214 ReciprocalMath = false;
215 break;
216 case options::OPT_Ofast:
217 [[fallthrough]];
218 case options::OPT_ffast_math:
219 HonorINFs = false;
220 HonorNaNs = false;
221 AssociativeMath = true;
222 ReciprocalMath = true;
223 ApproxFunc = true;
224 SignedZeros = false;
225 FPContract = "fast";
226 break;
227 case options::OPT_fno_fast_math:
228 HonorINFs = true;
229 HonorNaNs = true;
230 AssociativeMath = false;
231 ReciprocalMath = false;
232 ApproxFunc = false;
233 SignedZeros = true;
234 // -fno-fast-math should undo -ffast-math so I return FPContract to the
235 // default. It is important to check it is "fast" (the default) so that
236 // --ffp-contract=off -fno-fast-math --> -ffp-contract=off
237 if (FPContract == "fast")
238 FPContract = "";
239 break;
240 }
241
242 // If we handled this option claim it
243 A->claim();
244 }
245
246 if (!HonorINFs && !HonorNaNs && AssociativeMath && ReciprocalMath &&
247 ApproxFunc && !SignedZeros &&
248 (FPContract == "fast" || FPContract == "")) {
249 CmdArgs.push_back("-ffast-math");
250 return;
251 }
252
253 if (!FPContract.empty())
254 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
255
256 if (!HonorINFs)
257 CmdArgs.push_back("-menable-no-infs");
258
259 if (!HonorNaNs)
260 CmdArgs.push_back("-menable-no-nans");
261
262 if (ApproxFunc)
263 CmdArgs.push_back("-fapprox-func");
264
265 if (!SignedZeros)
266 CmdArgs.push_back("-fno-signed-zeros");
267
268 if (AssociativeMath && !SignedZeros)
269 CmdArgs.push_back("-mreassociate");
270
271 if (ReciprocalMath)
272 CmdArgs.push_back("-freciprocal-math");
273}
274
276 const InputInfo &Output, const InputInfoList &Inputs,
277 const ArgList &Args, const char *LinkingOutput) const {
278 const auto &TC = getToolChain();
279 const llvm::Triple &Triple = TC.getEffectiveTriple();
280 const std::string &TripleStr = Triple.getTriple();
281
282 const Driver &D = TC.getDriver();
283 ArgStringList CmdArgs;
284 DiagnosticsEngine &Diags = D.getDiags();
285
286 // Invoke ourselves in -fc1 mode.
287 CmdArgs.push_back("-fc1");
288
289 // Add the "effective" target triple.
290 CmdArgs.push_back("-triple");
291 CmdArgs.push_back(Args.MakeArgString(TripleStr));
292
293 if (isa<PreprocessJobAction>(JA)) {
294 CmdArgs.push_back("-E");
295 } else if (isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) {
296 if (JA.getType() == types::TY_Nothing) {
297 CmdArgs.push_back("-fsyntax-only");
298 } else if (JA.getType() == types::TY_AST) {
299 CmdArgs.push_back("-emit-ast");
300 } else if (JA.getType() == types::TY_LLVM_IR ||
301 JA.getType() == types::TY_LTO_IR) {
302 CmdArgs.push_back("-emit-llvm");
303 } else if (JA.getType() == types::TY_LLVM_BC ||
304 JA.getType() == types::TY_LTO_BC) {
305 CmdArgs.push_back("-emit-llvm-bc");
306 } else if (JA.getType() == types::TY_PP_Asm) {
307 CmdArgs.push_back("-S");
308 } else {
309 assert(false && "Unexpected output type!");
310 }
311 } else if (isa<AssembleJobAction>(JA)) {
312 CmdArgs.push_back("-emit-obj");
313 } else {
314 assert(false && "Unexpected action class for Flang tool.");
315 }
316
317 const InputInfo &Input = Inputs[0];
318 types::ID InputType = Input.getType();
319
320 // Add preprocessing options like -I, -D, etc. if we are using the
321 // preprocessor (i.e. skip when dealing with e.g. binary files).
323 addPreprocessingOptions(Args, CmdArgs);
324
325 addFortranDialectOptions(Args, CmdArgs);
326
327 // Color diagnostics are parsed by the driver directly from argv and later
328 // re-parsed to construct this job; claim any possible color diagnostic here
329 // to avoid warn_drv_unused_argument.
330 Args.getLastArg(options::OPT_fcolor_diagnostics,
331 options::OPT_fno_color_diagnostics);
332 if (Diags.getDiagnosticOptions().ShowColors)
333 CmdArgs.push_back("-fcolor-diagnostics");
334
335 // LTO mode is parsed by the Clang driver library.
336 LTOKind LTOMode = D.getLTOMode(/* IsOffload */ false);
337 assert(LTOMode != LTOK_Unknown && "Unknown LTO mode.");
338 if (LTOMode == LTOK_Full)
339 CmdArgs.push_back("-flto=full");
340 else if (LTOMode == LTOK_Thin) {
341 Diags.Report(
343 "the option '-flto=thin' is a work in progress"));
344 CmdArgs.push_back("-flto=thin");
345 }
346
347 // -fPIC and related options.
348 addPicOptions(Args, CmdArgs);
349
350 // Floating point related options
351 addFloatingPointOptions(D, Args, CmdArgs);
352
353 // Add target args, features, etc.
354 addTargetOptions(Args, CmdArgs);
355
356 // Add other compile options
357 addOtherOptions(Args, CmdArgs);
358
359 // Offloading related options
360 addOffloadOptions(C, Inputs, JA, Args, CmdArgs);
361
362 // Forward -Xflang arguments to -fc1
363 Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);
364
365 // Forward -mllvm options to the LLVM option parser. In practice, this means
366 // forwarding to `-fc1` as that's where the LLVM parser is run.
367 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
368 A->claim();
369 A->render(Args, CmdArgs);
370 }
371
372 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
373 A->claim();
374 A->render(Args, CmdArgs);
375 }
376
377 // Remove any unsupported gfortran diagnostic options
378 for (const Arg *A : Args.filtered(options::OPT_flang_ignored_w_Group)) {
379 A->claim();
380 D.Diag(diag::warn_drv_unsupported_diag_option_for_flang)
381 << A->getOption().getName();
382 }
383
384 // Optimization level for CodeGen.
385 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
386 if (A->getOption().matches(options::OPT_O4)) {
387 CmdArgs.push_back("-O3");
388 D.Diag(diag::warn_O4_is_O3);
389 } else if (A->getOption().matches(options::OPT_Ofast)) {
390 CmdArgs.push_back("-O3");
391 } else {
392 A->render(Args, CmdArgs);
393 }
394 }
395
396 if (Output.isFilename()) {
397 CmdArgs.push_back("-o");
398 CmdArgs.push_back(Output.getFilename());
399 } else {
400 assert(Output.isNothing() && "Invalid output.");
401 }
402
403 assert(Input.isFilename() && "Invalid input.");
404
405 addDashXForInput(Args, Input, CmdArgs);
406
407 CmdArgs.push_back(Input.getFilename());
408
409 // TODO: Replace flang-new with flang once the new driver replaces the
410 // throwaway driver
411 const char *Exec = Args.MakeArgString(D.GetProgramPath("flang-new", TC));
412 C.addCommand(std::make_unique<Command>(JA, *this,
414 Exec, CmdArgs, Inputs, Output));
415}
416
417Flang::Flang(const ToolChain &TC) : Tool("flang-new", "flang frontend", TC) {}
418
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition: Clang.cpp:671
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition: Flang.cpp:23
static void addFloatingPointOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Flang.cpp:146
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1542
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:868
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:557
types::ID getType() const
Definition: Action.h:148
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition: Action.h:218
bool isDeviceOffloading(OffloadKind OKind) const
Definition: Action.h:221
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:77
DiagnosticsEngine & getDiags() const
Definition: Driver.h:390
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:144
LTOKind getLTOMode(bool IsOffload=false) const
Get the specific kind of LTO being performed.
Definition: Driver.h:704
std::string GetProgramPath(StringRef Name, const ToolChain &TC) const
GetProgramPath - Lookup Name in the list of program search paths.
Definition: Driver.cpp:5933
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getFilename() const
Definition: InputInfo.h:83
bool isNothing() const
Definition: InputInfo.h:74
bool isFilename() const
Definition: InputInfo.h:75
types::ID getType() const
Definition: InputInfo.h:77
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:91
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:252
const Driver & getDriver() const
Definition: ToolChain.h:236
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:266
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
const ToolChain & getToolChain() const
Definition: Tool.h:52
Flang(const ToolChain &TC)
Definition: Flang.cpp:417
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Flang.cpp:275
void getTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForAS, bool IsAux=false)
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
const char * RelocationModelName(llvm::Reloc::Model Model)
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition: Types.cpp:56
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:52
LTOKind
Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
Definition: Driver.h:58
@ LTOK_Unknown
Definition: Driver.h:62
@ C
Languages that the frontend can parse and compile.
static constexpr ResponseFileSupport AtFileUTF8()
Definition: Job.h:85