xref: /llvm-project-15.0.7/lld/Common/Args.cpp (revision 2fa83cb7)
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 int64_t lld::args::getInteger(opt::InputArgList &Args, unsigned Key,
30                               int64_t Default) {
31   auto *A = Args.getLastArg(Key);
32   if (!A)
33     return Default;
34 
35   int64_t V;
36   if (to_integer(A->getValue(), V, 10))
37     return V;
38 
39   StringRef Spelling = Args.getArgString(A->getIndex());
40   error(Spelling + ": number expected, but got '" + A->getValue() + "'");
41   return 0;
42 }
43 
44 std::vector<StringRef> lld::args::getStrings(opt::InputArgList &Args, int Id) {
45   std::vector<StringRef> V;
46   for (auto *Arg : Args.filtered(Id))
47     V.push_back(Arg->getValue());
48   return V;
49 }
50 
51 uint64_t lld::args::getZOptionValue(opt::InputArgList &Args, int Id,
52                                     StringRef Key, uint64_t Default) {
53   for (auto *Arg : Args.filtered_reverse(Id)) {
54     std::pair<StringRef, StringRef> KV = StringRef(Arg->getValue()).split('=');
55     if (KV.first == Key) {
56       uint64_t Result = Default;
57       if (!to_integer(KV.second, Result))
58         error("invalid " + Key + ": " + KV.second);
59       return Result;
60     }
61   }
62   return Default;
63 }
64 
65 std::vector<StringRef> lld::args::getLines(MemoryBufferRef MB) {
66   SmallVector<StringRef, 0> Arr;
67   MB.getBuffer().split(Arr, '\n');
68 
69   std::vector<StringRef> Ret;
70   for (StringRef S : Arr) {
71     S = S.trim();
72     if (!S.empty() && S[0] != '#')
73       Ret.push_back(S);
74   }
75   return Ret;
76 }
77 
78 StringRef lld::args::getFilenameWithoutExe(StringRef Path) {
79   if (Path.endswith_lower(".exe"))
80     return sys::path::stem(Path);
81   return sys::path::filename(Path);
82 }
83