Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Support/CommandLine.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- CommandLine.cpp - Command line parser implementation --------------===//
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
// This class implements a command line argument processor that is useful when
10
// creating a tool.  It provides a simple, minimalistic interface that is easily
11
// extensible and supports nonlocal (library) command line options.
12
//
13
// Note that rather than trying to figure out what this code does, you could try
14
// reading the library documentation located in docs/CommandLine.html
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "llvm/Support/CommandLine.h"
19
#include "llvm-c/Support.h"
20
#include "llvm/ADT/ArrayRef.h"
21
#include "llvm/ADT/Optional.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/SmallPtrSet.h"
24
#include "llvm/ADT/SmallString.h"
25
#include "llvm/ADT/StringExtras.h"
26
#include "llvm/ADT/StringMap.h"
27
#include "llvm/ADT/Triple.h"
28
#include "llvm/ADT/Twine.h"
29
#include "llvm/Config/config.h"
30
#include "llvm/Support/ConvertUTF.h"
31
#include "llvm/Support/Debug.h"
32
#include "llvm/Support/ErrorHandling.h"
33
#include "llvm/Support/FileSystem.h"
34
#include "llvm/Support/Host.h"
35
#include "llvm/Support/ManagedStatic.h"
36
#include "llvm/Support/MemoryBuffer.h"
37
#include "llvm/Support/Path.h"
38
#include "llvm/Support/Process.h"
39
#include "llvm/Support/StringSaver.h"
40
#include "llvm/Support/raw_ostream.h"
41
#include <cstdlib>
42
#include <map>
43
using namespace llvm;
44
using namespace cl;
45
46
#define DEBUG_TYPE "commandline"
47
48
//===----------------------------------------------------------------------===//
49
// Template instantiations and anchors.
50
//
51
namespace llvm {
52
namespace cl {
53
template class basic_parser<bool>;
54
template class basic_parser<boolOrDefault>;
55
template class basic_parser<int>;
56
template class basic_parser<unsigned>;
57
template class basic_parser<unsigned long>;
58
template class basic_parser<unsigned long long>;
59
template class basic_parser<double>;
60
template class basic_parser<float>;
61
template class basic_parser<std::string>;
62
template class basic_parser<char>;
63
64
template class opt<unsigned>;
65
template class opt<int>;
66
template class opt<std::string>;
67
template class opt<char>;
68
template class opt<bool>;
69
}
70
} // end namespace llvm::cl
71
72
// Pin the vtables to this file.
73
0
void GenericOptionValue::anchor() {}
74
0
void OptionValue<boolOrDefault>::anchor() {}
75
0
void OptionValue<std::string>::anchor() {}
76
0
void Option::anchor() {}
77
0
void basic_parser_impl::anchor() {}
78
0
void parser<bool>::anchor() {}
79
0
void parser<boolOrDefault>::anchor() {}
80
0
void parser<int>::anchor() {}
81
0
void parser<unsigned>::anchor() {}
82
0
void parser<unsigned long>::anchor() {}
83
0
void parser<unsigned long long>::anchor() {}
84
0
void parser<double>::anchor() {}
85
0
void parser<float>::anchor() {}
86
0
void parser<std::string>::anchor() {}
87
0
void parser<char>::anchor() {}
88
89
//===----------------------------------------------------------------------===//
90
91
static StringRef ArgPrefix = "  -";
92
static StringRef ArgPrefixLong = "  --";
93
static StringRef ArgHelpPrefix = " - ";
94
95
4.18k
static size_t argPlusPrefixesSize(StringRef ArgName) {
96
4.18k
  size_t Len = ArgName.size();
97
4.18k
  if (Len == 1)
98
279
    return Len + ArgPrefix.size() + ArgHelpPrefix.size();
99
3.90k
  return Len + ArgPrefixLong.size() + ArgHelpPrefix.size();
100
3.90k
}
101
102
5.15k
static StringRef argPrefix(StringRef ArgName) {
103
5.15k
  if (ArgName.size() == 1)
104
2.67k
    return ArgPrefix;
105
2.47k
  return ArgPrefixLong;
106
2.47k
}
107
108
// Option predicates...
109
6.12k
static inline bool isGrouping(const Option *O) {
110
6.12k
  return O->getMiscFlags() & cl::Grouping;
111
6.12k
}
112
5.89k
static inline bool isPrefixedOrGrouping(const Option *O) {
113
5.89k
  return isGrouping(O) || 
O->getFormattingFlag() == cl::Prefix2
||
114
5.89k
         
O->getFormattingFlag() == cl::AlwaysPrefix2
;
115
5.89k
}
116
117
118
namespace {
119
120
class PrintArg {
121
  StringRef ArgName;
122
public:
123
5.15k
  PrintArg(StringRef ArgName) : ArgName(ArgName) {}
124
  friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg&);
125
};
126
127
5.15k
raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
128
5.15k
  OS << argPrefix(Arg.ArgName) << Arg.ArgName;
129
5.15k
  return OS;
130
5.15k
}
131
132
class CommandLineParser {
133
public:
134
  // Globals for name and overview of program.  Program name is not a string to
135
  // avoid static ctor/dtor issues.
136
  std::string ProgramName;
137
  StringRef ProgramOverview;
138
139
  // This collects additional help to be printed.
140
  std::vector<StringRef> MoreHelp;
141
142
  // This collects Options added with the cl::DefaultOption flag. Since they can
143
  // be overridden, they are not added to the appropriate SubCommands until
144
  // ParseCommandLineOptions actually runs.
145
  SmallVector<Option*, 4> DefaultOptions;
146
147
  // This collects the different option categories that have been registered.
148
  SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
149
150
  // This collects the different subcommands that have been registered.
151
  SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
152
153
139k
  CommandLineParser() : ActiveSubCommand(nullptr) {
154
139k
    registerSubCommand(&*TopLevelSubCommand);
155
139k
    registerSubCommand(&*AllSubCommands);
156
139k
  }
157
158
  void ResetAllOptionOccurrences();
159
160
  bool ParseCommandLineOptions(int argc, const char *const *argv,
161
                               StringRef Overview, raw_ostream *Errs = nullptr,
162
                               bool LongOptionsUseDoubleDash = false);
163
164
90.5M
  void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
165
90.5M
    if (Opt.hasArgStr())
166
84.4M
      return;
167
6.11M
    if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
168
0
      errs() << ProgramName << ": CommandLine Error: Option '" << Name
169
0
             << "' registered more than once!\n";
170
0
      report_fatal_error("inconsistency in registered CommandLine options");
171
0
    }
172
6.11M
173
6.11M
    // If we're adding this to all sub-commands, add it to the ones that have
174
6.11M
    // already been registered.
175
6.11M
    if (SC == &*AllSubCommands) {
176
0
      for (const auto &Sub : RegisteredSubCommands) {
177
0
        if (SC == Sub)
178
0
          continue;
179
0
        addLiteralOption(Opt, Sub, Name);
180
0
      }
181
0
    }
182
6.11M
  }
183
184
90.5M
  void addLiteralOption(Option &Opt, StringRef Name) {
185
90.5M
    if (Opt.Subs.empty())
186
90.5M
      addLiteralOption(Opt, &*TopLevelSubCommand, Name);
187
7.04k
    else {
188
7.04k
      for (auto SC : Opt.Subs)
189
7.04k
        addLiteralOption(Opt, SC, Name);
190
7.04k
    }
191
90.5M
  }
192
193
149M
  void addOption(Option *O, SubCommand *SC) {
194
149M
    bool HadErrors = false;
195
149M
    if (O->hasArgStr()) {
196
148M
      // If it's a DefaultOption, check to make sure it isn't already there.
197
148M
      if (O->isDefaultOption() &&
198
148M
          
SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end()199k
)
199
16.2k
        return;
200
148M
201
148M
      // Add argument to the argument map!
202
148M
      if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
203
0
        errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
204
0
               << "' registered more than once!\n";
205
0
        HadErrors = true;
206
0
      }
207
148M
    }
208
149M
209
149M
    // Remember information about positional options.
210
149M
    
if (149M
O->getFormattingFlag() == cl::Positional149M
)
211
65.5k
      SC->PositionalOpts.push_back(O);
212
148M
    else if (O->getMiscFlags() & cl::Sink) // Remember sink options
213
0
      SC->SinkOpts.push_back(O);
214
148M
    else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
215
197
      if (SC->ConsumeAfterOpt) {
216
0
        O->error("Cannot specify more than one option with cl::ConsumeAfter!");
217
0
        HadErrors = true;
218
0
      }
219
197
      SC->ConsumeAfterOpt = O;
220
197
    }
221
149M
222
149M
    // Fail hard if there were errors. These are strictly unrecoverable and
223
149M
    // indicate serious issues such as conflicting option names or an
224
149M
    // incorrectly
225
149M
    // linked LLVM distribution.
226
149M
    if (HadErrors)
227
0
      report_fatal_error("inconsistency in registered CommandLine options");
228
149M
229
149M
    // If we're adding this to all sub-commands, add it to the ones that have
230
149M
    // already been registered.
231
149M
    if (SC == &*AllSubCommands) {
232
1.87M
      for (const auto &Sub : RegisteredSubCommands) {
233
1.87M
        if (SC == Sub)
234
932k
          continue;
235
947k
        addOption(O, Sub);
236
947k
      }
237
932k
    }
238
149M
  }
239
240
148M
  void addOption(Option *O, bool ProcessDefaultOption = false) {
241
148M
    if (!ProcessDefaultOption && 
O->isDefaultOption()148M
) {
242
139k
      DefaultOptions.push_back(O);
243
139k
      return;
244
139k
    }
245
148M
246
148M
    if (O->Subs.empty()) {
247
147M
      addOption(O, &*TopLevelSubCommand);
248
147M
    } else {
249
973k
      for (auto SC : O->Subs)
250
973k
        addOption(O, SC);
251
973k
    }
252
148M
  }
253
254
188
  void removeOption(Option *O, SubCommand *SC) {
255
188
    SmallVector<StringRef, 16> OptionNames;
256
188
    O->getExtraOptionNames(OptionNames);
257
188
    if (O->hasArgStr())
258
184
      OptionNames.push_back(O->ArgStr);
259
188
260
188
    SubCommand &Sub = *SC;
261
188
    auto End = Sub.OptionsMap.end();
262
188
    for (auto Name : OptionNames) {
263
184
      auto I = Sub.OptionsMap.find(Name);
264
184
      if (I != End && 
I->getValue() == O170
)
265
164
        Sub.OptionsMap.erase(I);
266
184
      }
267
188
268
188
    if (O->getFormattingFlag() == cl::Positional)
269
6
      for (auto Opt = Sub.PositionalOpts.begin();
270
7
           Opt != Sub.PositionalOpts.end(); 
++Opt1
) {
271
7
        if (*Opt == O) {
272
6
          Sub.PositionalOpts.erase(Opt);
273
6
          break;
274
6
        }
275
7
      }
276
182
    else if (O->getMiscFlags() & cl::Sink)
277
0
      for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
278
0
        if (*Opt == O) {
279
0
          Sub.SinkOpts.erase(Opt);
280
0
          break;
281
0
        }
282
0
      }
283
182
    else if (O == Sub.ConsumeAfterOpt)
284
0
      Sub.ConsumeAfterOpt = nullptr;
285
188
  }
286
287
118
  void removeOption(Option *O) {
288
118
    if (O->Subs.empty())
289
64
      removeOption(O, &*TopLevelSubCommand);
290
54
    else {
291
54
      if (O->isInAllSubCommands()) {
292
39
        for (auto SC : RegisteredSubCommands)
293
109
          removeOption(O, SC);
294
39
      } else {
295
15
        for (auto SC : O->Subs)
296
15
          removeOption(O, SC);
297
15
      }
298
54
    }
299
118
  }
300
301
0
  bool hasOptions(const SubCommand &Sub) const {
302
0
    return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
303
0
            nullptr != Sub.ConsumeAfterOpt);
304
0
  }
305
306
0
  bool hasOptions() const {
307
0
    for (const auto &S : RegisteredSubCommands) {
308
0
      if (hasOptions(*S))
309
0
        return true;
310
0
    }
311
0
    return false;
312
0
  }
313
314
1.75k
  SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
315
316
1
  void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
317
1
    SubCommand &Sub = *SC;
318
1
    if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
319
0
      errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
320
0
             << "' registered more than once!\n";
321
0
      report_fatal_error("inconsistency in registered CommandLine options");
322
0
    }
323
1
    Sub.OptionsMap.erase(O->ArgStr);
324
1
  }
325
326
1
  void updateArgStr(Option *O, StringRef NewName) {
327
1
    if (O->Subs.empty())
328
1
      updateArgStr(O, NewName, &*TopLevelSubCommand);
329
0
    else {
330
0
      if (O->isInAllSubCommands()) {
331
0
        for (auto SC : RegisteredSubCommands)
332
0
          updateArgStr(O, NewName, SC);
333
0
      } else {
334
0
        for (auto SC : O->Subs)
335
0
          updateArgStr(O, NewName, SC);
336
0
      }
337
0
    }
338
1
  }
