1 //===--- XRayArgs.cpp - Arguments for XRay --------------------------------===//
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 #include "clang/Driver/XRayArgs.h"
9 #include "ToolChains/CommonArgs.h"
10 #include "clang/Driver/Driver.h"
11 #include "clang/Driver/DriverDiagnostic.h"
12 #include "clang/Driver/Options.h"
13 #include "clang/Driver/ToolChain.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/Path.h"
18 #include "llvm/Support/ScopedPrinter.h"
19 #include "llvm/Support/SpecialCaseList.h"
20 
21 using namespace clang;
22 using namespace clang::driver;
23 using namespace llvm::opt;
24 
25 namespace {
26 constexpr char XRayInstrumentOption[] = "-fxray-instrument";
27 constexpr char XRayInstructionThresholdOption[] =
28     "-fxray-instruction-threshold=";
29 constexpr const char *const XRaySupportedModes[] = {"xray-fdr", "xray-basic"};
30 } // namespace
31 
32 XRayArgs::XRayArgs(const ToolChain &TC, const ArgList &Args) {
33   const Driver &D = TC.getDriver();
34   const llvm::Triple &Triple = TC.getTriple();
35   if (!Args.hasFlag(options::OPT_fxray_instrument,
36                     options::OPT_fno_xray_instrument, false))
37     return;
38   if (Triple.getOS() == llvm::Triple::Linux) {
39     switch (Triple.getArch()) {
40     case llvm::Triple::x86_64:
41     case llvm::Triple::arm:
42     case llvm::Triple::aarch64:
43     case llvm::Triple::ppc64le:
44     case llvm::Triple::mips:
45     case llvm::Triple::mipsel:
46     case llvm::Triple::mips64:
47     case llvm::Triple::mips64el:
48       break;
49     default:
50       D.Diag(diag::err_drv_clang_unsupported)
51           << (std::string(XRayInstrumentOption) + " on " + Triple.str());
52     }
53   } else if (Triple.isOSFreeBSD() || Triple.isOSOpenBSD() ||
54              Triple.isOSNetBSD() || Triple.isMacOSX()) {
55     if (Triple.getArch() != llvm::Triple::x86_64) {
56       D.Diag(diag::err_drv_clang_unsupported)
57           << (std::string(XRayInstrumentOption) + " on " + Triple.str());
58     }
59   } else if (Triple.getOS() == llvm::Triple::Fuchsia) {
60     switch (Triple.getArch()) {
61     case llvm::Triple::x86_64:
62     case llvm::Triple::aarch64:
63       break;
64     default:
65       D.Diag(diag::err_drv_clang_unsupported)
66           << (std::string(XRayInstrumentOption) + " on " + Triple.str());
67     }
68   } else {
69     D.Diag(diag::err_drv_clang_unsupported)
70         << (std::string(XRayInstrumentOption) + " on " + Triple.str());
71   }
72 
73   // Both XRay and -fpatchable-function-entry use
74   // TargetOpcode::PATCHABLE_FUNCTION_ENTER.
75   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ))
76     D.Diag(diag::err_drv_argument_not_allowed_with)
77         << "-fxray-instrument" << A->getSpelling();
78 
79   XRayInstrument = true;
80   if (const Arg *A =
81           Args.getLastArg(options::OPT_fxray_instruction_threshold_,
82                           options::OPT_fxray_instruction_threshold_EQ)) {
83     StringRef S = A->getValue();
84     if (S.getAsInteger(0, InstructionThreshold) || InstructionThreshold < 0)
85       D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
86   }
87 
88   // By default, the back-end will not emit the lowering for XRay customevent
89   // calls if the function is not instrumented. In the future we will change
90   // this default to be the reverse, but in the meantime we're going to
91   // introduce the new functionality behind a flag.
92   if (Args.hasFlag(options::OPT_fxray_always_emit_customevents,
93                    options::OPT_fno_xray_always_emit_customevents, false))
94     XRayAlwaysEmitCustomEvents = true;
95 
96   if (Args.hasFlag(options::OPT_fxray_always_emit_typedevents,
97                    options::OPT_fno_xray_always_emit_typedevents, false))
98     XRayAlwaysEmitTypedEvents = true;
99 
100   if (!Args.hasFlag(options::OPT_fxray_link_deps,
101                     options::OPT_fnoxray_link_deps, true))
102     XRayRT = false;
103 
104   if (Args.hasFlag(options::OPT_fxray_ignore_loops,
105                    options::OPT_fno_xray_ignore_loops, false))
106     XRayIgnoreLoops = true;
107 
108   auto Bundles =
109       Args.getAllArgValues(options::OPT_fxray_instrumentation_bundle);
110   if (Bundles.empty())
111     InstrumentationBundle.Mask = XRayInstrKind::All;
112   else
113     for (const auto &B : Bundles) {
114       llvm::SmallVector<StringRef, 2> BundleParts;
115       llvm::SplitString(B, BundleParts, ",");
116       for (const auto &P : BundleParts) {
117         // TODO: Automate the generation of the string case table.
118         auto Valid = llvm::StringSwitch<bool>(P)
119                          .Cases("none", "all", "function", "function-entry",
120                                 "function-exit", "custom", true)
121                          .Default(false);
122 
123         if (!Valid) {
124           D.Diag(clang::diag::err_drv_invalid_value)
125               << "-fxray-instrumentation-bundle=" << P;
126           continue;
127         }
128 
129         auto Mask = parseXRayInstrValue(P);
130         if (Mask == XRayInstrKind::None) {
131           InstrumentationBundle.clear();
132           break;
133         }
134 
135         InstrumentationBundle.Mask |= Mask;
136       }
137     }
138 
139   // Validate the always/never attribute files. We also make sure that they
140   // are treated as actual dependencies.
141   for (const auto &Filename :
142        Args.getAllArgValues(options::OPT_fxray_always_instrument)) {
143     if (D.getVFS().exists(Filename)) {
144       AlwaysInstrumentFiles.push_back(Filename);
145       ExtraDeps.push_back(Filename);
146     } else
147       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
148   }
149 
150   for (const auto &Filename :
151        Args.getAllArgValues(options::OPT_fxray_never_instrument)) {
152     if (D.getVFS().exists(Filename)) {
153       NeverInstrumentFiles.push_back(Filename);
154       ExtraDeps.push_back(Filename);
155     } else
156       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
157   }
158 
159   for (const auto &Filename :
160        Args.getAllArgValues(options::OPT_fxray_attr_list)) {
161     if (D.getVFS().exists(Filename)) {
162       AttrListFiles.push_back(Filename);
163       ExtraDeps.push_back(Filename);
164     } else
165       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
166   }
167 
168   // Get the list of modes we want to support.
169   auto SpecifiedModes = Args.getAllArgValues(options::OPT_fxray_modes);
170   if (SpecifiedModes.empty())
171     llvm::copy(XRaySupportedModes, std::back_inserter(Modes));
172   else
173     for (const auto &Arg : SpecifiedModes) {
174       // Parse CSV values for -fxray-modes=...
175       llvm::SmallVector<StringRef, 2> ModeParts;
176       llvm::SplitString(Arg, ModeParts, ",");
177       for (const auto &M : ModeParts)
178         if (M == "none")
179           Modes.clear();
180         else if (M == "all")
181           llvm::copy(XRaySupportedModes, std::back_inserter(Modes));
182         else
183           Modes.push_back(std::string(M));
184     }
185 
186   // Then we want to sort and unique the modes we've collected.
187   llvm::sort(Modes);
188   Modes.erase(std::unique(Modes.begin(), Modes.end()), Modes.end());
189 }
190 
191 void XRayArgs::addArgs(const ToolChain &TC, const ArgList &Args,
192                        ArgStringList &CmdArgs, types::ID InputType) const {
193   if (!XRayInstrument)
194     return;
195 
196   CmdArgs.push_back(XRayInstrumentOption);
197 
198   if (XRayAlwaysEmitCustomEvents)
199     CmdArgs.push_back("-fxray-always-emit-customevents");
200 
201   if (XRayAlwaysEmitTypedEvents)
202     CmdArgs.push_back("-fxray-always-emit-typedevents");
203 
204   if (XRayIgnoreLoops)
205     CmdArgs.push_back("-fxray-ignore-loops");
206 
207   CmdArgs.push_back(Args.MakeArgString(Twine(XRayInstructionThresholdOption) +
208                                        Twine(InstructionThreshold)));
209 
210   for (const auto &Always : AlwaysInstrumentFiles) {
211     SmallString<64> AlwaysInstrumentOpt("-fxray-always-instrument=");
212     AlwaysInstrumentOpt += Always;
213     CmdArgs.push_back(Args.MakeArgString(AlwaysInstrumentOpt));
214   }
215 
216   for (const auto &Never : NeverInstrumentFiles) {
217     SmallString<64> NeverInstrumentOpt("-fxray-never-instrument=");
218     NeverInstrumentOpt += Never;
219     CmdArgs.push_back(Args.MakeArgString(NeverInstrumentOpt));
220   }
221 
222   for (const auto &AttrFile : AttrListFiles) {
223     SmallString<64> AttrListFileOpt("-fxray-attr-list=");
224     AttrListFileOpt += AttrFile;
225     CmdArgs.push_back(Args.MakeArgString(AttrListFileOpt));
226   }
227 
228   for (const auto &Dep : ExtraDeps) {
229     SmallString<64> ExtraDepOpt("-fdepfile-entry=");
230     ExtraDepOpt += Dep;
231     CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
232   }
233 
234   for (const auto &Mode : Modes) {
235     SmallString<64> ModeOpt("-fxray-modes=");
236     ModeOpt += Mode;
237     CmdArgs.push_back(Args.MakeArgString(ModeOpt));
238   }
239 
240   SmallString<64> Bundle("-fxray-instrumentation-bundle=");
241   if (InstrumentationBundle.full()) {
242     Bundle += "all";
243   } else if (InstrumentationBundle.empty()) {
244     Bundle += "none";
245   } else {
246     if (InstrumentationBundle.has(XRayInstrKind::FunctionEntry) &&
247         InstrumentationBundle.has(XRayInstrKind::FunctionExit))
248       Bundle += "function";
249     else if (InstrumentationBundle.has(XRayInstrKind::FunctionEntry))
250       Bundle += "function-entry";
251     else if (InstrumentationBundle.has(XRayInstrKind::FunctionExit))
252       Bundle += "function-exit";
253 
254     if (InstrumentationBundle.has(XRayInstrKind::Custom))
255       Bundle += "custom";
256     if (InstrumentationBundle.has(XRayInstrKind::Typed))
257       Bundle += "typed";
258   }
259   CmdArgs.push_back(Args.MakeArgString(Bundle));
260 }
261