cc1as_main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. //===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
  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 is the entry point to the clang -cc1as functionality, which implements
  11. // the direct interface to the LLVM MC based assembler.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Basic/Diagnostic.h"
  15. #include "clang/Basic/DiagnosticOptions.h"
  16. #include "clang/Driver/DriverDiagnostic.h"
  17. #include "clang/Driver/Options.h"
  18. #include "clang/Frontend/FrontendDiagnostic.h"
  19. #include "clang/Frontend/TextDiagnosticPrinter.h"
  20. #include "clang/Frontend/Utils.h"
  21. #include "llvm/ADT/StringSwitch.h"
  22. #include "llvm/ADT/Triple.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/MC/MCAsmBackend.h"
  25. #include "llvm/MC/MCAsmInfo.h"
  26. #include "llvm/MC/MCCodeEmitter.h"
  27. #include "llvm/MC/MCContext.h"
  28. #include "llvm/MC/MCInstrInfo.h"
  29. #include "llvm/MC/MCObjectFileInfo.h"
  30. #include "llvm/MC/MCParser/MCAsmParser.h"
  31. #include "llvm/MC/MCRegisterInfo.h"
  32. #include "llvm/MC/MCStreamer.h"
  33. #include "llvm/MC/MCSubtargetInfo.h"
  34. #include "llvm/MC/MCTargetAsmParser.h"
  35. #include "llvm/MC/MCTargetOptions.h"
  36. #include "llvm/Option/Arg.h"
  37. #include "llvm/Option/ArgList.h"
  38. #include "llvm/Option/OptTable.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/FileSystem.h"
  42. #include "llvm/Support/FormattedStream.h"
  43. #include "llvm/Support/Host.h"
  44. #include "llvm/Support/ManagedStatic.h"
  45. #include "llvm/Support/MemoryBuffer.h"
  46. #include "llvm/Support/Path.h"
  47. #include "llvm/Support/PrettyStackTrace.h"
  48. #include "llvm/Support/Signals.h"
  49. #include "llvm/Support/SourceMgr.h"
  50. #include "llvm/Support/TargetRegistry.h"
  51. #include "llvm/Support/TargetSelect.h"
  52. #include "llvm/Support/Timer.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include <memory>
  55. #include <system_error>
  56. using namespace clang;
  57. using namespace clang::driver;
  58. using namespace clang::driver::options;
  59. using namespace llvm;
  60. using namespace llvm::opt;
  61. namespace {
  62. /// \brief Helper class for representing a single invocation of the assembler.
  63. struct AssemblerInvocation {
  64. /// @name Target Options
  65. /// @{
  66. /// The name of the target triple to assemble for.
  67. std::string Triple;
  68. /// If given, the name of the target CPU to determine which instructions
  69. /// are legal.
  70. std::string CPU;
  71. /// The list of target specific features to enable or disable -- this should
  72. /// be a list of strings starting with '+' or '-'.
  73. std::vector<std::string> Features;
  74. /// @}
  75. /// @name Language Options
  76. /// @{
  77. std::vector<std::string> IncludePaths;
  78. unsigned NoInitialTextSection : 1;
  79. unsigned SaveTemporaryLabels : 1;
  80. unsigned GenDwarfForAssembly : 1;
  81. unsigned CompressDebugSections : 1;
  82. unsigned DwarfVersion;
  83. std::string DwarfDebugFlags;
  84. std::string DwarfDebugProducer;
  85. std::string DebugCompilationDir;
  86. std::string MainFileName;
  87. /// @}
  88. /// @name Frontend Options
  89. /// @{
  90. std::string InputFile;
  91. std::vector<std::string> LLVMArgs;
  92. std::string OutputPath;
  93. enum FileType {
  94. FT_Asm, ///< Assembly (.s) output, transliterate mode.
  95. FT_Null, ///< No output, for timing purposes.
  96. FT_Obj ///< Object file output.
  97. };
  98. FileType OutputType;
  99. unsigned ShowHelp : 1;
  100. unsigned ShowVersion : 1;
  101. /// @}
  102. /// @name Transliterate Options
  103. /// @{
  104. unsigned OutputAsmVariant;
  105. unsigned ShowEncoding : 1;
  106. unsigned ShowInst : 1;
  107. /// @}
  108. /// @name Assembler Options
  109. /// @{
  110. unsigned RelaxAll : 1;
  111. unsigned NoExecStack : 1;
  112. /// @}
  113. public:
  114. AssemblerInvocation() {
  115. Triple = "";
  116. NoInitialTextSection = 0;
  117. InputFile = "-";
  118. OutputPath = "-";
  119. OutputType = FT_Asm;
  120. OutputAsmVariant = 0;
  121. ShowInst = 0;
  122. ShowEncoding = 0;
  123. RelaxAll = 0;
  124. NoExecStack = 0;
  125. DwarfVersion = 3;
  126. }
  127. static bool CreateFromArgs(AssemblerInvocation &Res,
  128. ArrayRef<const char *> Argv,
  129. DiagnosticsEngine &Diags);
  130. };
  131. }
  132. bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
  133. ArrayRef<const char *> Argv,
  134. DiagnosticsEngine &Diags) {
  135. bool Success = true;
  136. // Parse the arguments.
  137. std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
  138. const unsigned IncludedFlagsBitmask = options::CC1AsOption;
  139. unsigned MissingArgIndex, MissingArgCount;
  140. std::unique_ptr<InputArgList> Args(
  141. OptTbl->ParseArgs(Argv.begin(), Argv.end(), MissingArgIndex, MissingArgCount,
  142. IncludedFlagsBitmask));
  143. // Check for missing argument error.
  144. if (MissingArgCount) {
  145. Diags.Report(diag::err_drv_missing_argument)
  146. << Args->getArgString(MissingArgIndex) << MissingArgCount;
  147. Success = false;
  148. }
  149. // Issue errors on unknown arguments.
  150. for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
  151. ie = Args->filtered_end();
  152. it != ie; ++it) {
  153. Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Args);
  154. Success = false;
  155. }
  156. // Construct the invocation.
  157. // Target Options
  158. Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
  159. Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
  160. Opts.Features = Args->getAllArgValues(OPT_target_feature);
  161. // Use the default target triple if unspecified.
  162. if (Opts.Triple.empty())
  163. Opts.Triple = llvm::sys::getDefaultTargetTriple();
  164. // Language Options
  165. Opts.IncludePaths = Args->getAllArgValues(OPT_I);
  166. Opts.NoInitialTextSection = Args->hasArg(OPT_n);
  167. Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
  168. Opts.GenDwarfForAssembly = Args->hasArg(OPT_g_Flag);
  169. Opts.CompressDebugSections = Args->hasArg(OPT_compress_debug_sections);
  170. if (Args->hasArg(OPT_gdwarf_2))
  171. Opts.DwarfVersion = 2;
  172. if (Args->hasArg(OPT_gdwarf_3))
  173. Opts.DwarfVersion = 3;
  174. if (Args->hasArg(OPT_gdwarf_4))
  175. Opts.DwarfVersion = 4;
  176. Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
  177. Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
  178. Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
  179. Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
  180. // Frontend Options
  181. if (Args->hasArg(OPT_INPUT)) {
  182. bool First = true;
  183. for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
  184. ie = Args->filtered_end(); it != ie; ++it, First=false) {
  185. const Arg *A = it;
  186. if (First)
  187. Opts.InputFile = A->getValue();
  188. else {
  189. Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
  190. Success = false;
  191. }
  192. }
  193. }
  194. Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
  195. Opts.OutputPath = Args->getLastArgValue(OPT_o);
  196. if (Arg *A = Args->getLastArg(OPT_filetype)) {
  197. StringRef Name = A->getValue();
  198. unsigned OutputType = StringSwitch<unsigned>(Name)
  199. .Case("asm", FT_Asm)
  200. .Case("null", FT_Null)
  201. .Case("obj", FT_Obj)
  202. .Default(~0U);
  203. if (OutputType == ~0U) {
  204. Diags.Report(diag::err_drv_invalid_value)
  205. << A->getAsString(*Args) << Name;
  206. Success = false;
  207. } else
  208. Opts.OutputType = FileType(OutputType);
  209. }
  210. Opts.ShowHelp = Args->hasArg(OPT_help);
  211. Opts.ShowVersion = Args->hasArg(OPT_version);
  212. // Transliterate Options
  213. Opts.OutputAsmVariant =
  214. getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
  215. Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
  216. Opts.ShowInst = Args->hasArg(OPT_show_inst);
  217. // Assemble Options
  218. Opts.RelaxAll = Args->hasArg(OPT_mrelax_all);
  219. Opts.NoExecStack = Args->hasArg(OPT_mno_exec_stack);
  220. return Success;
  221. }
  222. static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
  223. DiagnosticsEngine &Diags,
  224. bool Binary) {
  225. if (Opts.OutputPath.empty())
  226. Opts.OutputPath = "-";
  227. // Make sure that the Out file gets unlinked from the disk if we get a
  228. // SIGINT.
  229. if (Opts.OutputPath != "-")
  230. sys::RemoveFileOnSignal(Opts.OutputPath);
  231. std::error_code EC;
  232. raw_fd_ostream *Out = new raw_fd_ostream(
  233. Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
  234. if (EC) {
  235. Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath
  236. << EC.message();
  237. delete Out;
  238. return nullptr;
  239. }
  240. return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
  241. }
  242. static bool ExecuteAssembler(AssemblerInvocation &Opts,
  243. DiagnosticsEngine &Diags) {
  244. // Get the target specific parser.
  245. std::string Error;
  246. const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
  247. if (!TheTarget)
  248. return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
  249. ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
  250. MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
  251. if (std::error_code EC = Buffer.getError()) {
  252. Error = EC.message();
  253. return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
  254. }
  255. SourceMgr SrcMgr;
  256. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  257. SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
  258. // Record the location of the include directories so that the lexer can find
  259. // it later.
  260. SrcMgr.setIncludeDirs(Opts.IncludePaths);
  261. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
  262. assert(MRI && "Unable to create target register info!");
  263. std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
  264. assert(MAI && "Unable to create target asm info!");
  265. // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
  266. // may be created with a combination of default and explicit settings.
  267. if (Opts.CompressDebugSections)
  268. MAI->setCompressDebugSections(true);
  269. bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
  270. std::unique_ptr<formatted_raw_ostream> Out(
  271. GetOutputStream(Opts, Diags, IsBinary));
  272. if (!Out)
  273. return true;
  274. // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
  275. // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
  276. std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
  277. MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
  278. // FIXME: Assembler behavior can change with -static.
  279. MOFI->InitMCObjectFileInfo(Opts.Triple,
  280. Reloc::Default, CodeModel::Default, Ctx);
  281. if (Opts.SaveTemporaryLabels)
  282. Ctx.setAllowTemporaryLabels(false);
  283. if (Opts.GenDwarfForAssembly)
  284. Ctx.setGenDwarfForAssembly(true);
  285. if (!Opts.DwarfDebugFlags.empty())
  286. Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
  287. if (!Opts.DwarfDebugProducer.empty())
  288. Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
  289. if (!Opts.DebugCompilationDir.empty())
  290. Ctx.setCompilationDir(Opts.DebugCompilationDir);
  291. if (!Opts.MainFileName.empty())
  292. Ctx.setMainFileName(StringRef(Opts.MainFileName));
  293. Ctx.setDwarfVersion(Opts.DwarfVersion);
  294. // Build up the feature string from the target feature list.
  295. std::string FS;
  296. if (!Opts.Features.empty()) {
  297. FS = Opts.Features[0];
  298. for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
  299. FS += "," + Opts.Features[i];
  300. }
  301. std::unique_ptr<MCStreamer> Str;
  302. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  303. std::unique_ptr<MCSubtargetInfo> STI(
  304. TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
  305. // FIXME: There is a bit of code duplication with addPassesToEmitFile.
  306. if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
  307. MCInstPrinter *IP =
  308. TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
  309. *STI);
  310. MCCodeEmitter *CE = nullptr;
  311. MCAsmBackend *MAB = nullptr;
  312. if (Opts.ShowEncoding) {
  313. CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
  314. MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
  315. }
  316. Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
  317. /*useDwarfDirectory*/ true,
  318. IP, CE, MAB,
  319. Opts.ShowInst));
  320. } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
  321. Str.reset(createNullStreamer(Ctx));
  322. } else {
  323. assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
  324. "Invalid file type!");
  325. MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
  326. MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
  327. Opts.CPU);
  328. Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
  329. CE, *STI, Opts.RelaxAll,
  330. Opts.NoExecStack));
  331. Str.get()->InitSections();
  332. }
  333. bool Failed = false;
  334. std::unique_ptr<MCAsmParser> Parser(
  335. createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
  336. // FIXME: init MCTargetOptions from sanitizer flags here.
  337. MCTargetOptions Options;
  338. std::unique_ptr<MCTargetAsmParser> TAP(
  339. TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
  340. if (!TAP)
  341. Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
  342. if (!Failed) {
  343. Parser->setTargetParser(*TAP.get());
  344. Failed = Parser->Run(Opts.NoInitialTextSection);
  345. }
  346. // Close the output stream early.
  347. Out.reset();
  348. // Delete output file if there were errors.
  349. if (Failed && Opts.OutputPath != "-")
  350. sys::fs::remove(Opts.OutputPath);
  351. return Failed;
  352. }
  353. static void LLVMErrorHandler(void *UserData, const std::string &Message,
  354. bool GenCrashDiag) {
  355. DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
  356. Diags.Report(diag::err_fe_error_backend) << Message;
  357. // We cannot recover from llvm errors.
  358. exit(1);
  359. }
  360. int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
  361. // Print a stack trace if we signal out.
  362. sys::PrintStackTraceOnErrorSignal();
  363. PrettyStackTraceProgram X(Argv.size(), Argv.data());
  364. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  365. // Initialize targets and assembly printers/parsers.
  366. InitializeAllTargetInfos();
  367. InitializeAllTargetMCs();
  368. InitializeAllAsmParsers();
  369. // Construct our diagnostic client.
  370. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  371. TextDiagnosticPrinter *DiagClient
  372. = new TextDiagnosticPrinter(errs(), &*DiagOpts);
  373. DiagClient->setPrefix("clang -cc1as");
  374. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  375. DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
  376. // Set an error handler, so that any LLVM backend diagnostics go through our
  377. // error handler.
  378. ScopedFatalErrorHandler FatalErrorHandler
  379. (LLVMErrorHandler, static_cast<void*>(&Diags));
  380. // Parse the arguments.
  381. AssemblerInvocation Asm;
  382. if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
  383. return 1;
  384. if (Asm.ShowHelp) {
  385. std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
  386. Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
  387. /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0);
  388. return 0;
  389. }
  390. // Honor -version.
  391. //
  392. // FIXME: Use a better -version message?
  393. if (Asm.ShowVersion) {
  394. llvm::cl::PrintVersionMessage();
  395. return 0;
  396. }
  397. // Honor -mllvm.
  398. //
  399. // FIXME: Remove this, one day.
  400. if (!Asm.LLVMArgs.empty()) {
  401. unsigned NumArgs = Asm.LLVMArgs.size();
  402. const char **Args = new const char*[NumArgs + 2];
  403. Args[0] = "clang (LLVM option parsing)";
  404. for (unsigned i = 0; i != NumArgs; ++i)
  405. Args[i + 1] = Asm.LLVMArgs[i].c_str();
  406. Args[NumArgs + 1] = nullptr;
  407. llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
  408. }
  409. // Execute the invocation, unless there were parsing errors.
  410. bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
  411. // If any timers were active but haven't been destroyed yet, print their
  412. // results now.
  413. TimerGroup::printAll(errs());
  414. return !!Failed;
  415. }