339
340
  void printOptionValues();
341
342
509k
  void registerCategory(OptionCategory *cat) {
343
509k
    assert(count_if(RegisteredOptionCategories,
344
509k
                    [cat](const OptionCategory *Category) {
345
509k
             return cat->getName() == Category->getName();
346
509k
           }) == 0 &&
347
509k
           "Duplicate option categories");
348
509k
349
509k
    RegisteredOptionCategories.insert(cat);
350
509k
  }
351
352
281k
  void registerSubCommand(SubCommand *sub) {
353
281k
    assert(count_if(RegisteredSubCommands,
354
281k
                    [sub](const SubCommand *Sub) {
355
281k
                      return (!sub->getName().empty()) &&
356
281k
                             (Sub->getName() == sub->getName());
357
281k
                    }) == 0 &&
358
281k
           "Duplicate subcommands");
359
281k
    RegisteredSubCommands.insert(sub);
360
281k
361
281k
    // For all options that have been registered for all subcommands, add the
362
281k
    // option to this subcommand now.
363
281k
    if (sub != &*AllSubCommands) {
364
141k
      for (auto &E : AllSubCommands->OptionsMap) {
365
305
        Option *O = E.second;
366
305
        if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
367
305
            O->hasArgStr())
368
305
          addOption(O, sub);
369
0
        else
370
0
          addLiteralOption(*O, sub, E.first());
371
305
      }
372
141k
    }
373
281k
  }
374
375
51
  void unregisterSubCommand(SubCommand *sub) {
376
51
    RegisteredSubCommands.erase(sub);
377
51
  }
378
379
  iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
380
78
  getRegisteredSubcommands() {
381
78
    return make_range(RegisteredSubCommands.begin(),
382
78
                      RegisteredSubCommands.end());
383
78
  }
384
385
16
  void reset() {
386
16
    ActiveSubCommand = nullptr;
387
16
    ProgramName.clear();
388
16
    ProgramOverview = StringRef();
389
16
390
16
    MoreHelp.clear();
391
16
    RegisteredOptionCategories.clear();
392
16
393
16
    ResetAllOptionOccurrences();
394
16
    RegisteredSubCommands.clear();
395
16
396
16
    TopLevelSubCommand->reset();
397
16
    AllSubCommands->reset();
398
16
    registerSubCommand(&*TopLevelSubCommand);
399
16
    registerSubCommand(&*AllSubCommands);
400
16
401
16
    DefaultOptions.clear();
402
16
  }
403
404
private:
405
  SubCommand *ActiveSubCommand;
406
407
  Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
408
  Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
409
181k
                           bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
410
181k
    Option *Opt = LookupOption(Sub, Arg, Value);
411
181k
    if (Opt && 
LongOptionsUseDoubleDash178k
&&
!HaveDoubleDash6
&&
!isGrouping(Opt)4
)
412
2
      return nullptr;
413
181k
    return Opt;
414
181k
  }
415
  SubCommand *LookupSubCommand(StringRef Name);
416
};
417
418
} // namespace
419
420
static ManagedStatic<CommandLineParser> GlobalParser;
421
422
90.5M
void cl::AddLiteralOption(Option &O, StringRef Name) {
423
90.5M
  GlobalParser->addLiteralOption(O, Name);
424
90.5M
}
425
426
10.3k
extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
427
10.3k
  GlobalParser->MoreHelp.push_back(Help);
428
10.3k
}
429
430
148M
void Option::addArgument() {
431
148M
  GlobalParser->addOption(this);
432
148M
  FullyInitialized = true;
433
148M
}
434
435
118
void Option::removeArgument() { GlobalParser->removeOption(this); }
436
437
147M
void Option::setArgStr(StringRef S) {
438
147M
  if (FullyInitialized)
439
1
    GlobalParser->updateArgStr(this, S);
440
147M
  assert((S.empty() || S[0] != '-') && "Option can't start with '-");
441
147M
  ArgStr = S;
442
147M
  if (ArgStr.size() == 1)
443
574k
    setMiscFlag(Grouping);
444
147M
}
445
446
11.1M
void Option::addCategory(OptionCategory &C) {
447
11.1M
  assert(!Categories.empty() && "Categories cannot be empty.");
448
11.1M
  // Maintain backward compatibility by replacing the default GeneralCategory
449
11.1M
  // if it's still set.  Otherwise, just add the new one.  The GeneralCategory
450
11.1M
  // must be explicitly added if you want multiple categories that include it.
451
11.1M
  if (&C != &GeneralCategory && 
Categories[0] == &GeneralCategory11.1M
)
452
11.1M
    Categories[0] = &C;
453
117
  else if (find(Categories, &C) == Categories.end())
454
2
    Categories.push_back(&C);
455
11.1M
}
456
457
53.0k
void Option::reset() {
458
53.0k
  NumOccurrences = 0;
459
53.0k
  setDefault();
460
53.0k
  if (isDefaultOption())
461
31
    removeArgument();
462
53.0k
}
463
464
// Initialise the general option category.
465
OptionCategory llvm::cl::GeneralCategory("General options");
466
467
509k
void OptionCategory::registerCategory() {
468
509k
  GlobalParser->registerCategory(this);
469
509k
}
470
471
// A special subcommand representing no subcommand. It is particularly important
472
// that this ManagedStatic uses constant initailization and not dynamic
473
// initialization because it is referenced from cl::opt constructors, which run
474
// dynamically in an arbitrary order.
475
LLVM_REQUIRE_CONSTANT_INITIALIZATION
476
ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
477
478
// A special subcommand that can be used to put an option into all subcommands.
479
ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
480
481
2.21k
void SubCommand::registerSubCommand() {
482
2.21k
  GlobalParser->registerSubCommand(this);
483
2.21k
}
484
485
51
void SubCommand::unregisterSubCommand() {
486
51
  GlobalParser->unregisterSubCommand(this);
487
51
}
488
489
32
void SubCommand::reset() {
490
32
  PositionalOpts.clear();
491
32
  SinkOpts.clear();
492
32
  OptionsMap.clear();
493
32
494
32
  ConsumeAfterOpt = nullptr;
495
32
}
496
497
1.72k
SubCommand::operator bool() const {
498
1.72k
  return (GlobalParser->getActiveSubCommand() == this);
499
1.72k
}
500
501
//===----------------------------------------------------------------------===//
502
// Basic, shared command line option processing machinery.
503
//
504
505
/// LookupOption - Lookup the option specified by the specified option on the
506
/// command line.  If there is a value specified (after an equal sign) return
507
/// that as well.  This assumes that leading dashes have already been stripped.
508
Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
509
181k
                                        StringRef &Value) {
510
181k
  // Reject all dashes.
511
181k
  if (Arg.empty())
512
0
    return nullptr;
513
181k
  assert(&Sub != &*AllSubCommands);
514
181k
515
181k
  size_t EqualPos = Arg.find('=');
516
181k
517
181k
  // If we have an equals sign, remember the value.
518
181k
  if (EqualPos == StringRef::npos) {
519
92.6k
    // Look up the option.
520
92.6k
    auto I = Sub.OptionsMap.find(Arg);
521
92.6k
    if (I == Sub.OptionsMap.end())
522
2.95k
      return nullptr;
523
89.7k
524
89.7k
    return I != Sub.OptionsMap.end() ? I->second : 
nullptr0
;
525
89.7k
  }
526
88.9k
527
88.9k
  // If the argument before the = is a valid option name and the option allows
528
88.9k
  // non-prefix form (ie is not AlwaysPrefix), we match.  If not, signal match
529
88.9k
  // failure by returning nullptr.
530
88.9k
  auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
531
88.9k
  if (I == Sub.OptionsMap.end())
532
9
    return nullptr;
533
88.9k
534
88.9k
  auto O = I->second;
535
88.9k
  if (O->getFormattingFlag() == cl::AlwaysPrefix)
536
2
    return nullptr;
537
88.9k
538
88.9k
  Value = Arg.substr(EqualPos + 1);
539
88.9k
  Arg = Arg.substr(0, EqualPos);
540
88.9k
  return I->second;
541
88.9k
}
542
543
4.72k
SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
544
4.72k
  if (Name.empty())
545
0
    return &*TopLevelSubCommand;
546
10.4k
  
for (auto S : RegisteredSubCommands)4.72k
{
547
10.4k
    if (S == &*AllSubCommands)
548
4.61k
      continue;
549
5.86k
    if (S->getName().empty())
550
4.66k
      continue;
551
1.20k
552
1.20k
    if (StringRef(S->getName()) == StringRef(Name))
553
289
      return S;
554
1.20k
  }
555
4.72k
  
return &*TopLevelSubCommand4.44k
;
556
4.72k
}
557
558
/// LookupNearestOption - Lookup the closest match to the option specified by
559
/// the specified option on the command line.  If there is a value specified
560
/// (after an equal sign) return that as well.  This assumes that leading dashes
561
/// have already been stripped.
562
static Option *LookupNearestOption(StringRef Arg,
563
                                   const StringMap<Option *> &OptionsMap,
564
15
                                   std::string &NearestString) {
565
15
  // Reject all dashes.
566
15
  if (Arg.empty())
567
0
    return nullptr;
568
15
569
15
  // Split on any equal sign.
570
15
  std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
571
15
  StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
572
15
  StringRef &RHS = SplitArg.second;
573
15
574
15
  // Find the closest match.
575
15
  Option *Best = nullptr;
576
15
  unsigned BestDistance = 0;
577
15
  for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
578
15
                                           ie = OptionsMap.end();
579
10.7k
       it != ie; 
++it10.7k
) {
580
10.7k
    Option *O = it->second;
581
10.7k
    SmallVector<StringRef, 16> OptionNames;
582
10.7k
    O->getExtraOptionNames(OptionNames);
583
10.7k
    if (O->hasArgStr())
584
9.77k
      OptionNames.push_back(O->ArgStr);
585
10.7k
586
10.7k
    bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
587
10.7k
    StringRef Flag = PermitValue ? 
LHS9.72k
:
Arg1.03k
;
588
463k
    for (auto Name : OptionNames) {
589
463k
      unsigned Distance = StringRef(Name).edit_distance(
590
463k
          Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
591
463k
      if (!Best || 
Distance < BestDistance463k
) {
592
56
        Best = O;
593
56
        BestDistance = Distance;
594
56
        if (RHS.empty() || 
!PermitValue0
)
595
56
          NearestString = Name;
596
0
        else
597
0
          NearestString = (Twine(Name) + "=" + RHS).str();
598
56
      }
599
463k
    }
600
10.7k
  }
601
15
602
15
  return Best;
603
15
}
604
605
/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
606
/// that does special handling of cl::CommaSeparated options.
607
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
608
                                          StringRef ArgName, StringRef Value,
609
208k
                                          bool MultiArg = false) {
610
208k
  // Check to see if this option accepts a comma separated list of values.  If
611
208k
  // it does, we have to split up the value into multiple values.
612
208k
  if (Handler->getMiscFlags() & CommaSeparated) {
613
12.6k
    StringRef Val(Value);
614
12.6k
    StringRef::size_type Pos = Val.find(',');
615
12.6k
616
16.0k
    while (Pos != StringRef::npos) {
617
3.40k
      // Process the portion before the comma.
618
3.40k
      if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
619
0
        return true;
620
3.40k
      // Erase the portion before the comma, AND the comma.
621
3.40k
      Val = Val.substr(Pos + 1);
622
3.40k
      // Check for another comma.
623
3.40k
      Pos = Val.find(',');
624
3.40k
    }
625
12.6k
626
12.6k
    Value = Val;
627
12.6k
  }
628
208k
629
208k
  return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
630
208k
}
631
632
/// ProvideOption - For Value, this differentiates between an empty value ("")
633
/// and a null value (StringRef()).  The later is accepted for arguments that
634
/// don't allow a value (-foo) the former is rejected (-foo=).
635
static inline bool ProvideOption(Option *Handler, StringRef ArgName,
636
                                 StringRef Value, int argc,
637
208k
                                 const char *const *argv, int &i) {
638
208k
  // Is this a multi-argument option?
639
208k
  unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
640
208k
641
208k
  // Enforce value requirements
642
208k
  switch (Handler->getValueExpectedFlag()) {
643
208k
  case ValueRequired:
644
136k
    if (!Value.data()) { // No value specified?
645
21.6k
      // If no other argument or the option only supports prefix form, we
646
21.6k
      // cannot look at the next argument.
647
21.6k
      if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
648
3
        return Handler->error("requires a value!");
649
21.6k
      // Steal the next argument, like for '-o filename'
650
21.6k
      assert(argv && "null check");
651
21.6k
      Value = StringRef(argv[++i]);
652
21.6k
    }
653
136k
    
break136k
;
654
136k
  case ValueDisallowed:
655
13.1k
    if (NumAdditionalVals > 0)
656
0
      return Handler->error("multi-valued option specified"
657
0
                            " with ValueDisallowed modifier!");
658
13.1k
659
13.1k
    if (Value.data())
660
1
      return Handler->error("does not allow a value! '" + Twine(Value) +
661
1
                            "' specified.");
662
13.1k
    break;
663
58.4k
  case ValueOptional:
664
58.4k
    break;
665
208k
  }
666
208k
667
208k
  // If this isn't a multi-arg option, just run the handler.
668
208k
  if (NumAdditionalVals == 0)
669
208k
    return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
670
1
671
1
  // If it is, run the handle several times.
672
1
  bool MultiArg = false;
673
1
674
1
  if (Value.data()) {
675
1
    if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
676
0
      return true;
677
1
    --NumAdditionalVals;
678
1
    MultiArg = true;
679
1
  }
680
1
681
2
  
while (1
NumAdditionalVals > 0) {
682
1
    if (i + 1 >= argc)
683
0
      return Handler->error("not enough values!");
684
1
    assert(argv && "null check");
685
1
    Value = StringRef(argv[++i]);
686
1
687
1
    if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
688
0
      return true;
689
1
    MultiArg = true;
690
1
    --NumAdditionalVals;
691
1
  }
692
1
  return false;
693
1
}
694
695
26.5k
static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
696
26.5k
  int Dummy = i;
