cc1as_main.cpp revision e9122a36c4c951c4cdce842dc8caf20874908cfd
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 15#include "clang/Basic/Diagnostic.h" 16#include "clang/Driver/Arg.h" 17#include "clang/Driver/ArgList.h" 18#include "clang/Driver/DriverDiagnostic.h" 19#include "clang/Driver/CC1AsOptions.h" 20#include "clang/Driver/OptTable.h" 21#include "clang/Driver/Options.h" 22#include "clang/Frontend/DiagnosticOptions.h" 23#include "clang/Frontend/FrontendDiagnostic.h" 24#include "clang/Frontend/TextDiagnosticPrinter.h" 25#include "llvm/ADT/OwningPtr.h" 26#include "llvm/ADT/StringSwitch.h" 27#include "llvm/MC/MCParser/MCAsmParser.h" 28#include "llvm/MC/MCAsmInfo.h" 29#include "llvm/MC/MCCodeEmitter.h" 30#include "llvm/MC/MCContext.h" 31#include "llvm/MC/MCStreamer.h" 32#include "llvm/Support/CommandLine.h" 33#include "llvm/Support/FormattedStream.h" 34#include "llvm/Support/ErrorHandling.h" 35#include "llvm/Support/ManagedStatic.h" 36#include "llvm/Support/MemoryBuffer.h" 37#include "llvm/Support/PrettyStackTrace.h" 38#include "llvm/Support/SourceMgr.h" 39#include "llvm/Support/Timer.h" 40#include "llvm/Support/raw_ostream.h" 41#include "llvm/System/Host.h" 42#include "llvm/System/Path.h" 43#include "llvm/System/Signals.h" 44#include "llvm/Target/TargetAsmBackend.h" 45#include "llvm/Target/TargetAsmParser.h" 46#include "llvm/Target/TargetData.h" 47#include "llvm/Target/TargetMachine.h" 48#include "llvm/Target/TargetRegistry.h" 49#include "llvm/Target/TargetSelect.h" 50using namespace clang; 51using namespace clang::driver; 52using namespace llvm; 53 54namespace { 55 56/// \brief Helper class for representing a single invocation of the assembler. 57struct AssemblerInvocation { 58 /// @name Target Options 59 /// @{ 60 61 std::string Triple; 62 63 /// @} 64 /// @name Language Options 65 /// @{ 66 67 std::vector<std::string> IncludePaths; 68 unsigned NoInitialTextSection : 1; 69 70 /// @} 71 /// @name Frontend Options 72 /// @{ 73 74 std::string InputFile; 75 std::vector<std::string> LLVMArgs; 76 std::string OutputPath; 77 enum FileType { 78 FT_Asm, ///< Assembly (.s) output, transliterate mode. 79 FT_Null, ///< No output, for timing purposes. 80 FT_Obj ///< Object file output. 81 }; 82 FileType OutputType; 83 unsigned ShowHelp : 1; 84 unsigned ShowVersion : 1; 85 86 /// @} 87 /// @name Transliterate Options 88 /// @{ 89 90 unsigned OutputAsmVariant; 91 unsigned ShowEncoding : 1; 92 unsigned ShowInst : 1; 93 94 /// @} 95 /// @name Assembler Options 96 /// @{ 97 98 unsigned RelaxAll : 1; 99 100 /// @} 101 102public: 103 AssemblerInvocation() { 104 Triple = ""; 105 NoInitialTextSection = 0; 106 InputFile = "-"; 107 OutputPath = "-"; 108 OutputType = FT_Asm; 109 OutputAsmVariant = 0; 110 ShowInst = 0; 111 ShowEncoding = 0; 112 RelaxAll = 0; 113 } 114 115 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin, 116 const char **ArgEnd, Diagnostic &Diags); 117}; 118 119} 120 121void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts, 122 const char **ArgBegin, 123 const char **ArgEnd, 124 Diagnostic &Diags) { 125 using namespace clang::driver::cc1asoptions; 126 // Parse the arguments. 127 OwningPtr<OptTable> OptTbl(createCC1AsOptTable()); 128 unsigned MissingArgIndex, MissingArgCount; 129 OwningPtr<InputArgList> Args( 130 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount)); 131 132 // Check for missing argument error. 133 if (MissingArgCount) 134 Diags.Report(diag::err_drv_missing_argument) 135 << Args->getArgString(MissingArgIndex) << MissingArgCount; 136 137 // Issue errors on unknown arguments. 138 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN), 139 ie = Args->filtered_end(); it != ie; ++it) 140 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args); 141 142 // Construct the invocation. 143 144 // Target Options 145 Opts.Triple = Args->getLastArgValue(OPT_triple); 146 if (Opts.Triple.empty()) // Use the host triple if unspecified. 147 Opts.Triple = sys::getHostTriple(); 148 149 // Language Options 150 Opts.IncludePaths = Args->getAllArgValues(OPT_I); 151 Opts.NoInitialTextSection = Args->hasArg(OPT_n); 152 153 // Frontend Options 154 if (Args->hasArg(OPT_INPUT)) { 155 bool First = true; 156 for (arg_iterator it = Args->filtered_begin(OPT_INPUT), 157 ie = Args->filtered_end(); it != ie; ++it, First=false) { 158 const Arg *A = it; 159 if (First) 160 Opts.InputFile = A->getValue(*Args); 161 else 162 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args); 163 } 164 } 165 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm); 166 Opts.OutputPath = Args->getLastArgValue(OPT_o); 167 if (Arg *A = Args->getLastArg(OPT_filetype)) { 168 StringRef Name = A->getValue(*Args); 169 unsigned OutputType = StringSwitch<unsigned>(Name) 170 .Case("asm", FT_Asm) 171 .Case("null", FT_Null) 172 .Case("obj", FT_Obj) 173 .Default(~0U); 174 if (OutputType == ~0U) 175 Diags.Report(diag::err_drv_invalid_value) 176 << A->getAsString(*Args) << Name; 177 else 178 Opts.OutputType = FileType(OutputType); 179 } 180 Opts.ShowHelp = Args->hasArg(OPT_help); 181 Opts.ShowVersion = Args->hasArg(OPT_version); 182 183 // Transliterate Options 184 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant, 185 0, Diags); 186 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding); 187 Opts.ShowInst = Args->hasArg(OPT_show_inst); 188 189 // Assemble Options 190 Opts.RelaxAll = Args->hasArg(OPT_relax_all); 191} 192 193static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts, 194 Diagnostic &Diags, 195 bool Binary) { 196 if (Opts.OutputPath.empty()) 197 Opts.OutputPath = "-"; 198 199 // Make sure that the Out file gets unlinked from the disk if we get a 200 // SIGINT. 201 if (Opts.OutputPath != "-") 202 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath)); 203 204 std::string Error; 205 raw_fd_ostream *Out = 206 new raw_fd_ostream(Opts.OutputPath.c_str(), Error, 207 (Binary ? raw_fd_ostream::F_Binary : 0)); 208 if (!Error.empty()) { 209 Diags.Report(diag::err_fe_unable_to_open_output) 210 << Opts.OutputPath << Error; 211 return 0; 212 } 213 214 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM); 215} 216 217static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) { 218 // Get the target specific parser. 219 std::string Error; 220 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error)); 221 if (!TheTarget) { 222 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; 223 return false; 224 } 225 226 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, &Error); 227 if (Buffer == 0) { 228 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile; 229 return false; 230 } 231 232 SourceMgr SrcMgr; 233 234 // Tell SrcMgr about this buffer, which is what the parser will pick up. 235 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 236 237 // Record the location of the include directories so that the lexer can find 238 // it later. 239 SrcMgr.setIncludeDirs(Opts.IncludePaths); 240 241 OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple)); 242 assert(MAI && "Unable to create target asm info!"); 243 244 MCContext Ctx(*MAI); 245 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj; 246 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary); 247 if (!Out) 248 return false; 249 250 // FIXME: We shouldn't need to do this (and link in codegen). 251 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, "")); 252 if (!TM) { 253 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; 254 return false; 255 } 256 257 OwningPtr<MCCodeEmitter> CE; 258 OwningPtr<MCStreamer> Str; 259 OwningPtr<TargetAsmBackend> TAB; 260 261 if (Opts.OutputType == AssemblerInvocation::FT_Asm) { 262 MCInstPrinter *IP = 263 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI); 264 if (Opts.ShowEncoding) 265 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx)); 266 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(), 267 /*asmverbose*/true, IP, CE.get(), 268 Opts.ShowInst)); 269 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) { 270 Str.reset(createNullStreamer(Ctx)); 271 } else { 272 assert(Opts.OutputType == AssemblerInvocation::FT_Obj && 273 "Invalid file type!"); 274 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx)); 275 TAB.reset(TheTarget->createAsmBackend(Opts.Triple)); 276 Str.reset(createMachOStreamer(Ctx, *TAB, *Out, CE.get(), Opts.RelaxAll)); 277 } 278 279 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx, 280 *Str.get(), *MAI)); 281 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM)); 282 if (!TAP) { 283 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; 284 return false; 285 } 286 287 Parser->setTargetParser(*TAP.get()); 288 289 bool Success = !Parser->Run(Opts.NoInitialTextSection); 290 291 // Close the output. 292 delete Out; 293 294 // Delete output on errors. 295 if (!Success && Opts.OutputPath != "-") 296 sys::Path(Opts.OutputPath).eraseFromDisk(); 297 298 return Success; 299} 300 301static void LLVMErrorHandler(void *UserData, const std::string &Message) { 302 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData); 303 304 Diags.Report(diag::err_fe_error_backend) << Message; 305 306 // We cannot recover from llvm errors. 307 exit(1); 308} 309 310int cc1as_main(const char **ArgBegin, const char **ArgEnd, 311 const char *Argv0, void *MainAddr) { 312 // Print a stack trace if we signal out. 313 sys::PrintStackTraceOnErrorSignal(); 314 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin); 315 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 316 317 // Initialize targets and assembly printers/parsers. 318 InitializeAllTargetInfos(); 319 // FIXME: We shouldn't need to initialize the Target(Machine)s. 320 InitializeAllTargets(); 321 InitializeAllAsmPrinters(); 322 InitializeAllAsmParsers(); 323 324 // Construct our diagnostic client. 325 TextDiagnosticPrinter DiagClient(errs(), DiagnosticOptions()); 326 DiagClient.setPrefix("clang -cc1as"); 327 Diagnostic Diags(&DiagClient); 328 329 // Set an error handler, so that any LLVM backend diagnostics go through our 330 // error handler. 331 install_fatal_error_handler(LLVMErrorHandler, 332 static_cast<void*>(&Diags)); 333 334 // Parse the arguments. 335 AssemblerInvocation Asm; 336 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags); 337 338 // Honor -help. 339 if (Asm.ShowHelp) { 340 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable()); 341 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler"); 342 return 0; 343 } 344 345 // Honor -version. 346 // 347 // FIXME: Use a better -version message? 348 if (Asm.ShowVersion) { 349 llvm::cl::PrintVersionMessage(); 350 return 0; 351 } 352 353 // Honor -mllvm. 354 // 355 // FIXME: Remove this, one day. 356 if (!Asm.LLVMArgs.empty()) { 357 unsigned NumArgs = Asm.LLVMArgs.size(); 358 const char **Args = new const char*[NumArgs + 2]; 359 Args[0] = "clang (LLVM option parsing)"; 360 for (unsigned i = 0; i != NumArgs; ++i) 361 Args[i + 1] = Asm.LLVMArgs[i].c_str(); 362 Args[NumArgs + 1] = 0; 363 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args)); 364 } 365 366 // Execute the invocation, unless there were parsing errors. 367 bool Success = false; 368 if (!Diags.getNumErrors()) 369 Success = ExecuteAssembler(Asm, Diags); 370 371 // If any timers were active but haven't been destroyed yet, print their 372 // results now. 373 TimerGroup::printAll(errs()); 374 375 return !Success; 376} 377