xref: /llvm-project-15.0.7/lld/Common/Args.cpp (revision e3748b5a)
1 //===- Args.cpp -----------------------------------------------------------===//
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 #include "lld/Common/Args.h"
10 #include "lld/Common/ErrorHandler.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/Support/Path.h"
16 
17 using namespace llvm;
18 using namespace lld;
19 
20 // TODO(sbc): Remove this once CGOptLevel can be set completely based on bitcode
21 // function metadata.
22 CodeGenOpt::Level lld::args::getCGOptLevel(int OptLevelLTO) {
23   if (OptLevelLTO == 3)
24     return CodeGenOpt::Aggressive;
25   assert(OptLevelLTO < 3);
26   return CodeGenOpt::Default;
27 }
28 
29 int lld::args::getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
30   auto *A = Args.getLastArg(Key);
31   if (!A)
32     return Default;
33 
34   int V;
35   if (to_integer(A->getValue(), V, 10))
36     return V;
37 
38   StringRef Spelling = Args.getArgString(A->getIndex());
39   error(Spelling + ": number expected, but got '" + A->getValue() + "'");
40   return 0;
41 }
42 
43 std::vector<StringRef> lld::args::getStrings(opt::InputArgList &Args, int Id) {
44   std::vector<StringRef> V;
45   for (auto *Arg : Args.filtered(Id))
46     V.push_back(Arg->getValue());
47   return V;
48 }
49 
50 uint64_t lld::args::getZOptionValue(opt::InputArgList &Args, int Id,
51                                     StringRef Key, uint64_t Default) {
52   for (auto *Arg : Args.filtered_reverse(Id)) {
53     std::pair<StringRef, StringRef> KV = StringRef(Arg->getValue()).split('=');
54     if (KV.first == Key) {
55       uint64_t Result = Default;
56       if (!to_integer(KV.second, Result))
57         error("invalid " + Key + ": " + KV.second);
58       return Result;
59     }
60   }
61   return Default;
62 }
63 
64 std::vector<StringRef> lld::args::getLines(MemoryBufferRef MB) {
65   SmallVector<StringRef, 0> Arr;
66   MB.getBuffer().split(Arr, '\n');
67 
68   std::vector<StringRef> Ret;
69   for (StringRef S : Arr) {
70     S = S.trim();
71     if (!S.empty() && S[0] != '#')
72       Ret.push_back(S);
73   }
74   return Ret;
75 }
76 
77 StringRef lld::args::getFilenameWithoutExe(StringRef Path) {
78   if (Path.endswith_lower(".exe"))
79     return sys::path::stem(Path);
80   return sys::path::filename(Path);
81 }
82