697
26.5k
  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
698
26.5k
}
699
700
// getOptionPred - Check to see if there are any options that satisfy the
701
// specified predicate with names that are the prefixes in Name.  This is
702
// checked by progressively stripping characters off of the name, checking to
703
// see if there options that satisfy the predicate.  If we find one, return it,
704
// otherwise return null.
705
//
706
static Option *getOptionPred(StringRef Name, size_t &Length,
707
                             bool (*Pred)(const Option *),
708
3.07k
                             const StringMap<Option *> &OptionsMap) {
709
3.07k
  StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
710
3.07k
  if (OMI != OptionsMap.end() && 
!Pred(OMI->getValue())39
)
711
2
    OMI = OptionsMap.end();
712
3.07k
713
3.07k
  // Loop while we haven't found an option and Name still has at least two
714
3.07k
  // characters in it (so that the next iteration will not be the empty
715
3.07k
  // string.
716
8.60k
  while (OMI == OptionsMap.end() && 
Name.size() > 15.54k
) {
717
5.53k
    Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
718
5.53k
    OMI = OptionsMap.find(Name);
719
5.53k
    if (OMI != OptionsMap.end() && 
!Pred(OMI->getValue())3.02k
)
720
0
      OMI = OptionsMap.end();
721
5.53k
  }
722
3.07k
723
3.07k
  if (OMI != OptionsMap.end() && 
Pred(OMI->second)3.05k
) {
724
3.05k
    Length = Name.size();
725
3.05k
    return OMI->second; // Found one!
726
3.05k
  }
727
13
  return nullptr; // No option found!
728
13
}
729
730
/// HandlePrefixedOrGroupedOption - The specified argument string (which started
731
/// with at least one '-') does not fully match an available option.  Check to
732
/// see if this is a prefix or grouped option.  If so, split arg into output an
733
/// Arg/Value pair and return the Option to parse it with.
734
static Option *
735
HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
736
                              bool &ErrorParsing,
737
2.96k
                              const StringMap<Option *> &OptionsMap) {
738
2.96k
  if (Arg.size() == 1)
739
0
    return nullptr;
740
2.96k
741
2.96k
  // Do the lookup!
742
2.96k
  size_t Length = 0;
743
2.96k
  Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
744
2.96k
  if (!PGOpt)
745
12
    return nullptr;
746
2.94k
747
3.05k
  
do 2.94k
{
748
3.05k
    StringRef MaybeValue =
749
3.05k
        (Length < Arg.size()) ? 
Arg.substr(Length)3.02k
:
StringRef()37
;
750
3.05k
    Arg = Arg.substr(0, Length);
751
3.05k
    assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
752
3.05k
753
3.05k
    // cl::Prefix options do not preserve '=' when used separately.
754
3.05k
    // The behavior for them with grouped options should be the same.
755
3.05k
    if (MaybeValue.empty() || 
PGOpt->getFormattingFlag() == cl::AlwaysPrefix3.02k
||
756
3.05k
        
(3.01k
PGOpt->getFormattingFlag() == cl::Prefix3.01k
&&
MaybeValue[0] != '='2.89k
)) {
757
2.93k
      Value = MaybeValue;
758
2.93k
      return PGOpt;
759
2.93k
    }
760
120
761
120
    if (MaybeValue[0] == '=') {
762
8
      Value = MaybeValue.substr(1);
763
8
      return PGOpt;
764
8
    }
765
112
766
112
    // This must be a grouped option.
767
112
    assert(isGrouping(PGOpt) && "Broken getOptionPred!");
768
112
769
112
    // Grouping options inside a group can't have values.
770
112
    if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
771
2
      ErrorParsing |= PGOpt->error("may not occur within a group!");
772
2
      return nullptr;
773
2
    }
774
110
775
110
    // Because the value for the option is not required, we don't need to pass
776
110
    // argc/argv in.
777
110
    int Dummy = 0;
778
110
    ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
779
110
780
110
    // Get the next grouping option.
781
110
    Arg = MaybeValue;
782
110
    PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
783
110
  } while (PGOpt);
784
2.94k
785
2.94k
  // We could not find a grouping option in the remainder of Arg.
786
2.94k
  
return nullptr1
;
787
2.94k
}
788
789
126k
static bool RequiresValue(const Option *O) {
790
126k
  return O->getNumOccurrencesFlag() == cl::Required ||
791
126k
         
O->getNumOccurrencesFlag() == cl::OneOrMore126k
;
792
126k
}
793
794
63.4k
static bool EatsUnboundedNumberOfValues(const Option *O) {
795
63.4k
  return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
796
63.4k
         
O->getNumOccurrencesFlag() == cl::OneOrMore53.5k
;
797
63.4k
}
798
799
3.61M
static bool isWhitespace(char C) {
800
3.61M
  return C == ' ' || 
C == '\t'2.71M
||
C == '\r'2.71M
||
C == '\n'2.71M
;
801
3.61M
}
802
803
8.28k
static bool isWhitespaceOrNull(char C) {
804
8.28k
  return isWhitespace(C) || 
C == '\0'7.74k
;
805
8.28k
}
806
807
3.30M
static bool isQuote(char C) { return C == '\"' || 
C == '\''2.70M
; }
808
809
void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
810
                                SmallVectorImpl<const char *> &NewArgv,
811
91
                                bool MarkEOLs) {
812
91
  SmallString<128> Token;
813
3.30M
  for (size_t I = 0, E = Src.size(); I != E; 
++I3.30M
) {
814
3.30M
    // Consume runs of whitespace.
815
3.30M
    if (Token.empty()) {
816
900k
      while (I != E && 
isWhitespace(Src[I])900k
) {
817
21
        // Mark the end of lines in response files
818
21
        if (MarkEOLs && 
Src[I] == '\n'0
)
819
0
          NewArgv.push_back(nullptr);
820
21
        ++I;
821
21
      }
822
900k
      if (I == E)
823
2
        break;
824
3.30M
    }
825
3.30M
826
3.30M
    char C = Src[I];
827
3.30M
828
3.30M
    // Backslash escapes the next character.
829
3.30M
    if (I + 1 < E && 
C == '\\'3.30M
) {
830
20
      ++I; // Skip the escape.
831
20
      Token.push_back(Src[I]);
832
20
      continue;
833
20
    }
834
3.30M
835
3.30M
    // Consume a quoted string.
836
3.30M
    if (isQuote(C)) {
837
600k
      ++I;
838
2.40M
      while (I != E && Src[I] != C) {
839
1.80M
        // Backslash escapes the next character.
840
1.80M
        if (Src[I] == '\\' && 
I + 1 != E9
)
841
9
          ++I;
842
1.80M
        Token.push_back(Src[I]);
843
1.80M
        ++I;
844
1.80M
      }
845
600k
      if (I == E)
846
0
        break;
847
600k
      continue;
848
600k
    }
849
2.70M
850
2.70M
    // End the token if this is whitespace.
851
2.70M
    if (isWhitespace(C)) {
852
900k
      if (!Token.empty())
853
900k
        NewArgv.push_back(Saver.save(StringRef(Token)).data());
854
900k
      Token.clear();
855
900k
      continue;
856
900k
    }
857
1.80M
858
1.80M
    // This is a normal character.  Append it.
859
1.80M
    Token.push_back(C);
860
1.80M
  }
861
91
862
91
  // Append the last token after hitting EOF with no whitespace.
863
91
  if (!Token.empty())
864
59
    NewArgv.push_back(Saver.save(StringRef(Token)).data());
865
91
  // Mark the end of response files
866
91
  if (MarkEOLs)
867
0
    NewArgv.push_back(nullptr);
868
91
}
869
870
/// Backslashes are interpreted in a rather complicated way in the Windows-style
871
/// command line, because backslashes are used both to separate path and to
872
/// escape double quote. This method consumes runs of backslashes as well as the
873
/// following double quote if it's escaped.
874
///
875
///  * If an even number of backslashes is followed by a double quote, one
876
///    backslash is output for every pair of backslashes, and the last double
877
///    quote remains unconsumed. The double quote will later be interpreted as
878
///    the start or end of a quoted string in the main loop outside of this
879
///    function.
880
///
881
///  * If an odd number of backslashes is followed by a double quote, one
882
///    backslash is output for every pair of backslashes, and a double quote is
883
///    output for the last pair of backslash-double quote. The double quote is
884
///    consumed in this case.
885
///
886
///  * Otherwise, backslashes are interpreted literally.
887
21
static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
888
21
  size_t E = Src.size();
889
21
  int BackslashCount = 0;
890
21
  // Skip the backslashes.
891
25
  do {
892
25
    ++I;
893
25
    ++BackslashCount;
894
25
  } while (I != E && Src[I] == '\\');
895
21
896
21
  bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
897
21
  if (FollowedByDoubleQuote) {
898
6
    Token.append(BackslashCount / 2, '\\');
899
6
    if (BackslashCount % 2 == 0)
900
1
      return I - 1;
901
5
    Token.push_back('"');
902
5
    return I;
903
5
  }
904
15
  Token.append(BackslashCount, '\\');
905
15
  return I - 1;
906
15
}
907
908
void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
909
                                    SmallVectorImpl<const char *> &NewArgv,
910
217
                                    bool MarkEOLs) {
911
217
  SmallString<128> Token;
912
217
913
217
  // This is a small state machine to consume characters until it reaches the
914
217
  // end of the source string.
915
217
  enum { INIT, UNQUOTED, QUOTED } State = INIT;
916
9.80k
  for (size_t I = 0, E = Src.size(); I != E; 
++I9.58k
) {
917
9.58k
    char C = Src[I];
918
9.58k
919
9.58k
    // INIT state indicates that the current input index is at the start of
920
9.58k
    // the string or between tokens.
921
9.58k
    if (State == INIT) {
922
670
      if (isWhitespaceOrNull(C)) {
923
279
        // Mark the end of lines in response files
924
279
        if (MarkEOLs && 
C == '\n'0
)
925
0
          NewArgv.push_back(nullptr);
926
279
        continue;
927
279
      }
928
391
      if (C == '"') {
929
4
        State = QUOTED;
930
4
        continue;
931
4
      }
932
387
      if (C == '\\') {
933
1
        I = parseBackslash(Src, I, Token);
934
1
        State = UNQUOTED;
935
1
        continue;
936
1
      }
937
386
      Token.push_back(C);
938
386
      State = UNQUOTED;
939
386
      continue;
940
386
    }
941
8.91k
942
8.91k
    // UNQUOTED state means that it's reading a token not quoted by double
943
8.91k
    // quotes.
944
8.91k
    if (State == UNQUOTED) {
945
7.61k
      // Whitespace means the end of the token.
946
7.61k
      if (isWhitespaceOrNull(C)) {
947
337
        NewArgv.push_back(Saver.save(StringRef(Token)).data());
948
337
        Token.clear();
949
337
        State = INIT;
950
337
        // Mark the end of lines in response files
951
337
        if (MarkEOLs && 
C == '\n'5
)
952
2
          NewArgv.push_back(nullptr);
953
337
        continue;
954
337
      }
955
7.27k
      if (C == '"') {
956
158
        State = QUOTED;
957
158
        continue;
958
158
      }
959
7.11k
      if (C == '\\') {
960
19
        I = parseBackslash(Src, I, Token);
961
19
        continue;
962
19
      }
963
7.09k
      Token.push_back(C);
964
7.09k
      continue;
965
7.09k
    }
966
1.30k
967
1.30k
    // QUOTED state means that it's reading a token quoted by double quotes.
968
1.30k
    if (State == QUOTED) {
969
1.30k
      if (C == '"') {
970
164
        if (I < (E - 1) && Src[I + 1] == '"') {
971
2
          // Consecutive double-quotes inside a quoted string implies one
972
2
          // double-quote.
973
2
          Token.push_back('"');
974
2
          I = I + 1;
975
2
          continue;
976
2
        }
977
162
        State = UNQUOTED;
978
162
        continue;
979
162
      }
980
1.14k
      if (C == '\\') {
981
1
        I = parseBackslash(Src, I, Token);
982
1
        continue;
983
1
      }
984
1.14k
      Token.push_back(C);
985
1.14k
    }
986
1.30k
  }
987
217
  // Append the last token after hitting EOF with no whitespace.
988
217
  if (!Token.empty())
989
54
    NewArgv.push_back(Saver.save(StringRef(Token)).data());
990
217
  // Mark the end of response files
991
217
  if (MarkEOLs)
992
2
    NewArgv.push_back(nullptr);
993
217
}
994
995
void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
996
                            SmallVectorImpl<const char *> &NewArgv,
