1 //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===// 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-dis [options] - Read LLVM bitcode from stdin, write asm to stdout 11 // llvm-dis [options] x.bc - Read LLVM bitcode from the x.bc file, write asm 12 // to the x.ll file. 13 // Options: 14 // 15 // Color Options: 16 // --color - Use colors in output (default=autodetect) 17 // 18 // Disassembler Options: 19 // -f - Enable binary output on terminals 20 // --materialize-metadata - Load module without materializing metadata, 21 // then materialize only the metadata 22 // -o <filename> - Override output filename 23 // --show-annotations - Add informational comments to the .ll file 24 // 25 // Generic Options: 26 // --help - Display available options 27 // (--help-hidden for more) 28 // --help-list - Display list of available options 29 // (--help-list-hidden for more) 30 // --version - Display the version of this program 31 // 32 //===----------------------------------------------------------------------===// 33 34 #include "llvm/Bitcode/BitcodeReader.h" 35 #include "llvm/IR/AssemblyAnnotationWriter.h" 36 #include "llvm/IR/DebugInfo.h" 37 #include "llvm/IR/DiagnosticInfo.h" 38 #include "llvm/IR/DiagnosticPrinter.h" 39 #include "llvm/IR/IntrinsicInst.h" 40 #include "llvm/IR/LLVMContext.h" 41 #include "llvm/IR/Module.h" 42 #include "llvm/IR/ModuleSummaryIndex.h" 43 #include "llvm/IR/Type.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Error.h" 46 #include "llvm/Support/FileSystem.h" 47 #include "llvm/Support/FormattedStream.h" 48 #include "llvm/Support/InitLLVM.h" 49 #include "llvm/Support/MemoryBuffer.h" 50 #include "llvm/Support/ToolOutputFile.h" 51 #include "llvm/Support/WithColor.h" 52 #include <system_error> 53 using namespace llvm; 54 55 static cl::OptionCategory DisCategory("Disassembler Options"); 56 57 static cl::list<std::string> InputFilenames(cl::Positional, 58 cl::desc("[input bitcode]..."), 59 cl::cat(DisCategory)); 60 61 static cl::opt<std::string> OutputFilename("o", 62 cl::desc("Override output filename"), 63 cl::value_desc("filename"), 64 cl::cat(DisCategory)); 65 66 static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"), 67 cl::cat(DisCategory)); 68 69 static cl::opt<bool> DontPrint("disable-output", 70 cl::desc("Don't output the .ll file"), 71 cl::Hidden, cl::cat(DisCategory)); 72 73 static cl::opt<bool> 74 SetImporting("set-importing", 75 cl::desc("Set lazy loading to pretend to import a module"), 76 cl::Hidden, cl::cat(DisCategory)); 77 78 static cl::opt<bool> 79 ShowAnnotations("show-annotations", 80 cl::desc("Add informational comments to the .ll file"), 81 cl::cat(DisCategory)); 82 83 static cl::opt<bool> PreserveAssemblyUseListOrder( 84 "preserve-ll-uselistorder", 85 cl::desc("Preserve use-list order when writing LLVM assembly."), 86 cl::init(false), cl::Hidden, cl::cat(DisCategory)); 87 88 static cl::opt<bool> 89 MaterializeMetadata("materialize-metadata", 90 cl::desc("Load module without materializing metadata, " 91 "then materialize only the metadata"), 92 cl::cat(DisCategory)); 93 94 static cl::opt<bool> PrintThinLTOIndexOnly( 95 "print-thinlto-index-only", 96 cl::desc("Only read thinlto index and print the index as LLVM assembly."), 97 cl::init(false), cl::Hidden, cl::cat(DisCategory)); 98 99 extern cl::opt<bool> WriteNewDbgInfoFormat; 100 101 extern cl::opt<cl::boolOrDefault> LoadBitcodeIntoNewDbgInfoFormat; 102 103 namespace { 104 105 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) { 106 OS << DL.getLine() << ":" << DL.getCol(); 107 if (DILocation *IDL = DL.getInlinedAt()) { 108 OS << "@"; 109 printDebugLoc(IDL, OS); 110 } 111 } 112 class CommentWriter : public AssemblyAnnotationWriter { 113 public: 114 void emitFunctionAnnot(const Function *F, 115 formatted_raw_ostream &OS) override { 116 OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses 117 OS << '\n'; 118 } 119 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override { 120 bool Padded = false; 121 if (!V.getType()->isVoidTy()) { 122 OS.PadToColumn(50); 123 Padded = true; 124 // Output # uses and type 125 OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]"; 126 } 127 if (const Instruction *I = dyn_cast<Instruction>(&V)) { 128 if (const DebugLoc &DL = I->getDebugLoc()) { 129 if (!Padded) { 130 OS.PadToColumn(50); 131 Padded = true; 132 OS << ";"; 133 } 134 OS << " [debug line = "; 135 printDebugLoc(DL,OS); 136 OS << "]"; 137 } 138 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) { 139 if (!Padded) { 140 OS.PadToColumn(50); 141 OS << ";"; 142 } 143 OS << " [debug variable = " << DDI->getVariable()->getName() << "]"; 144 } 145 else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) { 146 if (!Padded) { 147 OS.PadToColumn(50); 148 OS << ";"; 149 } 150 OS << " [debug variable = " << DVI->getVariable()->getName() << "]"; 151 } 152 } 153 } 154 }; 155 156 struct LLVMDisDiagnosticHandler : public DiagnosticHandler { 157 char *Prefix; 158 LLVMDisDiagnosticHandler(char *PrefixPtr) : Prefix(PrefixPtr) {} 159 bool handleDiagnostics(const DiagnosticInfo &DI) override { 160 raw_ostream &OS = errs(); 161 OS << Prefix << ": "; 162 switch (DI.getSeverity()) { 163 case DS_Error: WithColor::error(OS); break; 164 case DS_Warning: WithColor::warning(OS); break; 165 case DS_Remark: OS << "remark: "; break; 166 case DS_Note: WithColor::note(OS); break; 167 } 168 169 DiagnosticPrinterRawOStream DP(OS); 170 DI.print(DP); 171 OS << '\n'; 172 173 if (DI.getSeverity() == DS_Error) 174 exit(1); 175 return true; 176 } 177 }; 178 } // end anon namespace 179 180 static ExitOnError ExitOnErr; 181 182 int main(int argc, char **argv) { 183 InitLLVM X(argc, argv); 184 185 ExitOnErr.setBanner(std::string(argv[0]) + ": error: "); 186 187 cl::HideUnrelatedOptions({&DisCategory, &getColorCategory()}); 188 cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n"); 189 190 // Load bitcode into the new debug info format by default. 191 if (LoadBitcodeIntoNewDbgInfoFormat == cl::boolOrDefault::BOU_UNSET) 192 LoadBitcodeIntoNewDbgInfoFormat = cl::boolOrDefault::BOU_TRUE; 193 194 if (InputFilenames.size() < 1) { 195 InputFilenames.push_back("-"); 196 } else if (InputFilenames.size() > 1 && !OutputFilename.empty()) { 197 errs() 198 << "error: output file name cannot be set for multiple input files\n"; 199 return 1; 200 } 201 202 for (const auto &InputFilename : InputFilenames) { 203 // Use a fresh context for each input to avoid state 204 // cross-contamination across inputs (e.g. type name collisions). 205 LLVMContext Context; 206 Context.setDiagnosticHandler( 207 std::make_unique<LLVMDisDiagnosticHandler>(argv[0])); 208 209 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 210 MemoryBuffer::getFileOrSTDIN(InputFilename); 211 if (std::error_code EC = BufferOrErr.getError()) { 212 WithColor::error() << InputFilename << ": " << EC.message() << '\n'; 213 return 1; 214 } 215 std::unique_ptr<MemoryBuffer> MB = std::move(BufferOrErr.get()); 216 217 BitcodeFileContents IF = ExitOnErr(llvm::getBitcodeFileContents(*MB)); 218 219 const size_t N = IF.Mods.size(); 220 221 if (OutputFilename == "-" && N > 1) 222 errs() << "only single module bitcode files can be written to stdout\n"; 223 224 for (size_t I = 0; I < N; ++I) { 225 BitcodeModule MB = IF.Mods[I]; 226 227 std::unique_ptr<Module> M; 228 229 if (!PrintThinLTOIndexOnly) { 230 M = ExitOnErr( 231 MB.getLazyModule(Context, MaterializeMetadata, SetImporting)); 232 if (MaterializeMetadata) 233 ExitOnErr(M->materializeMetadata()); 234 else 235 ExitOnErr(M->materializeAll()); 236 } 237 238 BitcodeLTOInfo LTOInfo = ExitOnErr(MB.getLTOInfo()); 239 std::unique_ptr<ModuleSummaryIndex> Index; 240 if (LTOInfo.HasSummary) 241 Index = ExitOnErr(MB.getSummary()); 242 243 std::string FinalFilename(OutputFilename); 244 245 // Just use stdout. We won't actually print anything on it. 246 if (DontPrint) 247 FinalFilename = "-"; 248 249 if (FinalFilename.empty()) { // Unspecified output, infer it. 250 if (InputFilename == "-") { 251 FinalFilename = "-"; 252 } else { 253 StringRef IFN = InputFilename; 254 FinalFilename = (IFN.ends_with(".bc") ? IFN.drop_back(3) : IFN).str(); 255 if (N > 1) 256 FinalFilename += std::string(".") + std::to_string(I); 257 FinalFilename += ".ll"; 258 } 259 } else { 260 if (N > 1) 261 FinalFilename += std::string(".") + std::to_string(I); 262 } 263 264 std::error_code EC; 265 std::unique_ptr<ToolOutputFile> Out( 266 new ToolOutputFile(FinalFilename, EC, sys::fs::OF_TextWithCRLF)); 267 if (EC) { 268 errs() << EC.message() << '\n'; 269 return 1; 270 } 271 272 std::unique_ptr<AssemblyAnnotationWriter> Annotator; 273 if (ShowAnnotations) 274 Annotator.reset(new CommentWriter()); 275 276 // All that llvm-dis does is write the assembly to a file. 277 if (!DontPrint) { 278 if (M) { 279 M->setIsNewDbgInfoFormat(WriteNewDbgInfoFormat); 280 if (WriteNewDbgInfoFormat) 281 M->removeDebugIntrinsicDeclarations(); 282 M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder); 283 } 284 if (Index) 285 Index->print(Out->os()); 286 } 287 288 // Declare success. 289 Out->keep(); 290 } 291 } 292 293 return 0; 294 } 295