xref: /llvm-project/llvm/tools/llvm-as/llvm-as.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
1 //===--- llvm-as.cpp - The low-level LLVM assembler -----------------------===//
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 utility may be invoked in the following manner:
10 //   llvm-as --help         - Output information about command line switches
11 //   llvm-as [options]      - Read LLVM asm from stdin, write bitcode to stdout
12 //   llvm-as [options] x.ll - Read LLVM asm from the x.ll file, write bitcode
13 //                            to the x.bc file.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/AsmParser/Parser.h"
18 #include "llvm/Bitcode/BitcodeWriter.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/ModuleSummaryIndex.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/InitLLVM.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/SystemUtils.h"
29 #include "llvm/Support/ToolOutputFile.h"
30 #include <memory>
31 using namespace llvm;
32 
33 static cl::opt<std::string> InputFilename(cl::Positional,
34                                           cl::desc("<input .llvm file>"),
35                                           cl::init("-"));
36 
37 static cl::opt<std::string> OutputFilename("o",
38                                            cl::desc("Override output filename"),
39                                            cl::value_desc("filename"));
40 
41 static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"));
42 
43 static cl::opt<bool> DisableOutput("disable-output", cl::desc("Disable output"),
44                                    cl::init(false));
45 
46 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
47                                     cl::init(false));
48 
49 static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as parsed"),
50                              cl::Hidden);
51 
52 static cl::opt<bool>
53     DisableVerify("disable-verify", cl::Hidden,
54                   cl::desc("Do not run verifier on input LLVM (dangerous!)"));
55 
56 static cl::opt<bool> PreserveBitcodeUseListOrder(
57     "preserve-bc-uselistorder",
58     cl::desc("Preserve use-list order when writing LLVM bitcode."),
59     cl::init(true), cl::Hidden);
60 
61 static cl::opt<std::string> ClDataLayout("data-layout",
62                                          cl::desc("data layout string to use"),
63                                          cl::value_desc("layout-string"),
64                                          cl::init(""));
65 
66 static void WriteOutputFile(const Module *M, const ModuleSummaryIndex *Index) {
67   // Infer the output filename if needed.
68   if (OutputFilename.empty()) {
69     if (InputFilename == "-") {
70       OutputFilename = "-";
71     } else {
72       StringRef IFN = InputFilename;
73       OutputFilename = (IFN.endswith(".ll") ? IFN.drop_back(3) : IFN).str();
74       OutputFilename += ".bc";
75     }
76   }
77 
78   std::error_code EC;
79   std::unique_ptr<ToolOutputFile> Out(
80       new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
81   if (EC) {
82     errs() << EC.message() << '\n';
83     exit(1);
84   }
85 
86   if (Force || !CheckBitcodeOutputToConsole(Out->os(), true)) {
87     const ModuleSummaryIndex *IndexToWrite = nullptr;
88     // Don't attempt to write a summary index unless it contains any entries.
89     // Otherwise we get an empty summary section.
90     if (Index && Index->begin() != Index->end())
91       IndexToWrite = Index;
92     if (!IndexToWrite || (M && (!M->empty() || !M->global_empty())))
93       // If we have a non-empty Module, then we write the Module plus
94       // any non-null Index along with it as a per-module Index.
95       // If both are empty, this will give an empty module block, which is
96       // the expected behavior.
97       WriteBitcodeToFile(*M, Out->os(), PreserveBitcodeUseListOrder,
98                          IndexToWrite, EmitModuleHash);
99     else
100       // Otherwise, with an empty Module but non-empty Index, we write a
101       // combined index.
102       WriteIndexToFile(*IndexToWrite, Out->os());
103   }
104 
105   // Declare success.
106   Out->keep();
107 }
108 
109 int main(int argc, char **argv) {
110   InitLLVM X(argc, argv);
111   LLVMContext Context;
112   cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n");
113 
114   // Parse the file now...
115   SMDiagnostic Err;
116   auto ModuleAndIndex = parseAssemblyFileWithIndex(
117       InputFilename, Err, Context, nullptr, !DisableVerify, ClDataLayout);
118   std::unique_ptr<Module> M = std::move(ModuleAndIndex.Mod);
119   if (!M.get()) {
120     Err.print(argv[0], errs());
121     return 1;
122   }
123   std::unique_ptr<ModuleSummaryIndex> Index = std::move(ModuleAndIndex.Index);
124 
125   if (!DisableVerify) {
126     std::string ErrorStr;
127     raw_string_ostream OS(ErrorStr);
128     if (verifyModule(*M.get(), &OS)) {
129       errs() << argv[0]
130              << ": assembly parsed, but does not verify as correct!\n";
131       errs() << OS.str();
132       return 1;
133     }
134     // TODO: Implement and call summary index verifier.
135   }
136 
137   if (DumpAsm) {
138     errs() << "Here's the assembly:\n" << *M.get();
139     if (Index.get() && Index->begin() != Index->end())
140       Index->print(errs());
141   }
142 
143   if (!DisableOutput)
144     WriteOutputFile(M.get(), Index.get());
145 
146   return 0;
147 }
148