997
49
                            bool MarkEOLs) {
998
186
  for (const char *Cur = Source.begin(); Cur != Source.end();) {
999
137
    SmallString<128> Line;
1000
137
    // Check for comment line.
1001
137
    if (isWhitespace(*Cur)) {
1002
170
      while (Cur != Source.end() && 
isWhitespace(*Cur)133
)
1003
105
        ++Cur;
1004
65
      continue;
1005
65
    }
1006
72
    if (*Cur == '#') {
1007
340
      while (Cur != Source.end() && *Cur != '\n')
1008
326
        ++Cur;
1009
14
      continue;
1010
14
    }
1011
58
    // Find end of the current line.
1012
58
    const char *Start = Cur;
1013
765
    for (const char *End = Source.end(); Cur != End; 
++Cur707
) {
1014
754
      if (*Cur == '\\') {
1015
12
        if (Cur + 1 != End) {
1016
10
          ++Cur;
1017
10
          if (*Cur == '\n' ||
1018
10
              
(5
*Cur == '\r'5
&&
(Cur + 1 != End)4
&&
Cur[1] == '\n'4
)) {
1019
9
            Line.append(Start, Cur - 1);
1020
9
            if (*Cur == '\r')
1021
4
              ++Cur;
1022
9
            Start = Cur + 1;
1023
9
          }
1024
10
        }
1025
742
      } else if (*Cur == '\n')
1026
47
        break;
1027
754
    }
1028
58
    // Tokenize line.
1029
58
    Line.append(Start, Cur);
1030
58
    cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1031
58
  }
1032
49
}
1033
1034
// It is called byte order marker but the UTF-8 BOM is actually not affected
1035
// by the host system's endianness.
1036
76
static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
1037
76
  return (S.size() >= 3 && 
S[0] == '\xef'75
&&
S[1] == '\xbb'1
&&
S[2] == '\xbf'1
);
1038
76
}
1039
1040
static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
1041
                               TokenizerCallback Tokenizer,
1042
                               SmallVectorImpl<const char *> &NewArgv,
1043
160
                               bool MarkEOLs, bool RelativeNames) {
1044
160
  ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1045
160
      MemoryBuffer::getFile(FName);
1046
160
  if (!MemBufOrErr)
1047
83
    return false;
1048
77
  MemoryBuffer &MemBuf = *MemBufOrErr.get();
1049
77
  StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1050
77
1051
77
  // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1052
77
  ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1053
77
  std::string UTF8Buf;
1054
77
  if (hasUTF16ByteOrderMark(BufRef)) {
1055
1
    if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1056
0
      return false;
1057
1
    Str = StringRef(UTF8Buf);
1058
1
  }
1059
76
  // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1060
76
  // these bytes before parsing.
1061
76
  // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1062
76
  else if (hasUTF8ByteOrderMark(BufRef))
1063
1
    Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1064
77
1065
77
  // Tokenize the contents into NewArgv.
1066
77
  Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1067
77
1068
77
  // If names of nested response files should be resolved relative to including
1069
77
  // file, replace the included response file names with their full paths
1070
77
  // obtained by required resolution.
1071
77
  if (RelativeNames)
1072
113
    
for (unsigned I = 0; 41
I < NewArgv.size();
++I72
)
1073
72
      if (NewArgv[I]) {
1074
72
        StringRef Arg = NewArgv[I];
1075
72
        if (Arg.front() == '@') {
1076
8
          StringRef FileName = Arg.drop_front();
1077
8
          if (llvm::sys::path::is_relative(FileName)) {
1078
8
            SmallString<128> ResponseFile;
1079
8
            ResponseFile.append(1, '@');
1080
8
            if (llvm::sys::path::is_relative(FName)) {
1081
0
              SmallString<128> curr_dir;
1082
0
              llvm::sys::fs::current_path(curr_dir);
1083
0
              ResponseFile.append(curr_dir.str());
1084
0
            }
1085
8
            llvm::sys::path::append(
1086
8
                ResponseFile, llvm::sys::path::parent_path(FName), FileName);
1087
8
            NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
1088
8
          }
1089
8
        }
1090
72
      }
1091
77
1092
77
  return true;
1093
77
}
1094
1095
/// Expand response files on a command line recursively using the given
1096
/// StringSaver and tokenization strategy.
1097
bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1098
                             SmallVectorImpl<const char *> &Argv,
1099
170k
                             bool MarkEOLs, bool RelativeNames) {
1100
170k
  bool AllExpanded = true;
1101
170k
  struct ResponseFileRecord {
1102
170k
    const char *File;
1103
170k
    size_t End;
1104
170k
  };
1105
170k
1106
170k
  // To detect recursive response files, we maintain a stack of files and the
1107
170k
  // position of the last argument in the file. This position is updated
1108
170k
  // dynamically as we recursively expand files.
1109
170k
  SmallVector<ResponseFileRecord, 3> FileStack;
1110
170k
1111
170k
  // Push a dummy entry that represents the initial command line, removing
1112
170k
  // the need to check for an empty list.
1113
170k
  FileStack.push_back({"", Argv.size()});
1114
170k
1115
170k
  // Don't cache Argv.size() because it can change.
1116
3.49M
  for (unsigned I = 0; I != Argv.size();) {
1117
3.32M
    while (I == FileStack.back().End) {
1118
23
      // Passing the end of a file's argument list, so we can remove it from the
1119
23
      // stack.
1120
23
      FileStack.pop_back();
1121
23
    }
1122
3.32M
1123
3.32M
    const char *Arg = Argv[I];
1124
3.32M
    // Check if it is an EOL marker
1125
3.32M
    if (Arg == nullptr) {
1126
4
      ++I;
1127
4
      continue;
1128
4
    }
1129
3.32M
1130
3.32M
    if (Arg[0] != '@') {
1131
3.32M
      ++I;
1132
3.32M
      continue;
1133
3.32M
    }
1134
131
1135
131
    const char *FName = Arg + 1;
1136
131
    auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
1137
11
      return sys::fs::equivalent(RFile.File, FName);
1138
11
    };
1139
131
1140
131
    // Check for recursive response files.
1141
131
    if (std::any_of(FileStack.begin() + 1, FileStack.end(), IsEquivalent)) {
1142
3
      // This file is recursive, so we leave it in the argument stream and
1143
3
      // move on.
1144
3
      AllExpanded = false;
1145
3
      ++I;
1146
3
      continue;
1147
3
    }
1148
128
1149
128
    // Replace this response file argument with the tokenization of its
1150
128
    // contents.  Nested response files are expanded in subsequent iterations.
1151
128
    SmallVector<const char *, 0> ExpandedArgv;
1152
128
    if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
1153
128
                            RelativeNames)) {
1154
83
      // We couldn't read this file, so we leave it in the argument stream and
1155
83
      // move on.
1156
83
      AllExpanded = false;
1157
83
      ++I;
1158
83
      continue;
1159
83
    }
1160
45
1161
52
    
for (ResponseFileRecord &Record : FileStack)45
{
1162
52
      // Increase the end of all active records by the number of newly expanded
1163
52
      // arguments, minus the response file itself.
1164
52
      Record.End += ExpandedArgv.size() - 1;
1165
52
    }
1166
45
1167
45
    FileStack.push_back({FName, I + ExpandedArgv.size()});
1168
45
    Argv.erase(Argv.begin() + I);
1169
45
    Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1170
45
  }
1171
170k
1172
170k
  // If successful, the top of the file stack will mark the end of the Argv
1173
170k
  // stream. A failure here indicates a bug in the stack popping logic above.
1174
170k
  // Note that FileStack may have more than one element at this point because we
1175
170k
  // don't have a chance to pop the stack when encountering recursive files at
1176
170k
  // the end of the stream, so seeing that doesn't indicate a bug.
1177
170k
  assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1178
170k
  return AllExpanded;
1179
170k
}
1180
1181
bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1182
32
                        SmallVectorImpl<const char *> &Argv) {
1183
32
  if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1184
32
                          /*MarkEOLs*/ false, /*RelativeNames*/ true))
1185
0
    return false;
1186
32
  return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1187
32
                             /*MarkEOLs*/ false, /*RelativeNames*/ true);
1188
32
}
1189
1190
/// ParseEnvironmentOptions - An alternative entry point to the
1191
/// CommandLine library, which allows you to read the program's name
1192
/// from the caller (as PROGNAME) and its command-line arguments from
1193
/// an environment variable (whose name is given in ENVVAR).
1194
///
1195
void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1196
2
                                 const char *Overview) {
1197
2
  // Check args.
1198
2
  assert(progName && "Program name not specified");
1199
2
  assert(envVar && "Environment variable name missing");
1200
2
1201
2
  // Get the environment variable they want us to parse options out of.
1202
2
  llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1203
2
  if (!envValue)
1204
0
    return;
1205
2
1206
2
  // Get program's "name", which we wouldn't know without the caller
1207
2
  // telling us.
1208
2
  SmallVector<const char *, 20> newArgv;
1209
2
  BumpPtrAllocator A;
1210
2
  StringSaver Saver(A);
1211
2
  newArgv.push_back(Saver.save(progName).data());
1212
2
1213
2
  // Parse the value of the environment variable into a "command line"
1214
2
  // and hand it off to ParseCommandLineOptions().
1215
2
  TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1216
2
  int newArgc = static_cast<int>(newArgv.size());
1217
2
  ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1218
2
}
1219
1220
bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1221
                                 StringRef Overview, raw_ostream *Errs,
1222
                                 const char *EnvVar,
1223
102k
                                 bool LongOptionsUseDoubleDash) {
1224
102k
  SmallVector<const char *, 20> NewArgv;
1225
102k
  BumpPtrAllocator A;
1226
102k
  StringSaver Saver(A);
1227
102k
  NewArgv.push_back(argv[0]);
1228
102k
1229
102k
  // Parse options from environment variable.
1230
102k
  if (EnvVar) {
1231
0
    if (llvm::Optional<std::string> EnvValue =
1232
0
            sys::Process::GetEnv(StringRef(EnvVar)))
1233
0
      TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1234
0
  }
1235
102k
1236
102k
  // Append options from command line.
1237
333k
  for (int I = 1; I < argc; 
++I230k
)
1238
230k
    NewArgv.push_back(argv[I]);
1239
102k
  int NewArgc = static_cast<int>(NewArgv.size());
1240
102k
1241
102k
  // Parse all options.
1242
102k
  return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1243
102k
                                               Errs, LongOptionsUseDoubleDash);
