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/SourceMgr.h"
27#include "llvm/Support/SystemUtils.h"
28#include "llvm/Support/ToolOutputFile.h"
29#include <memory>
30#include <optional>
31using namespace llvm;
32
33cl::OptionCategory AsCat("llvm-as Options");
34
35static cl::opt<std::string> InputFilename(cl::Positional,
36                                          cl::desc("<input .llvm file>"),
37                                          cl::init("-"));
38
39static cl::opt<std::string> OutputFilename("o",
40                                           cl::desc("Override output filename"),
41                                           cl::value_desc("filename"),
42                                           cl::cat(AsCat));
43
44static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"),
45                           cl::cat(AsCat));
46
47static cl::opt<bool> DisableOutput("disable-output", cl::desc("Disable output"),
48                                   cl::init(false), cl::cat(AsCat));
49
50static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
51                                    cl::init(false), cl::cat(AsCat));
52
53static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as parsed"),
54                             cl::Hidden, cl::cat(AsCat));
55
56static cl::opt<bool>
57    DisableVerify("disable-verify", cl::Hidden,
58                  cl::desc("Do not run verifier on input LLVM (dangerous!)"),
59                  cl::cat(AsCat));
60
61static cl::opt<bool> PreserveBitcodeUseListOrder(
62    "preserve-bc-uselistorder",
63    cl::desc("Preserve use-list order when writing LLVM bitcode."),
64    cl::init(true), cl::Hidden, cl::cat(AsCat));
65
66static cl::opt<std::string> ClDataLayout("data-layout",
67                                         cl::desc("data layout string to use"),
68                                         cl::value_desc("layout-string"),
69                                         cl::init(""), cl::cat(AsCat));
70
71static void WriteOutputFile(const Module *M, const ModuleSummaryIndex *Index) {
72  // Infer the output filename if needed.
73  if (OutputFilename.empty()) {
74    if (InputFilename == "-") {
75      OutputFilename = "-";
76    } else {
77      StringRef IFN = InputFilename;
78      OutputFilename = (IFN.endswith(".ll") ? IFN.drop_back(3) : IFN).str();
79      OutputFilename += ".bc";
80    }
81  }
82
83  std::error_code EC;
84  std::unique_ptr<ToolOutputFile> Out(
85      new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
86  if (EC) {
87    errs() << EC.message() << '\n';
88    exit(1);
89  }
90
91  if (Force || !CheckBitcodeOutputToConsole(Out->os())) {
92    const ModuleSummaryIndex *IndexToWrite = nullptr;
93    // Don't attempt to write a summary index unless it contains any entries or
94    // has non-zero flags. The latter is used to assemble dummy index files for
95    // skipping modules by distributed ThinLTO backends. Otherwise we get an empty
96    // summary section.
97    if (Index && (Index->begin() != Index->end() || Index->getFlags()))
98      IndexToWrite = Index;
99    if (!IndexToWrite || (M && (!M->empty() || !M->global_empty())))
100      // If we have a non-empty Module, then we write the Module plus
101      // any non-null Index along with it as a per-module Index.
102      // If both are empty, this will give an empty module block, which is
103      // the expected behavior.
104      WriteBitcodeToFile(*M, Out->os(), PreserveBitcodeUseListOrder,
105                         IndexToWrite, EmitModuleHash);
106    else
107      // Otherwise, with an empty Module but non-empty Index, we write a
108      // combined index.
109      writeIndexToFile(*IndexToWrite, Out->os());
110  }
111
112  // Declare success.
113  Out->keep();
114}
115
116int main(int argc, char **argv) {
117  InitLLVM X(argc, argv);
118  cl::HideUnrelatedOptions(AsCat);
119  cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n");
120  LLVMContext Context;
121
122  // Parse the file now...
123  SMDiagnostic Err;
124  auto SetDataLayout = [](StringRef, StringRef) -> std::optional<std::string> {
125    if (ClDataLayout.empty())
126      return std::nullopt;
127    return ClDataLayout;
128  };
129  ParsedModuleAndIndex ModuleAndIndex;
130  if (DisableVerify) {
131    ModuleAndIndex = parseAssemblyFileWithIndexNoUpgradeDebugInfo(
132        InputFilename, Err, Context, nullptr, SetDataLayout);
133  } else {
134    ModuleAndIndex = parseAssemblyFileWithIndex(InputFilename, Err, Context,
135                                                nullptr, SetDataLayout);
136  }
137  std::unique_ptr<Module> M = std::move(ModuleAndIndex.Mod);
138  if (!M.get()) {
139    Err.print(argv[0], errs());
140    return 1;
141  }
142  std::unique_ptr<ModuleSummaryIndex> Index = std::move(ModuleAndIndex.Index);
143
144  if (!DisableVerify) {
145    std::string ErrorStr;
146    raw_string_ostream OS(ErrorStr);
147    if (verifyModule(*M.get(), &OS)) {
148      errs() << argv[0]
149             << ": assembly parsed, but does not verify as correct!\n";
150      errs() << OS.str();
151      return 1;
152    }
153    // TODO: Implement and call summary index verifier.
154  }
155
156  if (DumpAsm) {
157    errs() << "Here's the assembly:\n" << *M.get();
158    if (Index.get() && Index->begin() != Index->end())
159      Index->print(errs());
160  }
161
162  if (!DisableOutput)
163    WriteOutputFile(M.get(), Index.get());
164
165  return 0;
166}
167