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