1244
102k
}
1245
1246
186
void CommandLineParser::ResetAllOptionOccurrences() {
1247
186
  // So that we can parse different command lines multiple times in succession
1248
186
  // we reset all option values to look like they have never been seen before.
1249
437
  for (auto SC : RegisteredSubCommands) {
1250
437
    for (auto &O : SC->OptionsMap)
1251
53.0k
      O.second->reset();
1252
437
  }
1253
186
}
1254
1255
bool CommandLineParser::ParseCommandLineOptions(int argc,
1256
                                                const char *const *argv,
1257
                                                StringRef Overview,
1258
                                                raw_ostream *Errs,
1259
102k
                                                bool LongOptionsUseDoubleDash) {
1260
102k
  assert(hasOptions() && "No options specified!");
1261
102k
1262
102k
  // Expand response files.
1263
102k
  SmallVector<const char *, 20> newArgv(argv, argv + argc);
1264
102k
  BumpPtrAllocator A;
1265
102k
  StringSaver Saver(A);
1266
102k
  ExpandResponseFiles(Saver,
1267
102k
         Triple(sys::getProcessTriple()).isOSWindows() ?
1268
102k
         
cl::TokenizeWindowsCommandLine0
: cl::TokenizeGNUCommandLine,
1269
102k
         newArgv);
1270
102k
  argv = &newArgv[0];
1271
102k
  argc = static_cast<int>(newArgv.size());
1272
102k
1273
102k
  // Copy the program name into ProgName, making sure not to overflow it.
1274
102k
  ProgramName = sys::path::filename(StringRef(argv[0]));
1275
102k
1276
102k
  ProgramOverview = Overview;
1277
102k
  bool IgnoreErrors = Errs;
1278
102k
  if (!Errs)
1279
102k
    Errs = &errs();
1280
102k
  bool ErrorParsing = false;
1281
102k
1282
102k
  // Check out the positional arguments to collect information about them.
1283
102k
  unsigned NumPositionalRequired = 0;
1284
102k
1285
102k
  // Determine whether or not there are an unlimited number of positionals
1286
102k
  bool HasUnlimitedPositionals = false;
1287
102k
1288
102k
  int FirstArg = 1;
1289
102k
  SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1290
102k
  if (argc >= 2 && 
argv[FirstArg][0] != '-'70.3k
) {
1291
4.72k
    // If the first argument specifies a valid subcommand, start processing
1292
4.72k
    // options from the second argument.
1293
4.72k
    ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1294
4.72k
    if (ChosenSubCommand != &*TopLevelSubCommand)
1295
289
      FirstArg = 2;
1296
4.72k
  }
1297
102k
  GlobalParser->ActiveSubCommand = ChosenSubCommand;
1298
102k
1299
102k
  assert(ChosenSubCommand);
1300
102k
  auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1301
102k
  auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1302
102k
  auto &SinkOpts = ChosenSubCommand->SinkOpts;
1303
102k
  auto &OptionsMap = ChosenSubCommand->OptionsMap;
1304
102k
1305
102k
  for (auto O: DefaultOptions) {
1306
102k
    addOption(O, true);
1307
102k
  }
1308
102k
1309
102k
  if (ConsumeAfterOpt) {
1310
197
    assert(PositionalOpts.size() > 0 &&
1311
197
           "Cannot specify cl::ConsumeAfter without a positional argument!");
1312
197
  }
1313
102k
  if (!PositionalOpts.empty()) {
1314
63.1k
1315
63.1k
    // Calculate how many positional values are _required_.
1316
63.1k
    bool UnboundedFound = false;
1317
126k
    for (size_t i = 0, e = PositionalOpts.size(); i != e; 
++i63.4k
) {
1318
63.4k
      Option *Opt = PositionalOpts[i];
1319
63.4k
      if (RequiresValue(Opt))
1320
1.40k
        ++NumPositionalRequired;
1321
62.0k
      else if (ConsumeAfterOpt) {
1322
197
        // ConsumeAfter cannot be combined with "optional" positional options
1323
197
        // unless there is only one positional argument...
1324
197
        if (PositionalOpts.size() > 1) {
1325
0
          if (!IgnoreErrors)
1326
0
            Opt->error("error - this positional option will never be matched, "
1327
0
                       "because it does not Require a value, and a "
1328
0
                       "cl::ConsumeAfter option is active!");
1329
0
          ErrorParsing = true;
1330
0
        }
1331
61.8k
      } else if (UnboundedFound && 
!Opt->hasArgStr()110
) {
1332
0
        // This option does not "require" a value...  Make sure this option is
1333
0
        // not specified after an option that eats all extra arguments, or this
1334
0
        // one will never get any!
1335
0
        //
1336
0
        if (!IgnoreErrors)
1337
0
          Opt->error("error - option can never match, because "
1338
0
                     "another positional argument will match an "
1339
0
                     "unbounded number of values, and this option"
1340
0
                     " does not require a value!");
1341
0
        *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1342
0
              << "' is all messed up!\n";
1343
0
        *Errs << PositionalOpts.size();
1344
0
        ErrorParsing = true;
1345
0
      }
1346
63.4k
      UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1347
63.4k
    }
1348
63.1k
    HasUnlimitedPositionals = UnboundedFound || 
ConsumeAfterOpt52.2k
;
1349
63.1k
  }
1350
102k
1351
102k
  // PositionalVals - A vector of "positional" arguments we accumulate into
1352
102k
  // the process at the end.
1353
102k
  //
1354
102k
  SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1355
102k
1356
102k
  // If the program has named positional arguments, and the name has been run
1357
102k
  // across, keep track of which positional argument was named.  Otherwise put
1358
102k
  // the positional args into the PositionalVals list...
1359
102k
  Option *ActivePositionalArg = nullptr;
1360
102k
1361
102k
  // Loop over all of the arguments... processing them.
1362
102k
  bool DashDashFound = false; // Have we read '--'?
1363
310k
  for (int i = FirstArg; i < argc; 
++i208k
) {
1364
208k
    Option *Handler = nullptr;
1365
208k
    Option *NearestHandler = nullptr;
1366
208k
    std::string NearestHandlerString;
1367
208k
    StringRef Value;
1368
208k
    StringRef ArgName = "";
1369
208k
    bool HaveDoubleDash = false;
1370
208k
1371
208k
    // Check to see if this is a positional argument.  This argument is
1372
208k
    // considered to be positional if it doesn't start with '-', if it is "-"
1373
208k
    // itself, or if we have seen "--" already.
1374
208k
    //
1375
208k
    if (argv[i][0] != '-' || 
argv[i][1] == 0184k
||
DashDashFound181k
) {
1376
26.5k
      // Positional argument!
1377
26.5k
      if (ActivePositionalArg) {
1378
3
        ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1379
3
        continue; // We are done!
1380
3
      }
1381
26.5k
1382
26.5k
      if (!PositionalOpts.empty()) {
1383
26.5k
        PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1384
26.5k
1385
26.5k
        // All of the positional arguments have been fulfulled, give the rest to
1386
26.5k
        // the consume after option... if it's specified...
1387
26.5k
        //
1388
26.5k
        if (PositionalVals.size() >= NumPositionalRequired && 
ConsumeAfterOpt26.5k
) {
1389
197
          for (++i; i < argc; 
++i2
)
1390
2
            PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1391
195
          break; // Handle outside of the argument processing loop...
1392
195
        }
1393
26.3k
1394
26.3k
        // Delay processing positional arguments until the end...
1395
26.3k
        continue;
1396
26.3k
      }
1397
181k
    } else if (argv[i][0] == '-' && argv[i][1] == '-' && 
argv[i][2] == 05.83k
&&
1398
181k
               
!DashDashFound0
) {
1399
0
      DashDashFound = true; // This is the mythical "--"?
1400
0
      continue;             // Don't try to process it as an argument itself.
1401
181k
    } else if (ActivePositionalArg &&
1402
181k
               
(ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)5
) {
1403
5
      // If there is a positional argument eating options, check to see if this
1404
5
      // option is another positional argument.  If so, treat it as an argument,
1405
5
      // otherwise feed it to the eating positional.
1406
5
      ArgName = StringRef(argv[i] + 1);
1407
5
      // Eat second dash.
1408
5
      if (!ArgName.empty() && ArgName[0] == '-') {
1409
0
        HaveDoubleDash = true;
1410
0
        ArgName = ArgName.substr(1);
1411
0
      }
1412
5
1413
5
      Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1414
5
                                 LongOptionsUseDoubleDash, HaveDoubleDash);
1415
5
      if (!Handler || 
Handler->getFormattingFlag() != cl::Positional1
) {
1416
4
        ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1417
4
        continue; // We are done!
1418
4
      }
1419
181k
    } else { // We start with a '-', must be an argument.
1420
181k
      ArgName = StringRef(argv[i] + 1);
1421
181k
      // Eat second dash.
1422
181k
      if (!ArgName.empty() && ArgName[0] == '-') {
1423
5.83k
        HaveDoubleDash = true;
1424
5.83k
        ArgName = ArgName.substr(1);
1425
5.83k
      }
1426
181k
1427
181k
      Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1428
181k
                                 LongOptionsUseDoubleDash, HaveDoubleDash);
1429
181k
1430
181k
      // Check to see if this "option" is really a prefixed or grouped argument.
1431
181k
      if (!Handler && 
!(2.96k
LongOptionsUseDoubleDash2.96k
&&
HaveDoubleDash2
))
1432
2.96k
        Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1433
2.96k
                                                OptionsMap);
1434
181k
1435
181k
      // Otherwise, look for the closest available option to report to the user
1436
181k
      // in the upcoming error.
1437
181k
      if (!Handler && 
SinkOpts.empty()15
)
1438
15
        NearestHandler =
1439
15
            LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1440
181k
    }
1441
208k
1442
208k
    
if (181k
!Handler181k
) {
1443
21
      if (SinkOpts.empty()) {
1444
21
        *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1445
21
              << "'.  Try: '" << argv[0] << " --help'\n";
1446
21
1447
21
        if (NearestHandler) {
1448
15
          // If we know a near match, report it as well.
1449
15
          *Errs << ProgramName << ": Did you mean '"
1450
15
                << PrintArg(NearestHandlerString) << "'?\n";
1451
15
        }
1452
21
1453
21
        ErrorParsing = true;
1454
21
      } else {
1455
0
        for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1456
0
                                                 E = SinkOpts.end();
1457
0
             I != E; ++I)
1458
0
          (*I)->addOccurrence(i, "", StringRef(argv[i]));
1459
0
      }
1460
21
      continue;
1461
21
    }
1462
181k
1463
181k
    // If this is a named positional argument, just remember that it is the
1464
181k
    // active one...
1465
181k
    if (Handler->getFormattingFlag() == cl::Positional) {
1466
7
      if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1467
2
        Handler->error("This argument does not take a value.\n"
1468
2
                       "\tInstead, it consumes any positional arguments until "
1469
2
                       "the next recognized option.", *Errs);
1470
2
        ErrorParsing = true;
1471
2
      }
1472
7
      ActivePositionalArg = Handler;
1473
7
    }
1474
181k
    else
1475
181k
      ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1476
181k
  }
1477
102k
1478
102k
  // Check and handle positional arguments now...
1479
102k
  if (NumPositionalRequired > PositionalVals.size()) {
1480
0
      *Errs << ProgramName
1481
0
             << ": Not enough positional command line arguments specified!\n"
1482
0
             << "Must specify at least " << NumPositionalRequired
1483
0
             << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1484
0
             << ": See: " << argv[0] << " --help\n";
1485
0
1486
0
    ErrorParsing = true;
1487
102k
  } else if (!HasUnlimitedPositionals &&
1488
102k
             
PositionalVals.size() > PositionalOpts.size()91.8k
) {
1489
0
    *Errs << ProgramName << ": Too many positional arguments specified!\n"
1490
0
          << "Can specify at most " << PositionalOpts.size()
1491
0
          << " positional arguments: See: " << argv[0] << " --help\n";
1492
0
    ErrorParsing = true;
1493
0
1494
102k
  } else if (!ConsumeAfterOpt) {
1495
102k
    // Positional args have already been handled if ConsumeAfter is specified.
1496
102k
    unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1497
165k
    for (size_t i = 0, e = PositionalOpts.size(); i != e; 
++i63.2k
) {
1498
63.2k
      if (RequiresValue(PositionalOpts[i])) {
1499
1.40k
        ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1500
1.40k
                                PositionalVals[ValNo].second);
1501
1.40k
        ValNo++;
1502
1.40k
        --NumPositionalRequired; // We fulfilled our duty...
1503
1.40k
      }
1504
63.2k
1505
63.2k
      // If we _can_ give this option more arguments, do so now, as long as we
1506
63.2k
      // do not give it values that others need.  'Done' controls whether the
1507
63.2k
      // option even _WANTS_ any more.
1508
63.2k
      //
1509
63.2k
      bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1510
88.1k
      while (NumVals - ValNo > NumPositionalRequired && 
!Done25.0k
) {
1511
24.9k
        switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1512
24.9k
        case cl::Optional:
1513
15.6k
          Done = true; // Optional arguments want _at most_ one value
1514
15.6k
          LLVM_FALLTHROUGH;
1515
24.9k
        case cl::ZeroOrMore: // Zero or more will take all they can get...
1516
24.9k
        case cl::OneOrMore:  // One or more will take all they can get...
1517
24.9k
          ProvidePositionalOption(PositionalOpts[i],
1518
24.9k
                                  PositionalVals[ValNo].first,
1519
24.9k
                                  PositionalVals[ValNo].second);
1520
24.9k
          ValNo++;
1521
24.9k
          break;
1522
24.9k
        default:
1523
0
          llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1524
24.9k
                           "positional argument processing!");
1525
24.9k
        }
1526
24.9k
      }
1527
63.2k
    }
1528
102k
  } else {
1529
230
    assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1530
230
    unsigned ValNo = 0;
1531
230
    for (size_t j = 1, e = PositionalOpts.size(); j != e; 
++j0
)
1532
0
      if (RequiresValue(PositionalOpts[j])) {
1533
0
        ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1534
0
                                                PositionalVals[ValNo].first,
1535
0
                                                PositionalVals[ValNo].second);
1536
0
        ValNo++;
1537
0
      }
1538
230
1539
230
    // Handle the case where there is just one positional option, and it's
1540
230
    // optional.  In this case, we want to give JUST THE FIRST option to the
1541
230
    // positional option and keep the rest for the consume after.  The above
1542
230
    // loop would have assigned no values to positional options in this case.
1543
230
    //
1544
230
    if (PositionalOpts.size() == 1 && 
ValNo == 0197
&&
!PositionalVals.empty()197
) {
1545
195
      ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1546
195
                                              PositionalVals[ValNo].first,
1547
195
                                              PositionalVals[ValNo].second);
