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
17using namespace llvm;
18using namespace lld;
19
20// TODO(sbc): Remove this once CGOptLevel can be set completely based on bitcode
21// function metadata.
22int lld::args::getCGOptLevel(int optLevelLTO) {
23 return std::clamp(val: optLevelLTO, lo: 2, hi: 3);
24}
25
26static int64_t getInteger(opt::InputArgList &args, unsigned key,
27 int64_t Default, unsigned base) {
28 auto *a = args.getLastArg(Ids: key);
29 if (!a)
30 return Default;
31
32 int64_t v;
33 StringRef s = a->getValue();
34 if (base == 16)
35 s.consume_front_insensitive(Prefix: "0x");
36 if (to_integer(S: s, Num&: v, Base: base))
37 return v;
38
39 StringRef spelling = args.getArgString(Index: a->getIndex());
40 error(msg: spelling + ": number expected, but got '" + a->getValue() + "'");
41 return 0;
42}
43
44int64_t lld::args::getInteger(opt::InputArgList &args, unsigned key,
45 int64_t Default) {
46 return ::getInteger(args, key, Default, base: 10);
47}
48
49int64_t lld::args::getHex(opt::InputArgList &args, unsigned key,
50 int64_t Default) {
51 return ::getInteger(args, key, Default, base: 16);
52}
53
54SmallVector<StringRef, 0> lld::args::getStrings(opt::InputArgList &args,
55 int id) {
56 SmallVector<StringRef, 0> v;
57 for (auto *arg : args.filtered(Ids: id))
58 v.push_back(Elt: arg->getValue());
59 return v;
60}
61
62uint64_t lld::args::getZOptionValue(opt::InputArgList &args, int id,
63 StringRef key, uint64_t defaultValue) {
64 for (auto *arg : args.filtered(Ids: id)) {
65 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split(Separator: '=');
66 if (kv.first == key) {
67 if (!to_integer(S: kv.second, Num&: defaultValue))
68 error(msg: "invalid " + key + ": " + kv.second);
69 arg->claim();
70 }
71 }
72 return defaultValue;
73}
74
75std::vector<StringRef> lld::args::getLines(MemoryBufferRef mb) {
76 SmallVector<StringRef, 0> arr;
77 mb.getBuffer().split(A&: arr, Separator: '\n');
78
79 std::vector<StringRef> ret;
80 for (StringRef s : arr) {
81 s = s.trim();
82 if (!s.empty() && s[0] != '#')
83 ret.push_back(x: s);
84 }
85 return ret;
86}
87
88StringRef lld::args::getFilenameWithoutExe(StringRef path) {
89 if (path.ends_with_insensitive(Suffix: ".exe"))
90 return sys::path::stem(path);
91 return sys::path::filename(path);
92}
93

source code of lld/Common/Args.cpp