CommandLine.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. //===-- CommandLine.cpp - Command line parser implementation --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This class implements a command line argument processor that is useful when
  11. // creating a tool. It provides a simple, minimalistic interface that is easily
  12. // extensible and supports nonlocal (library) command line options.
  13. //
  14. // Note that rather than trying to figure out what this code does, you could try
  15. // reading the library documentation located in docs/CommandLine.html
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Support/CommandLine.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/ErrorHandling.h"
  21. #include "llvm/Support/MemoryBuffer.h"
  22. #include "llvm/Support/ManagedStatic.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/Support/system_error.h"
  25. #include "llvm/Support/Host.h"
  26. #include "llvm/Support/Path.h"
  27. #include "llvm/ADT/OwningPtr.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/ADT/SmallString.h"
  30. #include "llvm/ADT/StringMap.h"
  31. #include "llvm/ADT/Twine.h"
  32. #include "llvm/Config/config.h"
  33. #include <cerrno>
  34. #include <cstdlib>
  35. using namespace llvm;
  36. using namespace cl;
  37. //===----------------------------------------------------------------------===//
  38. // Template instantiations and anchors.
  39. //
  40. namespace llvm { namespace cl {
  41. TEMPLATE_INSTANTIATION(class basic_parser<bool>);
  42. TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
  43. TEMPLATE_INSTANTIATION(class basic_parser<int>);
  44. TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
  45. TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
  46. TEMPLATE_INSTANTIATION(class basic_parser<double>);
  47. TEMPLATE_INSTANTIATION(class basic_parser<float>);
  48. TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
  49. TEMPLATE_INSTANTIATION(class basic_parser<char>);
  50. TEMPLATE_INSTANTIATION(class opt<unsigned>);
  51. TEMPLATE_INSTANTIATION(class opt<int>);
  52. TEMPLATE_INSTANTIATION(class opt<std::string>);
  53. TEMPLATE_INSTANTIATION(class opt<char>);
  54. TEMPLATE_INSTANTIATION(class opt<bool>);
  55. } } // end namespace llvm::cl
  56. void GenericOptionValue::anchor() {}
  57. void OptionValue<boolOrDefault>::anchor() {}
  58. void OptionValue<std::string>::anchor() {}
  59. void Option::anchor() {}
  60. void basic_parser_impl::anchor() {}
  61. void parser<bool>::anchor() {}
  62. void parser<boolOrDefault>::anchor() {}
  63. void parser<int>::anchor() {}
  64. void parser<unsigned>::anchor() {}
  65. void parser<unsigned long long>::anchor() {}
  66. void parser<double>::anchor() {}
  67. void parser<float>::anchor() {}
  68. void parser<std::string>::anchor() {}
  69. void parser<char>::anchor() {}
  70. //===----------------------------------------------------------------------===//
  71. // Globals for name and overview of program. Program name is not a string to
  72. // avoid static ctor/dtor issues.
  73. static char ProgramName[80] = "<premain>";
  74. static const char *ProgramOverview = 0;
  75. // This collects additional help to be printed.
  76. static ManagedStatic<std::vector<const char*> > MoreHelp;
  77. extrahelp::extrahelp(const char *Help)
  78. : morehelp(Help) {
  79. MoreHelp->push_back(Help);
  80. }
  81. static bool OptionListChanged = false;
  82. // MarkOptionsChanged - Internal helper function.
  83. void cl::MarkOptionsChanged() {
  84. OptionListChanged = true;
  85. }
  86. /// RegisteredOptionList - This is the list of the command line options that
  87. /// have statically constructed themselves.
  88. static Option *RegisteredOptionList = 0;
  89. void Option::addArgument() {
  90. assert(NextRegistered == 0 && "argument multiply registered!");
  91. NextRegistered = RegisteredOptionList;
  92. RegisteredOptionList = this;
  93. MarkOptionsChanged();
  94. }
  95. //===----------------------------------------------------------------------===//
  96. // Basic, shared command line option processing machinery.
  97. //
  98. /// GetOptionInfo - Scan the list of registered options, turning them into data
  99. /// structures that are easier to handle.
  100. static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
  101. SmallVectorImpl<Option*> &SinkOpts,
  102. StringMap<Option*> &OptionsMap) {
  103. SmallVector<const char*, 16> OptionNames;
  104. Option *CAOpt = 0; // The ConsumeAfter option if it exists.
  105. for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
  106. // If this option wants to handle multiple option names, get the full set.
  107. // This handles enum options like "-O1 -O2" etc.
  108. O->getExtraOptionNames(OptionNames);
  109. if (O->ArgStr[0])
  110. OptionNames.push_back(O->ArgStr);
  111. // Handle named options.
  112. for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
  113. // Add argument to the argument map!
  114. if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
  115. errs() << ProgramName << ": CommandLine Error: Argument '"
  116. << OptionNames[i] << "' defined more than once!\n";
  117. }
  118. }
  119. OptionNames.clear();
  120. // Remember information about positional options.
  121. if (O->getFormattingFlag() == cl::Positional)
  122. PositionalOpts.push_back(O);
  123. else if (O->getMiscFlags() & cl::Sink) // Remember sink options
  124. SinkOpts.push_back(O);
  125. else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
  126. if (CAOpt)
  127. O->error("Cannot specify more than one option with cl::ConsumeAfter!");
  128. CAOpt = O;
  129. }
  130. }
  131. if (CAOpt)
  132. PositionalOpts.push_back(CAOpt);
  133. // Make sure that they are in order of registration not backwards.
  134. std::reverse(PositionalOpts.begin(), PositionalOpts.end());
  135. }
  136. /// LookupOption - Lookup the option specified by the specified option on the
  137. /// command line. If there is a value specified (after an equal sign) return
  138. /// that as well. This assumes that leading dashes have already been stripped.
  139. static Option *LookupOption(StringRef &Arg, StringRef &Value,
  140. const StringMap<Option*> &OptionsMap) {
  141. // Reject all dashes.
  142. if (Arg.empty()) return 0;
  143. size_t EqualPos = Arg.find('=');
  144. // If we have an equals sign, remember the value.
  145. if (EqualPos == StringRef::npos) {
  146. // Look up the option.
  147. StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
  148. return I != OptionsMap.end() ? I->second : 0;
  149. }
  150. // If the argument before the = is a valid option name, we match. If not,
  151. // return Arg unmolested.
  152. StringMap<Option*>::const_iterator I =
  153. OptionsMap.find(Arg.substr(0, EqualPos));
  154. if (I == OptionsMap.end()) return 0;
  155. Value = Arg.substr(EqualPos+1);
  156. Arg = Arg.substr(0, EqualPos);
  157. return I->second;
  158. }
  159. /// LookupNearestOption - Lookup the closest match to the option specified by
  160. /// the specified option on the command line. If there is a value specified
  161. /// (after an equal sign) return that as well. This assumes that leading dashes
  162. /// have already been stripped.
  163. static Option *LookupNearestOption(StringRef Arg,
  164. const StringMap<Option*> &OptionsMap,
  165. std::string &NearestString) {
  166. // Reject all dashes.
  167. if (Arg.empty()) return 0;
  168. // Split on any equal sign.
  169. std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
  170. StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
  171. StringRef &RHS = SplitArg.second;
  172. // Find the closest match.
  173. Option *Best = 0;
  174. unsigned BestDistance = 0;
  175. for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
  176. ie = OptionsMap.end(); it != ie; ++it) {
  177. Option *O = it->second;
  178. SmallVector<const char*, 16> OptionNames;
  179. O->getExtraOptionNames(OptionNames);
  180. if (O->ArgStr[0])
  181. OptionNames.push_back(O->ArgStr);
  182. bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
  183. StringRef Flag = PermitValue ? LHS : Arg;
  184. for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
  185. StringRef Name = OptionNames[i];
  186. unsigned Distance = StringRef(Name).edit_distance(
  187. Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
  188. if (!Best || Distance < BestDistance) {
  189. Best = O;
  190. BestDistance = Distance;
  191. if (RHS.empty() || !PermitValue)
  192. NearestString = OptionNames[i];
  193. else
  194. NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
  195. }
  196. }
  197. }
  198. return Best;
  199. }
  200. /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
  201. /// does special handling of cl::CommaSeparated options.
  202. static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
  203. StringRef ArgName,
  204. StringRef Value, bool MultiArg = false)
  205. {
  206. // Check to see if this option accepts a comma separated list of values. If
  207. // it does, we have to split up the value into multiple values.
  208. if (Handler->getMiscFlags() & CommaSeparated) {
  209. StringRef Val(Value);
  210. StringRef::size_type Pos = Val.find(',');
  211. while (Pos != StringRef::npos) {
  212. // Process the portion before the comma.
  213. if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
  214. return true;
  215. // Erase the portion before the comma, AND the comma.
  216. Val = Val.substr(Pos+1);
  217. Value.substr(Pos+1); // Increment the original value pointer as well.
  218. // Check for another comma.
  219. Pos = Val.find(',');
  220. }
  221. Value = Val;
  222. }
  223. if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
  224. return true;
  225. return false;
  226. }
  227. /// ProvideOption - For Value, this differentiates between an empty value ("")
  228. /// and a null value (StringRef()). The later is accepted for arguments that
  229. /// don't allow a value (-foo) the former is rejected (-foo=).
  230. static inline bool ProvideOption(Option *Handler, StringRef ArgName,
  231. StringRef Value, int argc,
  232. const char *const *argv, int &i) {
  233. // Is this a multi-argument option?
  234. unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
  235. // Enforce value requirements
  236. switch (Handler->getValueExpectedFlag()) {
  237. case ValueRequired:
  238. if (Value.data() == 0) { // No value specified?
  239. if (i+1 >= argc)
  240. return Handler->error("requires a value!");
  241. // Steal the next argument, like for '-o filename'
  242. Value = argv[++i];
  243. }
  244. break;
  245. case ValueDisallowed:
  246. if (NumAdditionalVals > 0)
  247. return Handler->error("multi-valued option specified"
  248. " with ValueDisallowed modifier!");
  249. if (Value.data())
  250. return Handler->error("does not allow a value! '" +
  251. Twine(Value) + "' specified.");
  252. break;
  253. case ValueOptional:
  254. break;
  255. }
  256. // If this isn't a multi-arg option, just run the handler.
  257. if (NumAdditionalVals == 0)
  258. return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
  259. // If it is, run the handle several times.
  260. bool MultiArg = false;
  261. if (Value.data()) {
  262. if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
  263. return true;
  264. --NumAdditionalVals;
  265. MultiArg = true;
  266. }
  267. while (NumAdditionalVals > 0) {
  268. if (i+1 >= argc)
  269. return Handler->error("not enough values!");
  270. Value = argv[++i];
  271. if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
  272. return true;
  273. MultiArg = true;
  274. --NumAdditionalVals;
  275. }
  276. return false;
  277. }
  278. static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
  279. int Dummy = i;
  280. return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
  281. }
  282. // Option predicates...
  283. static inline bool isGrouping(const Option *O) {
  284. return O->getFormattingFlag() == cl::Grouping;
  285. }
  286. static inline bool isPrefixedOrGrouping(const Option *O) {
  287. return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
  288. }
  289. // getOptionPred - Check to see if there are any options that satisfy the
  290. // specified predicate with names that are the prefixes in Name. This is
  291. // checked by progressively stripping characters off of the name, checking to
  292. // see if there options that satisfy the predicate. If we find one, return it,
  293. // otherwise return null.
  294. //
  295. static Option *getOptionPred(StringRef Name, size_t &Length,
  296. bool (*Pred)(const Option*),
  297. const StringMap<Option*> &OptionsMap) {
  298. StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
  299. // Loop while we haven't found an option and Name still has at least two
  300. // characters in it (so that the next iteration will not be the empty
  301. // string.
  302. while (OMI == OptionsMap.end() && Name.size() > 1) {
  303. Name = Name.substr(0, Name.size()-1); // Chop off the last character.
  304. OMI = OptionsMap.find(Name);
  305. }
  306. if (OMI != OptionsMap.end() && Pred(OMI->second)) {
  307. Length = Name.size();
  308. return OMI->second; // Found one!
  309. }
  310. return 0; // No option found!
  311. }
  312. /// HandlePrefixedOrGroupedOption - The specified argument string (which started
  313. /// with at least one '-') does not fully match an available option. Check to
  314. /// see if this is a prefix or grouped option. If so, split arg into output an
  315. /// Arg/Value pair and return the Option to parse it with.
  316. static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
  317. bool &ErrorParsing,
  318. const StringMap<Option*> &OptionsMap) {
  319. if (Arg.size() == 1) return 0;
  320. // Do the lookup!
  321. size_t Length = 0;
  322. Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
  323. if (PGOpt == 0) return 0;
  324. // If the option is a prefixed option, then the value is simply the
  325. // rest of the name... so fall through to later processing, by
  326. // setting up the argument name flags and value fields.
  327. if (PGOpt->getFormattingFlag() == cl::Prefix) {
  328. Value = Arg.substr(Length);
  329. Arg = Arg.substr(0, Length);
  330. assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
  331. return PGOpt;
  332. }
  333. // This must be a grouped option... handle them now. Grouping options can't
  334. // have values.
  335. assert(isGrouping(PGOpt) && "Broken getOptionPred!");
  336. do {
  337. // Move current arg name out of Arg into OneArgName.
  338. StringRef OneArgName = Arg.substr(0, Length);
  339. Arg = Arg.substr(Length);
  340. // Because ValueRequired is an invalid flag for grouped arguments,
  341. // we don't need to pass argc/argv in.
  342. assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
  343. "Option can not be cl::Grouping AND cl::ValueRequired!");
  344. int Dummy = 0;
  345. ErrorParsing |= ProvideOption(PGOpt, OneArgName,
  346. StringRef(), 0, 0, Dummy);
  347. // Get the next grouping option.
  348. PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
  349. } while (PGOpt && Length != Arg.size());
  350. // Return the last option with Arg cut down to just the last one.
  351. return PGOpt;
  352. }
  353. static bool RequiresValue(const Option *O) {
  354. return O->getNumOccurrencesFlag() == cl::Required ||
  355. O->getNumOccurrencesFlag() == cl::OneOrMore;
  356. }
  357. static bool EatsUnboundedNumberOfValues(const Option *O) {
  358. return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
  359. O->getNumOccurrencesFlag() == cl::OneOrMore;
  360. }
  361. /// ParseCStringVector - Break INPUT up wherever one or more
  362. /// whitespace characters are found, and store the resulting tokens in
  363. /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
  364. /// using strdup(), so it is the caller's responsibility to free()
  365. /// them later.
  366. ///
  367. static void ParseCStringVector(std::vector<char *> &OutputVector,
  368. const char *Input) {
  369. // Characters which will be treated as token separators:
  370. StringRef Delims = " \v\f\t\r\n";
  371. StringRef WorkStr(Input);
  372. while (!WorkStr.empty()) {
  373. // If the first character is a delimiter, strip them off.
  374. if (Delims.find(WorkStr[0]) != StringRef::npos) {
  375. size_t Pos = WorkStr.find_first_not_of(Delims);
  376. if (Pos == StringRef::npos) Pos = WorkStr.size();
  377. WorkStr = WorkStr.substr(Pos);
  378. continue;
  379. }
  380. // Find position of first delimiter.
  381. size_t Pos = WorkStr.find_first_of(Delims);
  382. if (Pos == StringRef::npos) Pos = WorkStr.size();
  383. // Everything from 0 to Pos is the next word to copy.
  384. char *NewStr = (char*)malloc(Pos+1);
  385. memcpy(NewStr, WorkStr.data(), Pos);
  386. NewStr[Pos] = 0;
  387. OutputVector.push_back(NewStr);
  388. WorkStr = WorkStr.substr(Pos);
  389. }
  390. }
  391. /// ParseEnvironmentOptions - An alternative entry point to the
  392. /// CommandLine library, which allows you to read the program's name
  393. /// from the caller (as PROGNAME) and its command-line arguments from
  394. /// an environment variable (whose name is given in ENVVAR).
  395. ///
  396. void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
  397. const char *Overview, bool ReadResponseFiles) {
  398. // Check args.
  399. assert(progName && "Program name not specified");
  400. assert(envVar && "Environment variable name missing");
  401. // Get the environment variable they want us to parse options out of.
  402. const char *envValue = getenv(envVar);
  403. if (!envValue)
  404. return;
  405. // Get program's "name", which we wouldn't know without the caller
  406. // telling us.
  407. std::vector<char*> newArgv;
  408. newArgv.push_back(strdup(progName));
  409. // Parse the value of the environment variable into a "command line"
  410. // and hand it off to ParseCommandLineOptions().
  411. ParseCStringVector(newArgv, envValue);
  412. int newArgc = static_cast<int>(newArgv.size());
  413. ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
  414. // Free all the strdup()ed strings.
  415. for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
  416. i != e; ++i)
  417. free(*i);
  418. }
  419. /// ExpandResponseFiles - Copy the contents of argv into newArgv,
  420. /// substituting the contents of the response files for the arguments
  421. /// of type @file.
  422. static void ExpandResponseFiles(unsigned argc, const char*const* argv,
  423. std::vector<char*>& newArgv) {
  424. for (unsigned i = 1; i != argc; ++i) {
  425. const char *arg = argv[i];
  426. if (arg[0] == '@') {
  427. sys::PathWithStatus respFile(++arg);
  428. // Check that the response file is not empty (mmap'ing empty
  429. // files can be problematic).
  430. const sys::FileStatus *FileStat = respFile.getFileStatus();
  431. if (FileStat && FileStat->getSize() != 0) {
  432. // If we could open the file, parse its contents, otherwise
  433. // pass the @file option verbatim.
  434. // TODO: we should also support recursive loading of response files,
  435. // since this is how gcc behaves. (From their man page: "The file may
  436. // itself contain additional @file options; any such options will be
  437. // processed recursively.")
  438. // Mmap the response file into memory.
  439. OwningPtr<MemoryBuffer> respFilePtr;
  440. if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
  441. ParseCStringVector(newArgv, respFilePtr->getBufferStart());
  442. continue;
  443. }
  444. }
  445. }
  446. newArgv.push_back(strdup(arg));
  447. }
  448. }
  449. void cl::ParseCommandLineOptions(int argc, const char * const *argv,
  450. const char *Overview, bool ReadResponseFiles) {
  451. // Process all registered options.
  452. SmallVector<Option*, 4> PositionalOpts;
  453. SmallVector<Option*, 4> SinkOpts;
  454. StringMap<Option*> Opts;
  455. GetOptionInfo(PositionalOpts, SinkOpts, Opts);
  456. assert((!Opts.empty() || !PositionalOpts.empty()) &&
  457. "No options specified!");
  458. // Expand response files.
  459. std::vector<char*> newArgv;
  460. if (ReadResponseFiles) {
  461. newArgv.push_back(strdup(argv[0]));
  462. ExpandResponseFiles(argc, argv, newArgv);
  463. argv = &newArgv[0];
  464. argc = static_cast<int>(newArgv.size());
  465. }
  466. // Copy the program name into ProgName, making sure not to overflow it.
  467. std::string ProgName = sys::path::filename(argv[0]);
  468. size_t Len = std::min(ProgName.size(), size_t(79));
  469. memcpy(ProgramName, ProgName.data(), Len);
  470. ProgramName[Len] = '\0';
  471. ProgramOverview = Overview;
  472. bool ErrorParsing = false;
  473. // Check out the positional arguments to collect information about them.
  474. unsigned NumPositionalRequired = 0;
  475. // Determine whether or not there are an unlimited number of positionals
  476. bool HasUnlimitedPositionals = false;
  477. Option *ConsumeAfterOpt = 0;
  478. if (!PositionalOpts.empty()) {
  479. if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
  480. assert(PositionalOpts.size() > 1 &&
  481. "Cannot specify cl::ConsumeAfter without a positional argument!");
  482. ConsumeAfterOpt = PositionalOpts[0];
  483. }
  484. // Calculate how many positional values are _required_.
  485. bool UnboundedFound = false;
  486. for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
  487. i != e; ++i) {
  488. Option *Opt = PositionalOpts[i];
  489. if (RequiresValue(Opt))
  490. ++NumPositionalRequired;
  491. else if (ConsumeAfterOpt) {
  492. // ConsumeAfter cannot be combined with "optional" positional options
  493. // unless there is only one positional argument...
  494. if (PositionalOpts.size() > 2)
  495. ErrorParsing |=
  496. Opt->error("error - this positional option will never be matched, "
  497. "because it does not Require a value, and a "
  498. "cl::ConsumeAfter option is active!");
  499. } else if (UnboundedFound && !Opt->ArgStr[0]) {
  500. // This option does not "require" a value... Make sure this option is
  501. // not specified after an option that eats all extra arguments, or this
  502. // one will never get any!
  503. //
  504. ErrorParsing |= Opt->error("error - option can never match, because "
  505. "another positional argument will match an "
  506. "unbounded number of values, and this option"
  507. " does not require a value!");
  508. }
  509. UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
  510. }
  511. HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
  512. }
  513. // PositionalVals - A vector of "positional" arguments we accumulate into
  514. // the process at the end.
  515. //
  516. SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
  517. // If the program has named positional arguments, and the name has been run
  518. // across, keep track of which positional argument was named. Otherwise put
  519. // the positional args into the PositionalVals list...
  520. Option *ActivePositionalArg = 0;
  521. // Loop over all of the arguments... processing them.
  522. bool DashDashFound = false; // Have we read '--'?
  523. for (int i = 1; i < argc; ++i) {
  524. Option *Handler = 0;
  525. Option *NearestHandler = 0;
  526. std::string NearestHandlerString;
  527. StringRef Value;
  528. StringRef ArgName = "";
  529. // If the option list changed, this means that some command line
  530. // option has just been registered or deregistered. This can occur in
  531. // response to things like -load, etc. If this happens, rescan the options.
  532. if (OptionListChanged) {
  533. PositionalOpts.clear();
  534. SinkOpts.clear();
  535. Opts.clear();
  536. GetOptionInfo(PositionalOpts, SinkOpts, Opts);
  537. OptionListChanged = false;
  538. }
  539. // Check to see if this is a positional argument. This argument is
  540. // considered to be positional if it doesn't start with '-', if it is "-"
  541. // itself, or if we have seen "--" already.
  542. //
  543. if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
  544. // Positional argument!
  545. if (ActivePositionalArg) {
  546. ProvidePositionalOption(ActivePositionalArg, argv[i], i);
  547. continue; // We are done!
  548. }
  549. if (!PositionalOpts.empty()) {
  550. PositionalVals.push_back(std::make_pair(argv[i],i));
  551. // All of the positional arguments have been fulfulled, give the rest to
  552. // the consume after option... if it's specified...
  553. //
  554. if (PositionalVals.size() >= NumPositionalRequired &&
  555. ConsumeAfterOpt != 0) {
  556. for (++i; i < argc; ++i)
  557. PositionalVals.push_back(std::make_pair(argv[i],i));
  558. break; // Handle outside of the argument processing loop...
  559. }
  560. // Delay processing positional arguments until the end...
  561. continue;
  562. }
  563. } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
  564. !DashDashFound) {
  565. DashDashFound = true; // This is the mythical "--"?
  566. continue; // Don't try to process it as an argument itself.
  567. } else if (ActivePositionalArg &&
  568. (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
  569. // If there is a positional argument eating options, check to see if this
  570. // option is another positional argument. If so, treat it as an argument,
  571. // otherwise feed it to the eating positional.
  572. ArgName = argv[i]+1;
  573. // Eat leading dashes.
  574. while (!ArgName.empty() && ArgName[0] == '-')
  575. ArgName = ArgName.substr(1);
  576. Handler = LookupOption(ArgName, Value, Opts);
  577. if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
  578. ProvidePositionalOption(ActivePositionalArg, argv[i], i);
  579. continue; // We are done!
  580. }
  581. } else { // We start with a '-', must be an argument.
  582. ArgName = argv[i]+1;
  583. // Eat leading dashes.
  584. while (!ArgName.empty() && ArgName[0] == '-')
  585. ArgName = ArgName.substr(1);
  586. Handler = LookupOption(ArgName, Value, Opts);
  587. // Check to see if this "option" is really a prefixed or grouped argument.
  588. if (Handler == 0)
  589. Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
  590. ErrorParsing, Opts);
  591. // Otherwise, look for the closest available option to report to the user
  592. // in the upcoming error.
  593. if (Handler == 0 && SinkOpts.empty())
  594. NearestHandler = LookupNearestOption(ArgName, Opts,
  595. NearestHandlerString);
  596. }
  597. if (Handler == 0) {
  598. if (SinkOpts.empty()) {
  599. errs() << ProgramName << ": Unknown command line argument '"
  600. << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
  601. if (NearestHandler) {
  602. // If we know a near match, report it as well.
  603. errs() << ProgramName << ": Did you mean '-"
  604. << NearestHandlerString << "'?\n";
  605. }
  606. ErrorParsing = true;
  607. } else {
  608. for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
  609. E = SinkOpts.end(); I != E ; ++I)
  610. (*I)->addOccurrence(i, "", argv[i]);
  611. }
  612. continue;
  613. }
  614. // If this is a named positional argument, just remember that it is the
  615. // active one...
  616. if (Handler->getFormattingFlag() == cl::Positional)
  617. ActivePositionalArg = Handler;
  618. else
  619. ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
  620. }
  621. // Check and handle positional arguments now...
  622. if (NumPositionalRequired > PositionalVals.size()) {
  623. errs() << ProgramName
  624. << ": Not enough positional command line arguments specified!\n"
  625. << "Must specify at least " << NumPositionalRequired
  626. << " positional arguments: See: " << argv[0] << " -help\n";
  627. ErrorParsing = true;
  628. } else if (!HasUnlimitedPositionals &&
  629. PositionalVals.size() > PositionalOpts.size()) {
  630. errs() << ProgramName
  631. << ": Too many positional arguments specified!\n"
  632. << "Can specify at most " << PositionalOpts.size()
  633. << " positional arguments: See: " << argv[0] << " -help\n";
  634. ErrorParsing = true;
  635. } else if (ConsumeAfterOpt == 0) {
  636. // Positional args have already been handled if ConsumeAfter is specified.
  637. unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
  638. for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
  639. if (RequiresValue(PositionalOpts[i])) {
  640. ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
  641. PositionalVals[ValNo].second);
  642. ValNo++;
  643. --NumPositionalRequired; // We fulfilled our duty...
  644. }
  645. // If we _can_ give this option more arguments, do so now, as long as we
  646. // do not give it values that others need. 'Done' controls whether the
  647. // option even _WANTS_ any more.
  648. //
  649. bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
  650. while (NumVals-ValNo > NumPositionalRequired && !Done) {
  651. switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
  652. case cl::Optional:
  653. Done = true; // Optional arguments want _at most_ one value
  654. // FALL THROUGH
  655. case cl::ZeroOrMore: // Zero or more will take all they can get...
  656. case cl::OneOrMore: // One or more will take all they can get...
  657. ProvidePositionalOption(PositionalOpts[i],
  658. PositionalVals[ValNo].first,
  659. PositionalVals[ValNo].second);
  660. ValNo++;
  661. break;
  662. default:
  663. llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
  664. "positional argument processing!");
  665. }
  666. }
  667. }
  668. } else {
  669. assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
  670. unsigned ValNo = 0;
  671. for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
  672. if (RequiresValue(PositionalOpts[j])) {
  673. ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
  674. PositionalVals[ValNo].first,
  675. PositionalVals[ValNo].second);
  676. ValNo++;
  677. }
  678. // Handle the case where there is just one positional option, and it's
  679. // optional. In this case, we want to give JUST THE FIRST option to the
  680. // positional option and keep the rest for the consume after. The above
  681. // loop would have assigned no values to positional options in this case.
  682. //
  683. if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
  684. ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
  685. PositionalVals[ValNo].first,
  686. PositionalVals[ValNo].second);
  687. ValNo++;
  688. }
  689. // Handle over all of the rest of the arguments to the
  690. // cl::ConsumeAfter command line option...
  691. for (; ValNo != PositionalVals.size(); ++ValNo)
  692. ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
  693. PositionalVals[ValNo].first,
  694. PositionalVals[ValNo].second);
  695. }
  696. // Loop over args and make sure all required args are specified!
  697. for (StringMap<Option*>::iterator I = Opts.begin(),
  698. E = Opts.end(); I != E; ++I) {
  699. switch (I->second->getNumOccurrencesFlag()) {
  700. case Required:
  701. case OneOrMore:
  702. if (I->second->getNumOccurrences() == 0) {
  703. I->second->error("must be specified at least once!");
  704. ErrorParsing = true;
  705. }
  706. // Fall through
  707. default:
  708. break;
  709. }
  710. }
  711. // Now that we know if -debug is specified, we can use it.
  712. // Note that if ReadResponseFiles == true, this must be done before the
  713. // memory allocated for the expanded command line is free()d below.
  714. DEBUG(dbgs() << "Args: ";
  715. for (int i = 0; i < argc; ++i)
  716. dbgs() << argv[i] << ' ';
  717. dbgs() << '\n';
  718. );
  719. // Free all of the memory allocated to the map. Command line options may only
  720. // be processed once!
  721. Opts.clear();
  722. PositionalOpts.clear();
  723. MoreHelp->clear();
  724. // Free the memory allocated by ExpandResponseFiles.
  725. if (ReadResponseFiles) {
  726. // Free all the strdup()ed strings.
  727. for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
  728. i != e; ++i)
  729. free(*i);
  730. }
  731. // If we had an error processing our arguments, don't let the program execute
  732. if (ErrorParsing) exit(1);
  733. }
  734. //===----------------------------------------------------------------------===//
  735. // Option Base class implementation
  736. //
  737. bool Option::error(const Twine &Message, StringRef ArgName) {
  738. if (ArgName.data() == 0) ArgName = ArgStr;
  739. if (ArgName.empty())
  740. errs() << HelpStr; // Be nice for positional arguments
  741. else
  742. errs() << ProgramName << ": for the -" << ArgName;
  743. errs() << " option: " << Message << "\n";
  744. return true;
  745. }
  746. bool Option::addOccurrence(unsigned pos, StringRef ArgName,
  747. StringRef Value, bool MultiArg) {
  748. if (!MultiArg)
  749. NumOccurrences++; // Increment the number of times we have been seen
  750. switch (getNumOccurrencesFlag()) {
  751. case Optional:
  752. if (NumOccurrences > 1)
  753. return error("may only occur zero or one times!", ArgName);
  754. break;
  755. case Required:
  756. if (NumOccurrences > 1)
  757. return error("must occur exactly one time!", ArgName);
  758. // Fall through
  759. case OneOrMore:
  760. case ZeroOrMore:
  761. case ConsumeAfter: break;
  762. }
  763. return handleOccurrence(pos, ArgName, Value);
  764. }
  765. // getValueStr - Get the value description string, using "DefaultMsg" if nothing
  766. // has been specified yet.
  767. //
  768. static const char *getValueStr(const Option &O, const char *DefaultMsg) {
  769. if (O.ValueStr[0] == 0) return DefaultMsg;
  770. return O.ValueStr;
  771. }
  772. //===----------------------------------------------------------------------===//
  773. // cl::alias class implementation
  774. //
  775. // Return the width of the option tag for printing...
  776. size_t alias::getOptionWidth() const {
  777. return std::strlen(ArgStr)+6;
  778. }
  779. // Print out the option for the alias.
  780. void alias::printOptionInfo(size_t GlobalWidth) const {
  781. size_t L = std::strlen(ArgStr);
  782. outs() << " -" << ArgStr;
  783. outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
  784. }
  785. //===----------------------------------------------------------------------===//
  786. // Parser Implementation code...
  787. //
  788. // basic_parser implementation
  789. //
  790. // Return the width of the option tag for printing...
  791. size_t basic_parser_impl::getOptionWidth(const Option &O) const {
  792. size_t Len = std::strlen(O.ArgStr);
  793. if (const char *ValName = getValueName())
  794. Len += std::strlen(getValueStr(O, ValName))+3;
  795. return Len + 6;
  796. }
  797. // printOptionInfo - Print out information about this option. The
  798. // to-be-maintained width is specified.
  799. //
  800. void basic_parser_impl::printOptionInfo(const Option &O,
  801. size_t GlobalWidth) const {
  802. outs() << " -" << O.ArgStr;
  803. if (const char *ValName = getValueName())
  804. outs() << "=<" << getValueStr(O, ValName) << '>';
  805. outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
  806. }
  807. void basic_parser_impl::printOptionName(const Option &O,
  808. size_t GlobalWidth) const {
  809. outs() << " -" << O.ArgStr;
  810. outs().indent(GlobalWidth-std::strlen(O.ArgStr));
  811. }
  812. // parser<bool> implementation
  813. //
  814. bool parser<bool>::parse(Option &O, StringRef ArgName,
  815. StringRef Arg, bool &Value) {
  816. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  817. Arg == "1") {
  818. Value = true;
  819. return false;
  820. }
  821. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  822. Value = false;
  823. return false;
  824. }
  825. return O.error("'" + Arg +
  826. "' is invalid value for boolean argument! Try 0 or 1");
  827. }
  828. // parser<boolOrDefault> implementation
  829. //
  830. bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
  831. StringRef Arg, boolOrDefault &Value) {
  832. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  833. Arg == "1") {
  834. Value = BOU_TRUE;
  835. return false;
  836. }
  837. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  838. Value = BOU_FALSE;
  839. return false;
  840. }
  841. return O.error("'" + Arg +
  842. "' is invalid value for boolean argument! Try 0 or 1");
  843. }
  844. // parser<int> implementation
  845. //
  846. bool parser<int>::parse(Option &O, StringRef ArgName,
  847. StringRef Arg, int &Value) {
  848. if (Arg.getAsInteger(0, Value))
  849. return O.error("'" + Arg + "' value invalid for integer argument!");
  850. return false;
  851. }
  852. // parser<unsigned> implementation
  853. //
  854. bool parser<unsigned>::parse(Option &O, StringRef ArgName,
  855. StringRef Arg, unsigned &Value) {
  856. if (Arg.getAsInteger(0, Value))
  857. return O.error("'" + Arg + "' value invalid for uint argument!");
  858. return false;
  859. }
  860. // parser<unsigned long long> implementation
  861. //
  862. bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
  863. StringRef Arg, unsigned long long &Value){
  864. if (Arg.getAsInteger(0, Value))
  865. return O.error("'" + Arg + "' value invalid for uint argument!");
  866. return false;
  867. }
  868. // parser<double>/parser<float> implementation
  869. //
  870. static bool parseDouble(Option &O, StringRef Arg, double &Value) {
  871. SmallString<32> TmpStr(Arg.begin(), Arg.end());
  872. const char *ArgStart = TmpStr.c_str();
  873. char *End;
  874. Value = strtod(ArgStart, &End);
  875. if (*End != 0)
  876. return O.error("'" + Arg + "' value invalid for floating point argument!");
  877. return false;
  878. }
  879. bool parser<double>::parse(Option &O, StringRef ArgName,
  880. StringRef Arg, double &Val) {
  881. return parseDouble(O, Arg, Val);
  882. }
  883. bool parser<float>::parse(Option &O, StringRef ArgName,
  884. StringRef Arg, float &Val) {
  885. double dVal;
  886. if (parseDouble(O, Arg, dVal))
  887. return true;
  888. Val = (float)dVal;
  889. return false;
  890. }
  891. // generic_parser_base implementation
  892. //
  893. // findOption - Return the option number corresponding to the specified
  894. // argument string. If the option is not found, getNumOptions() is returned.
  895. //
  896. unsigned generic_parser_base::findOption(const char *Name) {
  897. unsigned e = getNumOptions();
  898. for (unsigned i = 0; i != e; ++i) {
  899. if (strcmp(getOption(i), Name) == 0)
  900. return i;
  901. }
  902. return e;
  903. }
  904. // Return the width of the option tag for printing...
  905. size_t generic_parser_base::getOptionWidth(const Option &O) const {
  906. if (O.hasArgStr()) {
  907. size_t Size = std::strlen(O.ArgStr)+6;
  908. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  909. Size = std::max(Size, std::strlen(getOption(i))+8);
  910. return Size;
  911. } else {
  912. size_t BaseSize = 0;
  913. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  914. BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
  915. return BaseSize;
  916. }
  917. }
  918. // printOptionInfo - Print out information about this option. The
  919. // to-be-maintained width is specified.
  920. //
  921. void generic_parser_base::printOptionInfo(const Option &O,
  922. size_t GlobalWidth) const {
  923. if (O.hasArgStr()) {
  924. size_t L = std::strlen(O.ArgStr);
  925. outs() << " -" << O.ArgStr;
  926. outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
  927. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  928. size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
  929. outs() << " =" << getOption(i);
  930. outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
  931. }
  932. } else {
  933. if (O.HelpStr[0])
  934. outs() << " " << O.HelpStr << '\n';
  935. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  936. size_t L = std::strlen(getOption(i));
  937. outs() << " -" << getOption(i);
  938. outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
  939. }
  940. }
  941. }
  942. static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
  943. // printGenericOptionDiff - Print the value of this option and it's default.
  944. //
  945. // "Generic" options have each value mapped to a name.
  946. void generic_parser_base::
  947. printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
  948. const GenericOptionValue &Default,
  949. size_t GlobalWidth) const {
  950. outs() << " -" << O.ArgStr;
  951. outs().indent(GlobalWidth-std::strlen(O.ArgStr));
  952. unsigned NumOpts = getNumOptions();
  953. for (unsigned i = 0; i != NumOpts; ++i) {
  954. if (Value.compare(getOptionValue(i)))
  955. continue;
  956. outs() << "= " << getOption(i);
  957. size_t L = std::strlen(getOption(i));
  958. size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
  959. outs().indent(NumSpaces) << " (default: ";
  960. for (unsigned j = 0; j != NumOpts; ++j) {
  961. if (Default.compare(getOptionValue(j)))
  962. continue;
  963. outs() << getOption(j);
  964. break;
  965. }
  966. outs() << ")\n";
  967. return;
  968. }
  969. outs() << "= *unknown option value*\n";
  970. }
  971. // printOptionDiff - Specializations for printing basic value types.
  972. //
  973. #define PRINT_OPT_DIFF(T) \
  974. void parser<T>:: \
  975. printOptionDiff(const Option &O, T V, OptionValue<T> D, \
  976. size_t GlobalWidth) const { \
  977. printOptionName(O, GlobalWidth); \
  978. std::string Str; \
  979. { \
  980. raw_string_ostream SS(Str); \
  981. SS << V; \
  982. } \
  983. outs() << "= " << Str; \
  984. size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
  985. outs().indent(NumSpaces) << " (default: "; \
  986. if (D.hasValue()) \
  987. outs() << D.getValue(); \
  988. else \
  989. outs() << "*no default*"; \
  990. outs() << ")\n"; \
  991. } \
  992. PRINT_OPT_DIFF(bool)
  993. PRINT_OPT_DIFF(boolOrDefault)
  994. PRINT_OPT_DIFF(int)
  995. PRINT_OPT_DIFF(unsigned)
  996. PRINT_OPT_DIFF(unsigned long long)
  997. PRINT_OPT_DIFF(double)
  998. PRINT_OPT_DIFF(float)
  999. PRINT_OPT_DIFF(char)
  1000. void parser<std::string>::
  1001. printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
  1002. size_t GlobalWidth) const {
  1003. printOptionName(O, GlobalWidth);
  1004. outs() << "= " << V;
  1005. size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
  1006. outs().indent(NumSpaces) << " (default: ";
  1007. if (D.hasValue())
  1008. outs() << D.getValue();
  1009. else
  1010. outs() << "*no default*";
  1011. outs() << ")\n";
  1012. }
  1013. // Print a placeholder for options that don't yet support printOptionDiff().
  1014. void basic_parser_impl::
  1015. printOptionNoValue(const Option &O, size_t GlobalWidth) const {
  1016. printOptionName(O, GlobalWidth);
  1017. outs() << "= *cannot print option value*\n";
  1018. }
  1019. //===----------------------------------------------------------------------===//
  1020. // -help and -help-hidden option implementation
  1021. //
  1022. static int OptNameCompare(const void *LHS, const void *RHS) {
  1023. typedef std::pair<const char *, Option*> pair_ty;
  1024. return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
  1025. }
  1026. // Copy Options into a vector so we can sort them as we like.
  1027. static void
  1028. sortOpts(StringMap<Option*> &OptMap,
  1029. SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
  1030. bool ShowHidden) {
  1031. SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
  1032. for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
  1033. I != E; ++I) {
  1034. // Ignore really-hidden options.
  1035. if (I->second->getOptionHiddenFlag() == ReallyHidden)
  1036. continue;
  1037. // Unless showhidden is set, ignore hidden flags.
  1038. if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
  1039. continue;
  1040. // If we've already seen this option, don't add it to the list again.
  1041. if (!OptionSet.insert(I->second))
  1042. continue;
  1043. Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
  1044. I->second));
  1045. }
  1046. // Sort the options list alphabetically.
  1047. qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
  1048. }
  1049. namespace {
  1050. class HelpPrinter {
  1051. size_t MaxArgLen;
  1052. const Option *EmptyArg;
  1053. const bool ShowHidden;
  1054. public:
  1055. explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
  1056. EmptyArg = 0;
  1057. }
  1058. void operator=(bool Value) {
  1059. if (Value == false) return;
  1060. // Get all the options.
  1061. SmallVector<Option*, 4> PositionalOpts;
  1062. SmallVector<Option*, 4> SinkOpts;
  1063. StringMap<Option*> OptMap;
  1064. GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
  1065. SmallVector<std::pair<const char *, Option*>, 128> Opts;
  1066. sortOpts(OptMap, Opts, ShowHidden);
  1067. if (ProgramOverview)
  1068. outs() << "OVERVIEW: " << ProgramOverview << "\n";
  1069. outs() << "USAGE: " << ProgramName << " [options]";
  1070. // Print out the positional options.
  1071. Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
  1072. if (!PositionalOpts.empty() &&
  1073. PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
  1074. CAOpt = PositionalOpts[0];
  1075. for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
  1076. if (PositionalOpts[i]->ArgStr[0])
  1077. outs() << " --" << PositionalOpts[i]->ArgStr;
  1078. outs() << " " << PositionalOpts[i]->HelpStr;
  1079. }
  1080. // Print the consume after option info if it exists...
  1081. if (CAOpt) outs() << " " << CAOpt->HelpStr;
  1082. outs() << "\n\n";
  1083. // Compute the maximum argument length...
  1084. MaxArgLen = 0;
  1085. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1086. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  1087. outs() << "OPTIONS:\n";
  1088. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1089. Opts[i].second->printOptionInfo(MaxArgLen);
  1090. // Print any extra help the user has declared.
  1091. for (std::vector<const char *>::iterator I = MoreHelp->begin(),
  1092. E = MoreHelp->end(); I != E; ++I)
  1093. outs() << *I;
  1094. MoreHelp->clear();
  1095. // Halt the program since help information was printed
  1096. exit(1);
  1097. }
  1098. };
  1099. } // End anonymous namespace
  1100. // Define the two HelpPrinter instances that are used to print out help, or
  1101. // help-hidden...
  1102. //
  1103. static HelpPrinter NormalPrinter(false);
  1104. static HelpPrinter HiddenPrinter(true);
  1105. static cl::opt<HelpPrinter, true, parser<bool> >
  1106. HOp("help", cl::desc("Display available options (-help-hidden for more)"),
  1107. cl::location(NormalPrinter), cl::ValueDisallowed);
  1108. static cl::opt<HelpPrinter, true, parser<bool> >
  1109. HHOp("help-hidden", cl::desc("Display all available options"),
  1110. cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
  1111. static cl::opt<bool>
  1112. PrintOptions("print-options",
  1113. cl::desc("Print non-default options after command line parsing"),
  1114. cl::Hidden, cl::init(false));
  1115. static cl::opt<bool>
  1116. PrintAllOptions("print-all-options",
  1117. cl::desc("Print all option values after command line parsing"),
  1118. cl::Hidden, cl::init(false));
  1119. // Print the value of each option.
  1120. void cl::PrintOptionValues() {
  1121. if (!PrintOptions && !PrintAllOptions) return;
  1122. // Get all the options.
  1123. SmallVector<Option*, 4> PositionalOpts;
  1124. SmallVector<Option*, 4> SinkOpts;
  1125. StringMap<Option*> OptMap;
  1126. GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
  1127. SmallVector<std::pair<const char *, Option*>, 128> Opts;
  1128. sortOpts(OptMap, Opts, /*ShowHidden*/true);
  1129. // Compute the maximum argument length...
  1130. size_t MaxArgLen = 0;
  1131. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1132. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  1133. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1134. Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
  1135. }
  1136. static void (*OverrideVersionPrinter)() = 0;
  1137. static std::vector<void (*)()>* ExtraVersionPrinters = 0;
  1138. namespace {
  1139. class VersionPrinter {
  1140. public:
  1141. void print() {
  1142. raw_ostream &OS = outs();
  1143. OS << "LLVM (http://llvm.org/):\n"
  1144. << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
  1145. #ifdef LLVM_VERSION_INFO
  1146. OS << LLVM_VERSION_INFO;
  1147. #endif
  1148. OS << "\n ";
  1149. #ifndef __OPTIMIZE__
  1150. OS << "DEBUG build";
  1151. #else
  1152. OS << "Optimized build";
  1153. #endif
  1154. #ifndef NDEBUG
  1155. OS << " with assertions";
  1156. #endif
  1157. std::string CPU = sys::getHostCPUName();
  1158. if (CPU == "generic") CPU = "(unknown)";
  1159. OS << ".\n"
  1160. #if (ENABLE_TIMESTAMPS == 1)
  1161. << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
  1162. #endif
  1163. << " Default target: " << sys::getDefaultTargetTriple() << '\n'
  1164. << " Host CPU: " << CPU << '\n';
  1165. }
  1166. void operator=(bool OptionWasSpecified) {
  1167. if (!OptionWasSpecified) return;
  1168. if (OverrideVersionPrinter != 0) {
  1169. (*OverrideVersionPrinter)();
  1170. exit(1);
  1171. }
  1172. print();
  1173. // Iterate over any registered extra printers and call them to add further
  1174. // information.
  1175. if (ExtraVersionPrinters != 0) {
  1176. outs() << '\n';
  1177. for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
  1178. E = ExtraVersionPrinters->end();
  1179. I != E; ++I)
  1180. (*I)();
  1181. }
  1182. exit(1);
  1183. }
  1184. };
  1185. } // End anonymous namespace
  1186. // Define the --version option that prints out the LLVM version for the tool
  1187. static VersionPrinter VersionPrinterInstance;
  1188. static cl::opt<VersionPrinter, true, parser<bool> >
  1189. VersOp("version", cl::desc("Display the version of this program"),
  1190. cl::location(VersionPrinterInstance), cl::ValueDisallowed);
  1191. // Utility function for printing the help message.
  1192. void cl::PrintHelpMessage() {
  1193. // This looks weird, but it actually prints the help message. The
  1194. // NormalPrinter variable is a HelpPrinter and the help gets printed when
  1195. // its operator= is invoked. That's because the "normal" usages of the
  1196. // help printer is to be assigned true/false depending on whether the
  1197. // -help option was given or not. Since we're circumventing that we have
  1198. // to make it look like -help was given, so we assign true.
  1199. NormalPrinter = true;
  1200. }
  1201. /// Utility function for printing version number.
  1202. void cl::PrintVersionMessage() {
  1203. VersionPrinterInstance.print();
  1204. }
  1205. void cl::SetVersionPrinter(void (*func)()) {
  1206. OverrideVersionPrinter = func;
  1207. }
  1208. void cl::AddExtraVersionPrinter(void (*func)()) {
  1209. if (ExtraVersionPrinters == 0)
  1210. ExtraVersionPrinters = new std::vector<void (*)()>;
  1211. ExtraVersionPrinters->push_back(func);
  1212. }