1548
195
      ValNo++;
1549
195
    }
1550
230
1551
230
    // Handle over all of the rest of the arguments to the
1552
230
    // cl::ConsumeAfter command line option...
1553
232
    for (; ValNo != PositionalVals.size(); 
++ValNo2
)
1554
2
      ErrorParsing |=
1555
2
          ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1556
2
                                  PositionalVals[ValNo].second);
1557
230
  }
1558
102k
1559
102k
  // Loop over args and make sure all required args are specified!
1560
104M
  
for (const auto &Opt : OptionsMap)102k
{
1561
104M
    switch (Opt.second->getNumOccurrencesFlag()) {
1562
104M
    case Required:
1563
901
    case OneOrMore:
1564
901
      if (Opt.second->getNumOccurrences() == 0) {
1565
4
        Opt.second->error("must be specified at least once!");
1566
4
        ErrorParsing = true;
1567
4
      }
1568
901
      LLVM_FALLTHROUGH;
1569
104M
    default:
1570
104M
      break;
1571
104M
    }
1572
104M
  }
1573
102k
1574
102k
  // Now that we know if -debug is specified, we can use it.
1575
102k
  // Note that if ReadResponseFiles == true, this must be done before the
1576
102k
  // memory allocated for the expanded command line is free()d below.
1577
102k
  LLVM_DEBUG(dbgs() << "Args: ";
1578
102k
             for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1579
102k
             dbgs() << '\n';);
1580
102k
1581
102k
  // Free all of the memory allocated to the map.  Command line options may only
1582
102k
  // be processed once!
1583
102k
  MoreHelp.clear();
1584
102k
1585
102k
  // If we had an error processing our arguments, don't let the program execute
1586
102k
  if (ErrorParsing) {
1587
26
    if (!IgnoreErrors)
1588
8
      exit(1);
1589
18
    return false;
1590
18
  }
1591
102k
  return true;
1592
102k
}
1593
1594
//===----------------------------------------------------------------------===//
1595
// Option Base class implementation
1596
//
1597
1598
3.04k
bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1599
3.04k
  if (!ArgName.data())
1600
3.04k
    ArgName = ArgStr;
1601
3.04k
  if (ArgName.empty())
1602
0
    Errs << HelpStr; // Be nice for positional arguments
1603
3.04k
  else
1604
3.04k
    Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName);
1605
3.04k
1606
3.04k
  Errs << " option: " << Message << "\n";
1607
3.04k
  return true;
1608
3.04k
}
1609
1610
bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1611
211k
                           bool MultiArg) {
1612
211k
  if (!MultiArg)
1613
211k
    NumOccurrences++; // Increment the number of times we have been seen
1614
211k
1615
211k
  switch (getNumOccurrencesFlag()) {
1616
211k
  case Optional:
1617
151k
    if (NumOccurrences > 1)
1618
2
      return error("may only occur zero or one times!", ArgName);
1619
151k
    break;
1620
151k
  case Required:
1621
1.05k
    if (NumOccurrences > 1)
1622
0
      return error("must occur exactly one time!", ArgName);
1623
1.05k
    LLVM_FALLTHROUGH;
1624
60.0k
  case OneOrMore:
1625
60.0k
  case ZeroOrMore:
1626
60.0k
  case ConsumeAfter:
1627
60.0k
    break;
1628
211k
  }
1629
211k
1630
211k
  return handleOccurrence(pos, ArgName, Value);
1631
211k
}
1632
1633
// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1634
// has been specified yet.
1635
//
1636
1.63k
static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1637
1.63k
  if (O.ValueStr.empty())
1638
1.37k
    return DefaultMsg;
1639
258
  return O.ValueStr;
1640
258
}
1641
1642
//===----------------------------------------------------------------------===//
1643
// cl::alias class implementation
1644
//
1645
1646
// Return the width of the option tag for printing...
1647
137
size_t alias::getOptionWidth() const {
1648
137
  return argPlusPrefixesSize(ArgStr);
1649
137
}
1650
1651
void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1652
2.14k
                          size_t FirstLineIndentedBy) {
1653
2.14k
  assert(Indent >= FirstLineIndentedBy);
1654
2.14k
  std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1655
2.14k
  outs().indent(Indent - FirstLineIndentedBy)
1656
2.14k
      << ArgHelpPrefix << Split.first << "\n";
1657
2.16k
  while (!Split.second.empty()) {
1658
20
    Split = Split.second.split('\n');
1659
20
    outs().indent(Indent) << Split.first << "\n";
1660
20
  }
1661
2.14k
}
1662
1663
// Print out the option for the alias.
1664
137
void alias::printOptionInfo(size_t GlobalWidth) const {
1665
137
  outs() << PrintArg(ArgStr);
1666
137
  printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1667
137
}
1668
1669
//===----------------------------------------------------------------------===//
1670
// Parser Implementation code...
1671
//
1672
1673
// basic_parser implementation
1674
//
1675
1676
// Return the width of the option tag for printing...
1677
3.73k
size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1678
3.73k
  size_t Len = argPlusPrefixesSize(O.ArgStr);
1679
3.73k
  auto ValName = getValueName();
1680
3.73k
  if (!ValName.empty()) {
1681
1.12k
    size_t FormattingLen = 3;
1682
1.12k
    if (O.getMiscFlags() & PositionalEatsArgs)
1683
0
      FormattingLen = 6;
1684
1.12k
    Len += getValueStr(O, ValName).size() + FormattingLen;
1685
1.12k
  }
1686
3.73k
1687
3.73k
  return Len;
1688
3.73k
}
1689
1690
// printOptionInfo - Print out information about this option.  The
1691
// to-be-maintained width is specified.
1692
//
1693
void basic_parser_impl::printOptionInfo(const Option &O,
1694
1.81k
                                        size_t GlobalWidth) const {
1695
1.81k
  outs() << PrintArg(O.ArgStr);
1696
1.81k
1697
1.81k
  auto ValName = getValueName();
1698
1.81k
  if (!ValName.empty()) {
1699
507
    if (O.getMiscFlags() & PositionalEatsArgs) {
1700
0
      outs() << " <" << getValueStr(O, ValName) << ">...";
1701
507
    } else {
1702
507
      outs() << "=<" << getValueStr(O, ValName) << '>';
1703
507
    }
1704
507
  }
1705
1.81k
1706
1.81k
  Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1707
1.81k
}
1708
1709
void basic_parser_impl::printOptionName(const Option &O,
1710
0
                                        size_t GlobalWidth) const {
1711
0
  outs() << PrintArg(O.ArgStr);
1712
0
  outs().indent(GlobalWidth - O.ArgStr.size());
1713
0
}
1714
1715
// parser<bool> implementation
1716
//
1717
bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1718
43.6k
                         bool &Value) {
1719
43.6k
  if (Arg == "" || 
Arg == "true"3.03k
||
Arg == "TRUE"2.37k
||
Arg == "True"2.37k
||
1720
43.6k
      
Arg == "1"2.37k
) {
1721
41.5k
    Value = true;
1722
41.5k
    return false;
1723
41.5k
  }
1724
2.09k
1725
2.09k
  if (Arg == "false" || 
Arg == "FALSE"597
||
Arg == "False"597
||
Arg == "0"597
) {
1726
2.09k
    Value = false;
1727
2.09k
    return false;
1728
2.09k
  }
1729
0
  return O.error("'" + Arg +
1730
0
                 "' is invalid value for boolean argument! Try 0 or 1");
1731
0
}
1732
1733
// parser<boolOrDefault> implementation
1734
//
1735
bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1736
14.2k
                                  boolOrDefault &Value) {
1737
14.2k
  if (Arg == "" || 
Arg == "true"219
||
Arg == "TRUE"159
||
Arg == "True"159
||
1738
14.2k
      
Arg == "1"159
) {
1739
14.0k
    Value = BOU_TRUE;
1740
14.0k
    return false;
1741
14.0k
  }
1742
153
  if (Arg == "false" || 
Arg == "FALSE"76
||
Arg == "False"76
||
Arg == "0"76
) {
1743
153
    Value = BOU_FALSE;
1744
153
    return false;
1745
153
  }
1746
0
1747
0
  return O.error("'" + Arg +
1748
0
                 "' is invalid value for boolean argument! Try 0 or 1");
1749
0
}
1750
1751
// parser<int> implementation
1752
//
1753
bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1754
997
                        int &Value) {
1755
997
  if (Arg.getAsInteger(0, Value))
1756
0
    return O.error("'" + Arg + "' value invalid for integer argument!");
1757
997
  return false;
1758
997
}
1759
1760
// parser<unsigned> implementation
1761
//
1762
bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1763
3.51k
                             unsigned &Value) {
1764
3.51k
1765
3.51k
  if (Arg.getAsInteger(0, Value))
1766
0
    return O.error("'" + Arg + "' value invalid for uint argument!");
1767
3.51k
  return false;
1768
3.51k
}
1769
1770
// parser<unsigned long> implementation
1771
//
1772
bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1773
2
                                  unsigned long &Value) {
1774
2
1775
2
  if (Arg.getAsInteger(0, Value))
1776
0
    return O.error("'" + Arg + "' value invalid for ulong argument!");
1777
2
  return false;
1778
2
}
1779
1780
// parser<unsigned long long> implementation
1781
//
1782
bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1783
                                       StringRef Arg,
1784
224
                                       unsigned long long &Value) {
1785
224
1786
224
  if (Arg.getAsInteger(0, Value))
1787
1
    return O.error("'" + Arg + "' value invalid for ullong argument!");
1788
223
  return false;
1789
223
}
1790
1791
// parser<double>/parser<float> implementation
1792
//
1793
16
static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1794
16
  if (to_float(Arg, Value))
1795
16
    return false;
1796
0
  return O.error("'" + Arg + "' value invalid for floating point argument!");
1797
0
}
1798
1799
bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1800
0
                           double &Val) {
1801
0
  return parseDouble(O, Arg, Val);
1802
0
}
1803
1804
bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1805
16
                          float &Val) {
1806
16
  double dVal;
1807
16
  if (parseDouble(O, Arg, dVal))
1808
0
    return true;
1809
16
  Val = (float)dVal;
1810
16
  return false;
1811
16
}
1812
1813
// generic_parser_base implementation
1814
//
1815
1816
// findOption - Return the option number corresponding to the specified
1817
// argument string.  If the option is not found, getNumOptions() is returned.
1818
//
1819
71.7M
unsigned generic_parser_base::findOption(StringRef Name) {
1820
71.7M
  unsigned e = getNumOptions();
1821
71.7M
1822
13.0G
  for (unsigned i = 0; i != e; 
++i12.9G
) {
1823
12.9G
    if (getOption(i) == Name)
1824
619k
      return i;
1825
12.9G
  }
1826
71.7M
  
return e71.1M
;
1827
71.7M
}
1828
1829
static StringRef EqValue = "=<value>";
1830
static StringRef EmptyOption = "<empty>";
1831
static StringRef OptionPrefix = "    =";
1832
static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1833
1834
static bool shouldPrintOption(StringRef Name, StringRef Description,
1835
2.10k
                              const Option &O) {
1836
2.10k
  return O.getValueExpectedFlag() != ValueOptional || 
!Name.empty()55
||
1837
2.10k
         
!Description.empty()15
;
1838
2.10k
}
1839
1840
// Return the width of the option tag for printing...
1841
91
size_t generic_parser_base::getOptionWidth(const Option &O) const {
1842
91
  if (O.hasArgStr()) {
1843
84
    size_t Size =
1844
84
        argPlusPrefixesSize(O.ArgStr) + EqValue.size();
1845
1.14k
    for (unsigned i = 0, e = getNumOptions(); i != e; 
++i1.05k
) {
1846
1.05k
      StringRef Name = getOption(i);
1847
1.05k
      if (!shouldPrintOption(Name, getDescription(i), O))
1848
7
        continue;
1849
1.04k
      size_t NameSize = Name.empty() ? 
EmptyOption.size()2
:
Name.size()1.04k
;
1850
1.04k
      Size = std::max(Size, NameSize + OptionPrefixesSize);
1851
1.04k
    }
1852
84
    return Size;
1853
84
  } else {
1854
7
    size_t BaseSize = 0;
1855
55
    for (unsigned i = 0, e = getNumOptions(); i != e; 
++i48
)
1856
48
      BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1857
7
    return BaseSize;
1858
7
  }
1859
91
}
1860
1861
// printOptionInfo - Print out information about this option.  The
1862
// to-be-maintained width is specified.
1863
//
1864
void generic_parser_base::printOptionInfo(const Option &O,
1865
90
                                          size_t GlobalWidth) const {
1866
90
  if (O.hasArgStr()) {
1867
83
    // When the value is optional, first print a line just describing the
1868
83
    // option without values.
1869
83
    if (O.getValueExpectedFlag() == ValueOptional) {
1870
30
      for (unsigned i = 0, e = getNumOptions(); i != e; 
++i21
) {
1871
29
        if (getOption(i).empty()) {
1872
8
          outs() << PrintArg(O.ArgStr);
1873
8
          Option::printHelpStr(O.HelpStr, GlobalWidth,
1874
8
                               argPlusPrefixesSize(O.ArgStr));
1875
8
          break;
1876
8
        }
1877
29
      }
1878
9
    }
1879
83
1880
83
    outs() << PrintArg(O.ArgStr) << EqValue;
1881
83
    Option::printHelpStr(O.HelpStr, GlobalWidth,
1882
83
                         EqValue.size() +
1883
83
                             argPlusPrefixesSize(O.ArgStr));
1884
1.13k
    for (unsigned i = 0, e = getNumOptions(); i != e; 
++i1.05k
) {
1885
1.05k
      StringRef OptionName = getOption(i);
1886
1.05k
      StringRef Description = getDescription(i);
1887
1.05k
      if (!shouldPrintOption(OptionName, Description, O))
1888
7
        continue;
1889
1.04k
      assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize);
1890
1.04k
      size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize;
1891
1.04k
      outs() << OptionPrefix << OptionName;
1892
1.04k
      if (OptionName.empty()) {
1893
2
        outs() << EmptyOption;
1894
2
        assert(NumSpaces >= EmptyOption.size());
1895
2
        NumSpaces -= EmptyOption.size();
1896
2
      }
1897
1.04k
      if (!Description.empty())
1898
1.04k
        outs().indent(NumSpaces) << ArgHelpPrefix << "  " << Description;
1899
1.04k
      outs() << '\n';
1900
1.04k
    }
1901
83
  } else {
1902
7
    if (!O.HelpStr.empty())
1903
7
      outs() << "  " << O.HelpStr << '\n';
1904
55
    for (unsigned i = 0, e = getNumOptions(); i != e; 
++i48
) {
1905
48
      StringRef Option = getOption(i);
1906
48
      outs() << "    " << PrintArg(Option);
1907
48
      Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1908
48
    }
1909
7
  }
