]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-mc/llvm-mc.cpp
Update ena-com HAL to v1.1.4.3 and update driver accordingly
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-mc / llvm-mc.cpp
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
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 utility is a simple driver that allows command line hacking on machine
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Disassembler.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCParser/AsmLexer.h"
23 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42
43 using namespace llvm;
44
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50                cl::value_desc("filename"));
51
52 static cl::opt<bool>
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54
55 static cl::opt<bool> RelaxELFRel(
56     "relax-relocations", cl::init(true),
57     cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
58
59 static cl::opt<DebugCompressionType> CompressDebugSections(
60     "compress-debug-sections", cl::ValueOptional,
61     cl::init(DebugCompressionType::None),
62     cl::desc("Choose DWARF debug sections compression:"),
63     cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
64                clEnumValN(DebugCompressionType::Z, "zlib",
65                           "Use zlib compression"),
66                clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
67                           "Use zlib-gnu compression (deprecated)")));
68
69 static cl::opt<bool>
70 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
71
72 static cl::opt<bool>
73 ShowInstOperands("show-inst-operands",
74                  cl::desc("Show instructions operands as parsed"));
75
76 static cl::opt<unsigned>
77 OutputAsmVariant("output-asm-variant",
78                  cl::desc("Syntax variant to use for output printing"));
79
80 static cl::opt<bool>
81 PrintImmHex("print-imm-hex", cl::init(false),
82             cl::desc("Prefer hex format for immediate values"));
83
84 static cl::list<std::string>
85 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
86
87 static cl::opt<bool>
88     PreserveComments("preserve-comments",
89                      cl::desc("Preserve Comments in outputted assembly"));
90
91 enum OutputFileType {
92   OFT_Null,
93   OFT_AssemblyFile,
94   OFT_ObjectFile
95 };
96 static cl::opt<OutputFileType>
97 FileType("filetype", cl::init(OFT_AssemblyFile),
98   cl::desc("Choose an output file type:"),
99   cl::values(
100        clEnumValN(OFT_AssemblyFile, "asm",
101                   "Emit an assembly ('.s') file"),
102        clEnumValN(OFT_Null, "null",
103                   "Don't emit anything (for timing purposes)"),
104        clEnumValN(OFT_ObjectFile, "obj",
105                   "Emit a native object ('.o') file")));
106
107 static cl::list<std::string>
108 IncludeDirs("I", cl::desc("Directory of include files"),
109             cl::value_desc("directory"), cl::Prefix);
110
111 static cl::opt<std::string>
112 ArchName("arch", cl::desc("Target arch to assemble for, "
113                           "see -version for available targets"));
114
115 static cl::opt<std::string>
116 TripleName("triple", cl::desc("Target triple to assemble for, "
117                               "see -version for available targets"));
118
119 static cl::opt<std::string>
120 MCPU("mcpu",
121      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122      cl::value_desc("cpu-name"),
123      cl::init(""));
124
125 static cl::list<std::string>
126 MAttrs("mattr",
127   cl::CommaSeparated,
128   cl::desc("Target specific attributes (-mattr=help for details)"),
129   cl::value_desc("a1,+a2,-a3,..."));
130
131 static cl::opt<bool> PIC("position-independent",
132                          cl::desc("Position independent"), cl::init(false));
133
134 static cl::opt<llvm::CodeModel::Model>
135 CMModel("code-model",
136         cl::desc("Choose code model"),
137         cl::init(CodeModel::Default),
138         cl::values(clEnumValN(CodeModel::Default, "default",
139                               "Target default code model"),
140                    clEnumValN(CodeModel::Small, "small",
141                               "Small code model"),
142                    clEnumValN(CodeModel::Kernel, "kernel",
143                               "Kernel code model"),
144                    clEnumValN(CodeModel::Medium, "medium",
145                               "Medium code model"),
146                    clEnumValN(CodeModel::Large, "large",
147                               "Large code model")));
148
149 static cl::opt<bool>
150 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
151                                    "in the text section"));
152
153 static cl::opt<bool>
154 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
155                                   "source files"));
156
157 static cl::opt<std::string>
158 DebugCompilationDir("fdebug-compilation-dir",
159                     cl::desc("Specifies the debug info's compilation dir"));
160
161 static cl::opt<std::string>
162 MainFileName("main-file-name",
163              cl::desc("Specifies the name we should consider the input file"));
164
165 static cl::opt<bool> SaveTempLabels("save-temp-labels",
166                                     cl::desc("Don't discard temporary labels"));
167
168 static cl::opt<bool> NoExecStack("no-exec-stack",
169                                  cl::desc("File doesn't need an exec stack"));
170
171 enum ActionType {
172   AC_AsLex,
173   AC_Assemble,
174   AC_Disassemble,
175   AC_MDisassemble,
176 };
177
178 static cl::opt<ActionType>
179 Action(cl::desc("Action to perform:"),
180        cl::init(AC_Assemble),
181        cl::values(clEnumValN(AC_AsLex, "as-lex",
182                              "Lex tokens from a .s file"),
183                   clEnumValN(AC_Assemble, "assemble",
184                              "Assemble a .s file (default)"),
185                   clEnumValN(AC_Disassemble, "disassemble",
186                              "Disassemble strings of hex bytes"),
187                   clEnumValN(AC_MDisassemble, "mdis",
188                              "Marked up disassembly of strings of hex bytes")));
189
190 static const Target *GetTarget(const char *ProgName) {
191   // Figure out the target triple.
192   if (TripleName.empty())
193     TripleName = sys::getDefaultTargetTriple();
194   Triple TheTriple(Triple::normalize(TripleName));
195
196   // Get the target specific parser.
197   std::string Error;
198   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
199                                                          Error);
200   if (!TheTarget) {
201     errs() << ProgName << ": " << Error;
202     return nullptr;
203   }
204
205   // Update the triple name and return the found target.
206   TripleName = TheTriple.getTriple();
207   return TheTarget;
208 }
209
210 static std::unique_ptr<tool_output_file> GetOutputStream() {
211   if (OutputFilename == "")
212     OutputFilename = "-";
213
214   std::error_code EC;
215   auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
216                                                  sys::fs::F_None);
217   if (EC) {
218     errs() << EC.message() << '\n';
219     return nullptr;
220   }
221
222   return Out;
223 }
224
225 static std::string DwarfDebugFlags;
226 static void setDwarfDebugFlags(int argc, char **argv) {
227   if (!getenv("RC_DEBUG_OPTIONS"))
228     return;
229   for (int i = 0; i < argc; i++) {
230     DwarfDebugFlags += argv[i];
231     if (i + 1 < argc)
232       DwarfDebugFlags += " ";
233   }
234 }
235
236 static std::string DwarfDebugProducer;
237 static void setDwarfDebugProducer() {
238   if(!getenv("DEBUG_PRODUCER"))
239     return;
240   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
241 }
242
243 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
244                       raw_ostream &OS) {
245
246   AsmLexer Lexer(MAI);
247   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
248
249   bool Error = false;
250   while (Lexer.Lex().isNot(AsmToken::Eof)) {
251     const AsmToken &Tok = Lexer.getTok();
252
253     switch (Tok.getKind()) {
254     default:
255       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
256                           "unknown token");
257       Error = true;
258       break;
259     case AsmToken::Error:
260       Error = true; // error already printed.
261       break;
262     case AsmToken::Identifier:
263       OS << "identifier: " << Lexer.getTok().getString();
264       break;
265     case AsmToken::Integer:
266       OS << "int: " << Lexer.getTok().getString();
267       break;
268     case AsmToken::Real:
269       OS << "real: " << Lexer.getTok().getString();
270       break;
271     case AsmToken::String:
272       OS << "string: " << Lexer.getTok().getString();
273       break;
274
275     case AsmToken::Amp:            OS << "Amp"; break;
276     case AsmToken::AmpAmp:         OS << "AmpAmp"; break;
277     case AsmToken::At:             OS << "At"; break;
278     case AsmToken::Caret:          OS << "Caret"; break;
279     case AsmToken::Colon:          OS << "Colon"; break;
280     case AsmToken::Comma:          OS << "Comma"; break;
281     case AsmToken::Dollar:         OS << "Dollar"; break;
282     case AsmToken::Dot:            OS << "Dot"; break;
283     case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
284     case AsmToken::Eof:            OS << "Eof"; break;
285     case AsmToken::Equal:          OS << "Equal"; break;
286     case AsmToken::EqualEqual:     OS << "EqualEqual"; break;
287     case AsmToken::Exclaim:        OS << "Exclaim"; break;
288     case AsmToken::ExclaimEqual:   OS << "ExclaimEqual"; break;
289     case AsmToken::Greater:        OS << "Greater"; break;
290     case AsmToken::GreaterEqual:   OS << "GreaterEqual"; break;
291     case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
292     case AsmToken::Hash:           OS << "Hash"; break;
293     case AsmToken::LBrac:          OS << "LBrac"; break;
294     case AsmToken::LCurly:         OS << "LCurly"; break;
295     case AsmToken::LParen:         OS << "LParen"; break;
296     case AsmToken::Less:           OS << "Less"; break;
297     case AsmToken::LessEqual:      OS << "LessEqual"; break;
298     case AsmToken::LessGreater:    OS << "LessGreater"; break;
299     case AsmToken::LessLess:       OS << "LessLess"; break;
300     case AsmToken::Minus:          OS << "Minus"; break;
301     case AsmToken::Percent:        OS << "Percent"; break;
302     case AsmToken::Pipe:           OS << "Pipe"; break;
303     case AsmToken::PipePipe:       OS << "PipePipe"; break;
304     case AsmToken::Plus:           OS << "Plus"; break;
305     case AsmToken::RBrac:          OS << "RBrac"; break;
306     case AsmToken::RCurly:         OS << "RCurly"; break;
307     case AsmToken::RParen:         OS << "RParen"; break;
308     case AsmToken::Slash:          OS << "Slash"; break;
309     case AsmToken::Star:           OS << "Star"; break;
310     case AsmToken::Tilde:          OS << "Tilde"; break;
311     case AsmToken::PercentCall16:
312       OS << "PercentCall16";
313       break;
314     case AsmToken::PercentCall_Hi:
315       OS << "PercentCall_Hi";
316       break;
317     case AsmToken::PercentCall_Lo:
318       OS << "PercentCall_Lo";
319       break;
320     case AsmToken::PercentDtprel_Hi:
321       OS << "PercentDtprel_Hi";
322       break;
323     case AsmToken::PercentDtprel_Lo:
324       OS << "PercentDtprel_Lo";
325       break;
326     case AsmToken::PercentGot:
327       OS << "PercentGot";
328       break;
329     case AsmToken::PercentGot_Disp:
330       OS << "PercentGot_Disp";
331       break;
332     case AsmToken::PercentGot_Hi:
333       OS << "PercentGot_Hi";
334       break;
335     case AsmToken::PercentGot_Lo:
336       OS << "PercentGot_Lo";
337       break;
338     case AsmToken::PercentGot_Ofst:
339       OS << "PercentGot_Ofst";
340       break;
341     case AsmToken::PercentGot_Page:
342       OS << "PercentGot_Page";
343       break;
344     case AsmToken::PercentGottprel:
345       OS << "PercentGottprel";
346       break;
347     case AsmToken::PercentGp_Rel:
348       OS << "PercentGp_Rel";
349       break;
350     case AsmToken::PercentHi:
351       OS << "PercentHi";
352       break;
353     case AsmToken::PercentHigher:
354       OS << "PercentHigher";
355       break;
356     case AsmToken::PercentHighest:
357       OS << "PercentHighest";
358       break;
359     case AsmToken::PercentLo:
360       OS << "PercentLo";
361       break;
362     case AsmToken::PercentNeg:
363       OS << "PercentNeg";
364       break;
365     case AsmToken::PercentPcrel_Hi:
366       OS << "PercentPcrel_Hi";
367       break;
368     case AsmToken::PercentPcrel_Lo:
369       OS << "PercentPcrel_Lo";
370       break;
371     case AsmToken::PercentTlsgd:
372       OS << "PercentTlsgd";
373       break;
374     case AsmToken::PercentTlsldm:
375       OS << "PercentTlsldm";
376       break;
377     case AsmToken::PercentTprel_Hi:
378       OS << "PercentTprel_Hi";
379       break;
380     case AsmToken::PercentTprel_Lo:
381       OS << "PercentTprel_Lo";
382       break;
383     }
384
385     // Print the token string.
386     OS << " (\"";
387     OS.write_escaped(Tok.getString());
388     OS << "\")\n";
389   }
390
391   return Error;
392 }
393
394 static int fillCommandLineSymbols(MCAsmParser &Parser) {
395   for (auto &I: DefineSymbol) {
396     auto Pair = StringRef(I).split('=');
397     auto Sym = Pair.first;
398     auto Val = Pair.second;
399
400     if (Sym.empty() || Val.empty()) {
401       errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
402       return 1;
403     }
404     int64_t Value;
405     if (Val.getAsInteger(0, Value)) {
406       errs() << "error: Value is not an integer: " << Val << "\n";
407       return 1;
408     }
409     Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
410   }
411   return 0;
412 }
413
414 static int AssembleInput(const char *ProgName, const Target *TheTarget,
415                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
416                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
417                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
418   std::unique_ptr<MCAsmParser> Parser(
419       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
420   std::unique_ptr<MCTargetAsmParser> TAP(
421       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
422
423   if (!TAP) {
424     errs() << ProgName
425            << ": error: this target does not support assembly parsing.\n";
426     return 1;
427   }
428
429   int SymbolResult = fillCommandLineSymbols(*Parser);
430   if(SymbolResult)
431     return SymbolResult;
432   Parser->setShowParsedOperands(ShowInstOperands);
433   Parser->setTargetParser(*TAP);
434
435   int Res = Parser->Run(NoInitialTextSection);
436
437   return Res;
438 }
439
440 int main(int argc, char **argv) {
441   // Print a stack trace if we signal out.
442   sys::PrintStackTraceOnErrorSignal(argv[0]);
443   PrettyStackTraceProgram X(argc, argv);
444   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
445
446   // Initialize targets and assembly printers/parsers.
447   llvm::InitializeAllTargetInfos();
448   llvm::InitializeAllTargetMCs();
449   llvm::InitializeAllAsmParsers();
450   llvm::InitializeAllDisassemblers();
451
452   // Register the target printer for --version.
453   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
454
455   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
456   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
457   TripleName = Triple::normalize(TripleName);
458   setDwarfDebugFlags(argc, argv);
459
460   setDwarfDebugProducer();
461
462   const char *ProgName = argv[0];
463   const Target *TheTarget = GetTarget(ProgName);
464   if (!TheTarget)
465     return 1;
466   // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
467   // construct the Triple object.
468   Triple TheTriple(TripleName);
469
470   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
471       MemoryBuffer::getFileOrSTDIN(InputFilename);
472   if (std::error_code EC = BufferPtr.getError()) {
473     errs() << InputFilename << ": " << EC.message() << '\n';
474     return 1;
475   }
476   MemoryBuffer *Buffer = BufferPtr->get();
477
478   SourceMgr SrcMgr;
479
480   // Tell SrcMgr about this buffer, which is what the parser will pick up.
481   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
482
483   // Record the location of the include directories so that the lexer can find
484   // it later.
485   SrcMgr.setIncludeDirs(IncludeDirs);
486
487   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
488   assert(MRI && "Unable to create target register info!");
489
490   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
491   assert(MAI && "Unable to create target asm info!");
492
493   MAI->setRelaxELFRelocations(RelaxELFRel);
494
495   if (CompressDebugSections != DebugCompressionType::None) {
496     if (!zlib::isAvailable()) {
497       errs() << ProgName
498              << ": build tools with zlib to enable -compress-debug-sections";
499       return 1;
500     }
501     MAI->setCompressDebugSections(CompressDebugSections);
502   }
503   MAI->setPreserveAsmComments(PreserveComments);
504
505   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
506   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
507   MCObjectFileInfo MOFI;
508   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
509   MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
510
511   if (SaveTempLabels)
512     Ctx.setAllowTemporaryLabels(false);
513
514   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
515   // Default to 4 for dwarf version.
516   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
517   if (DwarfVersion < 2 || DwarfVersion > 5) {
518     errs() << ProgName << ": Dwarf version " << DwarfVersion
519            << " is not supported." << '\n';
520     return 1;
521   }
522   Ctx.setDwarfVersion(DwarfVersion);
523   if (!DwarfDebugFlags.empty())
524     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
525   if (!DwarfDebugProducer.empty())
526     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
527   if (!DebugCompilationDir.empty())
528     Ctx.setCompilationDir(DebugCompilationDir);
529   else {
530     // If no compilation dir is set, try to use the current directory.
531     SmallString<128> CWD;
532     if (!sys::fs::current_path(CWD))
533       Ctx.setCompilationDir(CWD);
534   }
535   if (!MainFileName.empty())
536     Ctx.setMainFileName(MainFileName);
537
538   // Package up features to be passed to target/subtarget
539   std::string FeaturesStr;
540   if (MAttrs.size()) {
541     SubtargetFeatures Features;
542     for (unsigned i = 0; i != MAttrs.size(); ++i)
543       Features.AddFeature(MAttrs[i]);
544     FeaturesStr = Features.getString();
545   }
546
547   std::unique_ptr<tool_output_file> Out = GetOutputStream();
548   if (!Out)
549     return 1;
550
551   std::unique_ptr<buffer_ostream> BOS;
552   raw_pwrite_stream *OS = &Out->os();
553   std::unique_ptr<MCStreamer> Str;
554
555   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
556   std::unique_ptr<MCSubtargetInfo> STI(
557       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
558
559   MCInstPrinter *IP = nullptr;
560   if (FileType == OFT_AssemblyFile) {
561     IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
562                                         *MAI, *MCII, *MRI);
563
564     if (!IP) {
565       errs()
566           << "error: unable to create instruction printer for target triple '"
567           << TheTriple.normalize() << "' with assembly variant "
568           << OutputAsmVariant << ".\n";
569       return 1;
570     }
571
572     // Set the display preference for hex vs. decimal immediates.
573     IP->setPrintImmHex(PrintImmHex);
574
575     // Set up the AsmStreamer.
576     MCCodeEmitter *CE = nullptr;
577     MCAsmBackend *MAB = nullptr;
578     if (ShowEncoding) {
579       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
580       MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
581     }
582     auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
583     Str.reset(TheTarget->createAsmStreamer(
584         Ctx, std::move(FOut), /*asmverbose*/ true,
585         /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
586
587   } else if (FileType == OFT_Null) {
588     Str.reset(TheTarget->createNullStreamer(Ctx));
589   } else {
590     assert(FileType == OFT_ObjectFile && "Invalid file type!");
591
592     // Don't waste memory on names of temp labels.
593     Ctx.setUseNamesOnTempLabels(false);
594
595     if (!Out->os().supportsSeeking()) {
596       BOS = make_unique<buffer_ostream>(Out->os());
597       OS = BOS.get();
598     }
599
600     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
601     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
602                                                       MCOptions);
603     Str.reset(TheTarget->createMCObjectStreamer(
604         TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
605         MCOptions.MCIncrementalLinkerCompatible,
606         /*DWARFMustBeAtTheEnd*/ false));
607     if (NoExecStack)
608       Str->InitSections(true);
609   }
610
611   int Res = 1;
612   bool disassemble = false;
613   switch (Action) {
614   case AC_AsLex:
615     Res = AsLexInput(SrcMgr, *MAI, Out->os());
616     break;
617   case AC_Assemble:
618     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
619                         *MCII, MCOptions);
620     break;
621   case AC_MDisassemble:
622     assert(IP && "Expected assembly output");
623     IP->setUseMarkup(1);
624     disassemble = true;
625     break;
626   case AC_Disassemble:
627     disassemble = true;
628     break;
629   }
630   if (disassemble)
631     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
632                                     *Buffer, SrcMgr, Out->os());
633
634   // Keep output if no errors.
635   if (Res == 0) Out->keep();
636   return Res;
637 }