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