1910
90
}
1911
1912
static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1913
1914
// printGenericOptionDiff - Print the value of this option and it's default.
1915
//
1916
// "Generic" options have each value mapped to a name.
1917
void generic_parser_base::printGenericOptionDiff(
1918
    const Option &O, const GenericOptionValue &Value,
1919
0
    const GenericOptionValue &Default, size_t GlobalWidth) const {
1920
0
  outs() << "  " << PrintArg(O.ArgStr);
1921
0
  outs().indent(GlobalWidth - O.ArgStr.size());
1922
0
1923
0
  unsigned NumOpts = getNumOptions();
1924
0
  for (unsigned i = 0; i != NumOpts; ++i) {
1925
0
    if (Value.compare(getOptionValue(i)))
1926
0
      continue;
1927
0
1928
0
    outs() << "= " << getOption(i);
1929
0
    size_t L = getOption(i).size();
1930
0
    size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1931
0
    outs().indent(NumSpaces) << " (default: ";
1932
0
    for (unsigned j = 0; j != NumOpts; ++j) {
1933
0
      if (Default.compare(getOptionValue(j)))
1934
0
        continue;
1935
0
      outs() << getOption(j);
1936
0
      break;
1937
0
    }
1938
0
    outs() << ")\n";
1939
0
    return;
1940
0
  }
1941
0
  outs() << "= *unknown option value*\n";
1942
0
}
1943
1944
// printOptionDiff - Specializations for printing basic value types.
1945
//
1946
#define PRINT_OPT_DIFF(T)                                                      \
1947
  void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1948
0
                                  size_t GlobalWidth) const {                  \
1949
0
    printOptionName(O, GlobalWidth);                                           \
1950
0
    std::string Str;                                                           \
1951
0
    {                                                                          \
1952
0
      raw_string_ostream SS(Str);                                              \
1953
0
      SS << V;                                                                 \
1954
0
    }                                                                          \
1955
0
    outs() << "= " << Str;                                                     \
1956
0
    size_t NumSpaces =                                                         \
1957
0
        MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1958
0
    outs().indent(NumSpaces) << " (default: ";                                 \
1959
0
    if (D.hasValue())                                                          \
1960
0
      outs() << D.getValue();                                                  \
1961
0
    else                                                                       \
1962
0
      outs() << "*no default*";                                                \
1963
0
    outs() << ")\n";                                                           \
1964
0
  }
Unexecuted instantiation: llvm::cl::parser<bool>::printOptionDiff(llvm::cl::Option const&, bool, llvm::cl::OptionValue<bool>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<llvm::cl::boolOrDefault>::printOptionDiff(llvm::cl::Option const&, llvm::cl::boolOrDefault, llvm::cl::OptionValue<llvm::cl::boolOrDefault>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<int>::printOptionDiff(llvm::cl::Option const&, int, llvm::cl::OptionValue<int>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<unsigned int>::printOptionDiff(llvm::cl::Option const&, unsigned int, llvm::cl::OptionValue<unsigned int>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<unsigned long>::printOptionDiff(llvm::cl::Option const&, unsigned long, llvm::cl::OptionValue<unsigned long>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<unsigned long long>::printOptionDiff(llvm::cl::Option const&, unsigned long long, llvm::cl::OptionValue<unsigned long long>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<double>::printOptionDiff(llvm::cl::Option const&, double, llvm::cl::OptionValue<double>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<float>::printOptionDiff(llvm::cl::Option const&, float, llvm::cl::OptionValue<float>, unsigned long) const
Unexecuted instantiation: llvm::cl::parser<char>::printOptionDiff(llvm::cl::Option const&, char, llvm::cl::OptionValue<char>, unsigned long) const
1965
1966
PRINT_OPT_DIFF(bool)
1967
PRINT_OPT_DIFF(boolOrDefault)
1968
PRINT_OPT_DIFF(int)
1969
PRINT_OPT_DIFF(unsigned)
1970
PRINT_OPT_DIFF(unsigned long)
1971
PRINT_OPT_DIFF(unsigned long long)
1972
PRINT_OPT_DIFF(double)
1973
PRINT_OPT_DIFF(float)
1974
PRINT_OPT_DIFF(char)
1975
1976
void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1977
                                          const OptionValue<std::string> &D,
1978
0
                                          size_t GlobalWidth) const {
1979
0
  printOptionName(O, GlobalWidth);
1980
0
  outs() << "= " << V;
1981
0
  size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1982
0
  outs().indent(NumSpaces) << " (default: ";
1983
0
  if (D.hasValue())
1984
0
    outs() << D.getValue();
1985
0
  else
1986
0
    outs() << "*no default*";
1987
0
  outs() << ")\n";
1988
0
}
1989
1990
// Print a placeholder for options that don't yet support printOptionDiff().
1991
void basic_parser_impl::printOptionNoValue(const Option &O,
1992
0
                                           size_t GlobalWidth) const {
1993
0
  printOptionName(O, GlobalWidth);
1994
0
  outs() << "= *cannot print option value*\n";
1995
0
}
1996
1997
//===----------------------------------------------------------------------===//
1998
// -help and -help-hidden option implementation
1999
//
2000
2001
static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2002
16.8k
                          const std::pair<const char *, Option *> *RHS) {
2003
16.8k
  return strcmp(LHS->first, RHS->first);
2004
16.8k
}
2005
2006
static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2007
15
                          const std::pair<const char *, SubCommand *> *RHS) {
2008
15
  return strcmp(LHS->first, RHS->first);
2009
15
}
2010
2011
// Copy Options into a vector so we can sort them as we like.
2012
static void sortOpts(StringMap<Option *> &OptMap,
2013
                     SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2014
28
                     bool ShowHidden) {
2015
28
  SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2016
28
2017
28
  for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2018
4.48k
       I != E; 
++I4.45k
) {
2019
4.45k
    // Ignore really-hidden options.
2020
4.45k
    if (I->second->getOptionHiddenFlag() == ReallyHidden)
2021
1.89k
      continue;
2022
2.55k
2023
2.55k
    // Unless showhidden is set, ignore hidden flags.
2024
2.55k
    if (I->second->getOptionHiddenFlag() == Hidden && 
!ShowHidden1.59k
)
2025
429
      continue;
2026
2.12k
2027
2.12k
    // If we've already seen this option, don't add it to the list again.
2028
2.12k
    if (!OptionSet.insert(I->second).second)
2029
41
      continue;
2030
2.08k
2031
2.08k
    Opts.push_back(
2032
2.08k
        std::pair<const char *, Option *>(I->getKey().data(), I->second));
2033
2.08k
  }
2034
28
2035
28
  // Sort the options list alphabetically.
2036
28
  array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2037
28
}
2038
2039
static void
2040
sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2041
28
                SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2042
63
  for (const auto &S : SubMap) {
2043
63
    if (S->getName().empty())
2044
56
      continue;
2045
7
    Subs.push_back(std::make_pair(S->getName().data(), S));
2046
7
  }
2047
28
  array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2048
28
}
2049
2050
namespace {
2051
2052
class HelpPrinter {
2053
protected:
2054
  const bool ShowHidden;
2055
  typedef SmallVector<std::pair<const char *, Option *>, 128>
2056
      StrOptionPairVector;
2057
  typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
2058
      StrSubCommandPairVector;
2059
  // Print the options. Opts is assumed to be alphabetically sorted.
2060
0
  virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2061
0
    for (size_t i = 0, e = Opts.size(); i != e; ++i)
2062
0
      Opts[i].second->printOptionInfo(MaxArgLen);
2063
0
  }
2064
2065
1
  void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2066
7
    for (const auto &S : Subs) {
2067
7
      outs() << "  " << S.first;
2068
7
      if (!S.second->getDescription().empty()) {
2069
7
        outs().indent(MaxSubLen - strlen(S.first));
2070
7
        outs() << " - " << S.second->getDescription();
2071
7
      }
2072
7
      outs() << "\n";
2073
7
    }
2074
1
  }
2075
2076
public:
2077
558k
  explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2078
558k
  virtual ~HelpPrinter() {}
2079
2080
  // Invoke the printer.
2081
27
  void operator=(bool Value) {
2082
27
    if (!Value)
2083
0
      return;
2084
27
    printHelp();
2085
27
2086
27
    // Halt the program since help information was printed
2087
27
    exit(0);
2088
27
  }
2089
2090
28
  void printHelp() {
2091
28
    SubCommand *Sub = GlobalParser->getActiveSubCommand();
2092
28
    auto &OptionsMap = Sub->OptionsMap;
2093
28
    auto &PositionalOpts = Sub->PositionalOpts;
2094
28
    auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2095
28
2096
28
    StrOptionPairVector Opts;
2097
28
    sortOpts(OptionsMap, Opts, ShowHidden);
2098
28
2099
28
    StrSubCommandPairVector Subs;
2100
28
    sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2101
28
2102
28
    if (!GlobalParser->ProgramOverview.empty())
2103
27
      outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2104
28
2105
28
    if (Sub == &*TopLevelSubCommand) {
2106
28
      outs() << "USAGE: " << GlobalParser->ProgramName;
2107
28
      if (Subs.size() > 2)
2108
1
        outs() << " [subcommand]";
2109
28
      outs() << " [options]";
2110
28
    } else {
2111
0
      if (!Sub->getDescription().empty()) {
2112
0
        outs() << "SUBCOMMAND '" << Sub->getName()
2113
0
               << "': " << Sub->getDescription() << "\n\n";
2114
0
      }
2115
0
      outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2116
0
             << " [options]";
2117
0
    }
2118
28
2119
28
    for (auto Opt : PositionalOpts) {
2120
26
      if (Opt->hasArgStr())
2121
0
        outs() << " --" << Opt->ArgStr;
2122
26
      outs() << " " << Opt->HelpStr;
2123
26
    }
2124
28
2125
28
    // Print the consume after option info if it exists...
2126
28
    if (ConsumeAfterOpt)
2127
0
      outs() << " " << ConsumeAfterOpt->HelpStr;
2128
28
2129
28
    if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
2130
1
      // Compute the maximum subcommand length...
2131
1
      size_t MaxSubLen = 0;
2132
8
      for (size_t i = 0, e = Subs.size(); i != e; 
++i7
)
2133
7
        MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2134
1
2135
1
      outs() << "\n\n";
2136
1
      outs() << "SUBCOMMANDS:\n\n";
2137
1
      printSubCommands(Subs, MaxSubLen);
2138
1
      outs() << "\n";
2139
1
      outs() << "  Type \"" << GlobalParser->ProgramName
2140
1
             << " <subcommand> --help\" to get more help on a specific "
2141
1
                "subcommand";
2142
1
    }
2143
28
2144
28
    outs() << "\n\n";
2145
28
2146
28
    // Compute the maximum argument length...
2147
28
    size_t MaxArgLen = 0;
2148
2.11k
    for (size_t i = 0, e = Opts.size(); i != e; 
++i2.08k
)
2149
2.08k
      MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2150
28
2151
28
    outs() << "OPTIONS:\n";
2152
28
    printOptions(Opts, MaxArgLen);
2153
28
2154
28
    // Print any extra help the user has declared.
2155
28
    for (auto I : GlobalParser->MoreHelp)
2156
19
      outs() << I;
2157
28
    GlobalParser->MoreHelp.clear();
2158
28
  }
2159
};
2160
2161
class CategorizedHelpPrinter : public HelpPrinter {
2162
public:
2163
279k
  explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2164
2165
  // Helper function for printOptions().
2166
  // It shall return a negative value if A's name should be lexicographically
2167
  // ordered before B's name. It returns a value greater than zero if B's name
2168
  // should be ordered before A's name, and it returns 0 otherwise.
2169
  static int OptionCategoryCompare(OptionCategory *const *A,
2170
160
                                   OptionCategory *const *B) {
2171
160
    return (*A)->getName().compare((*B)->getName());
2172
160
  }
2173
2174
  // Make sure we inherit our base class's operator=()
2175
  using HelpPrinter::operator=;
2176
2177
protected:
2178
28
  void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2179
28
    std::vector<OptionCategory *> SortedCategories;
2180
28
    std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2181
28
2182
28
    // Collect registered option categories into vector in preparation for
2183
28
    // sorting.
2184
28
    for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
2185
28
              E = GlobalParser->RegisteredOptionCategories.end();
2186
133
         I != E; 
++I105
) {
2187
105
      SortedCategories.push_back(*I);
2188
105
    }
2189
28
2190
28
    // Sort the different option categories alphabetically.
2191
28
    assert(SortedCategories.size() > 0 && "No option categories registered!");
2192
28
    array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2193
28
                   OptionCategoryCompare);
2194
28
2195
28
    // Create map to empty vectors.
2196
28
    for (std::vector<OptionCategory *>::const_iterator
2197
28
             I = SortedCategories.begin(),
2198
28
             E = SortedCategories.end();
2199
133
         I != E; 
++I105
)
2200
105
      CategorizedOptions[*I] = std::vector<Option *>();
2201
28
2202
28
    // Walk through pre-sorted options and assign into categories.
2203
28
    // Because the options are already alphabetically sorted the
2204
28
    // options within categories will also be alphabetically sorted.
2205
2.11k
    for (size_t I = 0, E = Opts.size(); I != E; 
++I2.08k
) {
2206
2.08k
      Option *Opt = Opts[I].second;
2207
2.08k
      for (auto &Cat : Opt->Categories) {
2208
2.08k
        assert(CategorizedOptions.count(Cat) > 0 &&
2209
2.08k
               "Option has an unregistered category");
2210
2.08k
        CategorizedOptions[Cat].push_back(Opt);
2211
2.08k
      }
2212
2.08k
    }
2213
28
2214
28
    // Now do printing.
2215
28
    for (std::vector<OptionCategory *>::const_iterator
2216
28
             Category = SortedCategories.begin(),
2217
28
             E = SortedCategories.end();
2218
133
         Category != E; 
++Category105
) {
2219
105
      // Hide empty categories for --help, but show for --help-hidden.
2220
105
      const auto &CategoryOptions = CategorizedOptions[*Category];
2221
105
      bool IsEmptyCategory = CategoryOptions.empty();
2222
105
      if (!ShowHidden && 
IsEmptyCategory80
)
2223
21
        continue;
2224
84
2225
84
      // Print category information.
2226
84
      outs() << "\n";
2227
84
      outs() << (*Category)->getName() << ":\n";
2228
84
2229
84
      // Check if description is set.
2230
84
      if (!(*Category)->getDescription().empty())
2231
2
        outs() << (*Category)->getDescription() << "\n\n";
2232
82
      else
2233
82
        outs() << "\n";
2234
84
2235
84
      // When using --help-hidden explicitly state if the category has no
2236
84
      // options associated with it.
2237
84
      if (IsEmptyCategory) {
2238
4
        outs() << "  This option category has no options.\n";
2239
4
        continue;
2240
4
      }
2241
80
      // Loop over the options in the category and print.
2242
80
      for (const Option *Opt : CategoryOptions)
2243
2.08k
        Opt->printOptionInfo(MaxArgLen);
2244
80
    }
2245
28
  }
2246
};
2247
2248
// This wraps the Uncategorizing and Categorizing printers and decides
2249
// at run time which should be invoked.
2250
class HelpPrinterWrapper {
2251
private:
2252
  HelpPrinter &UncategorizedPrinter;
2253
  CategorizedHelpPrinter &CategorizedPrinter;
2254
2255
public:
2256
  explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2257
                              CategorizedHelpPrinter &CategorizedPrinter)
2258
      : UncategorizedPrinter(UncategorizedPrinter),
2259
279k
        CategorizedPrinter(CategorizedPrinter) {}
2260
2261
  // Invoke the printer.
2262
  void operator=(bool Value);
2263
};
2264
2265
} // End anonymous namespace
2266
2267
// Declare the four HelpPrinter instances that are used to print out help, or
2268
// help-hidden as an uncategorized list or in categories.
2269
static HelpPrinter UncategorizedNormalPrinter(false);
2270
static HelpPrinter UncategorizedHiddenPrinter(true);
2271
static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2272
static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2273
2274
// Declare HelpPrinter wrappers that will decide whether or not to invoke
2275
// a categorizing help printer
2276
static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2277
                                               CategorizedNormalPrinter);
2278
static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2279
                                               CategorizedHiddenPrinter);
2280
2281
// Define a category for generic options that all tools should have.
2282
static cl::OptionCategory GenericCategory("Generic Options");
2283
2284
// Define uncategorized help printers.
2285
// --help-list is hidden by default because if Option categories are being used
2286
// then --help behaves the same as --help-list.
2287
static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2288
    "help-list",
2289
    cl::desc("Display list of available options (--help-list-hidden for more)"),
2290
    cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2291
    cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2292
2293
static cl::opt<HelpPrinter, true, parser<bool>>
2294
    HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2295
          cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2296
          cl::ValueDisallowed, cl::cat(GenericCategory),
2297
          cl::sub(*AllSubCommands));
2298
2299
// Define uncategorized/categorized help printers. These printers change their
2300
// behaviour at runtime depending on whether one or more Option categories have
2301
// been declared.
2302
static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2303
    HOp("help", cl::desc("Display available options (--help-hidden for more)"),
2304
        cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2305
        cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2306
2307
static cl::alias HOpA("h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2308
                      cl::DefaultOption);
2309
2310
static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2311
    HHOp("help-hidden", cl::desc("Display all available options"),
2312
         cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2313
         cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2314
2315
static cl::opt<bool> PrintOptions(
2316
    "print-options",
2317
    cl::desc("Print non-default options after command line parsing"),
2318
    cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2319
    cl::sub(*AllSubCommands));
2320
2321
static cl::opt<bool> PrintAllOptions(
2322
    "print-all-options",
2323
    cl::desc("Print all option values after command line parsing"), cl::Hidden,
2324
    cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2325
2326
27
void HelpPrinterWrapper::operator=(bool Value) {
2327
27
  if (!Value)
2328
0
    return;
2329
27
2330
27
  // Decide which printer to invoke. If more than one option category is
2331
27
  // registered then it is useful to show the categorized help instead of
2332
27
  // uncategorized help.
2333
27
  if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2334
27
    // unhide --help-list option so user can have uncategorized output if they
2335
27
    // want it.
2336
27
    HLOp.setHiddenFlag(NotHidden);
2337
27
2338
27
    CategorizedPrinter = true; // Invoke categorized printer
2339
27
  } else
2340
0
    UncategorizedPrinter = true; // Invoke uncategorized printer
2341
27
}
2342
2343
// Print the value of each option.
2344
57.2k
void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2345
2346
57.2k
void CommandLineParser::printOptionValues() {
2347
57.2k
  if (!PrintOptions && !PrintAllOptions)
2348
57.2k
    return;
2349
0
2350
0
  SmallVector<std::pair<const char *, Option *>, 128> Opts;
2351
0
  sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2352
0
2353
0
  // Compute the maximum argument length...
2354
0
  size_t MaxArgLen = 0;
2355
0
  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2356
0
    MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2357
0
2358
0
  for (size_t i = 0, e = Opts.size(); i != e; ++i)
2359
0
    Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2360
0
}
2361
2362
static VersionPrinterTy OverrideVersionPrinter = nullptr;
2363
2364
static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2365
2366
namespace {
2367
class VersionPrinter {
2368
public:
2369
12
  void print() {
2370
12
    raw_ostream &OS = outs();
2371
#ifdef PACKAGE_VENDOR
2372
    OS << PACKAGE_VENDOR << " ";
2373
#else
2374
    OS << "LLVM (http://llvm.org/):\n  ";
2375
12
#endif
2376
12
    OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2377
#ifdef LLVM_VERSION_INFO
2378
    OS << " " << LLVM_VERSION_INFO;
2379
#endif
2380
    OS << "\n  ";
2381
#ifndef __OPTIMIZE__
2382
    OS << "DEBUG build";
2383
#else
2384
    OS << "Optimized build";
2385
12
#endif
2386
#ifndef NDEBUG
2387
    OS << " with assertions";
2388
#endif
2389
#if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2390
12
    std::string CPU = sys::getHostCPUName();
2391
12
    if (CPU == "generic")
2392
0
      CPU = "(unknown)";
2393
12
    OS << ".\n"
2394
12
       << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
2395
12
       << "  Host CPU: " << CPU;
2396
12
#endif
2397
12
    OS << '\n';
2398
12
  }
2399
5
  void operator=(bool OptionWasSpecified) {
2400
5
    if (!OptionWasSpecified)
2401
0
      return;
2402
5
2403
5
    if (OverrideVersionPrinter != nullptr) {
2404
0
      OverrideVersionPrinter(outs());
2405
0
      exit(0);
2406
0
    }
2407
5
    print();
2408
5
2409
5
    // Iterate over any registered extra printers and call them to add further
2410
5
    // information.
2411
5
    if (ExtraVersionPrinters != nullptr) {
2412
2
      outs() << '\n';
2413
2
      for (auto I : *ExtraVersionPrinters)
2414
2
        I(outs());
2415
2
    }
2416
5
2417
5
    exit(0);
2418
5
  }
2419
};
2420
} // End anonymous namespace
2421
2422
// Define the --version option that prints out the LLVM version for the tool
2423
static VersionPrinter VersionPrinterInstance;
2424
2425
static cl::opt<VersionPrinter, true, parser<bool>>
2426
    VersOp("version", cl::desc("Display the version of this program"),
2427
           cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2428
           cl::cat(GenericCategory));
2429
2430
// Utility function for printing the help message.
2431
1
void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2432
1
  if (!Hidden && !Categorized)
2433
0
    UncategorizedNormalPrinter.printHelp();
2434
1
  else if (!Hidden && Categorized)
2435
1
    CategorizedNormalPrinter.printHelp();
2436
0
  else if (Hidden && !Categorized)
2437
0
    UncategorizedHiddenPrinter.printHelp();
2438
0
  else
2439
0
    CategorizedHiddenPrinter.printHelp();
2440
1
}
2441
2442
/// Utility function for printing version number.
2443
7
void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2444
2445
186
void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2446
2447
43.6k
void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2448
43.6k
  if (!ExtraVersionPrinters)
2449
43.6k
    ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2450
43.6k
2451
43.6k
  ExtraVersionPrinters->push_back(func);
2452
43.6k
}
2453
2454
572
StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2455
572
  auto &Subs = GlobalParser->RegisteredSubCommands;
2456
572
  (void)Subs;
2457
572
  assert(is_contained(Subs, &Sub));
2458
572
  return Sub.OptionsMap;
2459
572
}
2460
2461
iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2462
78
cl::getRegisteredSubcommands() {
2463
78
  return GlobalParser->getRegisteredSubcommands();
2464
78
}
2465
2466
2.15k
void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2467
267k
  for (auto &I : Sub.OptionsMap) {
2468
267k
    for (auto &Cat : I.second->Categories) {
2469
267k
      if (Cat != &Category &&
2470
267k
          
Cat != &GenericCategory229k
)
2471
214k
        I.second->setHiddenFlag(cl::ReallyHidden);
2472
267k
    }
2473
267k
  }
2474
2.15k
}
2475
2476
void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2477
5.18k
                              SubCommand &Sub) {
2478
781k
  for (auto &I : Sub.OptionsMap) {
2479
781k
    for (auto &Cat : I.second->Categories) {
2480
781k
      if (find(Categories, Cat) == Categories.end() && 
Cat != &GenericCategory427k
)
2481
391k
        I.second->setHiddenFlag(cl::ReallyHidden);
2482
781k
    }
2483
781k
  }
2484
5.18k
}
2485
2486
16
void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2487
170
void cl::ResetAllOptionOccurrences() {
2488
170
  GlobalParser->ResetAllOptionOccurrences();
2489
170
}
2490
2491
void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2492
0
                                 const char *Overview) {
2493
0
  llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2494
0
                                    &llvm::nulls());
2495
0
}