1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// 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 llc code generator driver. It provides a convenient 11 // command-line interface for generating native assembly-language code 12 // or C code, given LLVM bitcode. 13 // 14 //===----------------------------------------------------------------------===// 15 16 17 #include "llvm/ADT/Triple.h" 18 #include "llvm/CodeGen/CommandFlags.h" 19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 20 #include "llvm/CodeGen/LinkAllCodegenComponents.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/IRPrintingPasses.h" 23 #include "llvm/IR/LLVMContext.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/IRReader/IRReader.h" 26 #include "llvm/MC/SubtargetFeature.h" 27 #include "llvm/Pass.h" 28 #include "llvm/PassManager.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/FileSystem.h" 32 #include "llvm/Support/FormattedStream.h" 33 #include "llvm/Support/Host.h" 34 #include "llvm/Support/ManagedStatic.h" 35 #include "llvm/Support/PluginLoader.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 #include "llvm/Target/TargetLibraryInfo.h" 43 #include "llvm/Target/TargetMachine.h" 44 #include <memory> 45 using namespace llvm; 46 47 // General options for llc. Other pass-specific options are specified 48 // within the corresponding llc passes, and target-specific options 49 // and back-end code generation options are specified with the target machine. 50 // 51 static cl::opt<std::string> 52 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 53 54 static cl::opt<std::string> 55 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 56 57 static cl::opt<unsigned> 58 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 59 cl::value_desc("N"), 60 cl::desc("Repeat compilation N times for timing")); 61 62 static cl::opt<bool> 63 NoIntegratedAssembler("no-integrated-as", cl::Hidden, 64 cl::desc("Disable integrated assembler")); 65 66 // Determine optimization level. 67 static cl::opt<char> 68 OptLevel("O", 69 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 70 "(default = '-O2')"), 71 cl::Prefix, 72 cl::ZeroOrMore, 73 cl::init(' ')); 74 75 static cl::opt<std::string> 76 TargetTriple("mtriple", cl::desc("Override target triple for module")); 77 78 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 79 cl::desc("Do not verify input module")); 80 81 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", 82 cl::desc("Disable simplify-libcalls")); 83 84 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 85 cl::desc("Show encoding in .s output")); 86 87 static cl::opt<bool> EnableDwarfDirectory( 88 "enable-dwarf-directory", cl::Hidden, 89 cl::desc("Use .file directives with an explicit directory.")); 90 91 static cl::opt<bool> AsmVerbose("asm-verbose", 92 cl::desc("Add comments to directives."), 93 cl::init(true)); 94 95 static int compileModule(char **, LLVMContext &); 96 97 // GetFileNameRoot - Helper function to get the basename of a filename. 98 static inline std::string 99 GetFileNameRoot(const std::string &InputFilename) { 100 std::string IFN = InputFilename; 101 std::string outputFilename; 102 int Len = IFN.length(); 103 if ((Len > 2) && 104 IFN[Len-3] == '.' && 105 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') || 106 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) { 107 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ 108 } else { 109 outputFilename = IFN; 110 } 111 return outputFilename; 112 } 113 114 static tool_output_file *GetOutputStream(const char *TargetName, 115 Triple::OSType OS, 116 const char *ProgName) { 117 // If we don't yet have an output filename, make one. 118 if (OutputFilename.empty()) { 119 if (InputFilename == "-") 120 OutputFilename = "-"; 121 else { 122 OutputFilename = GetFileNameRoot(InputFilename); 123 124 switch (FileType) { 125 case TargetMachine::CGFT_AssemblyFile: 126 if (TargetName[0] == 'c') { 127 if (TargetName[1] == 0) 128 OutputFilename += ".cbe.c"; 129 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 130 OutputFilename += ".cpp"; 131 else 132 OutputFilename += ".s"; 133 } else 134 OutputFilename += ".s"; 135 break; 136 case TargetMachine::CGFT_ObjectFile: 137 if (OS == Triple::Win32) 138 OutputFilename += ".obj"; 139 else 140 OutputFilename += ".o"; 141 break; 142 case TargetMachine::CGFT_Null: 143 OutputFilename += ".null"; 144 break; 145 } 146 } 147 } 148 149 // Decide if we need "binary" output. 150 bool Binary = false; 151 switch (FileType) { 152 case TargetMachine::CGFT_AssemblyFile: 153 break; 154 case TargetMachine::CGFT_ObjectFile: 155 case TargetMachine::CGFT_Null: 156 Binary = true; 157 break; 158 } 159 160 // Open the file. 161 std::string error; 162 sys::fs::OpenFlags OpenFlags = sys::fs::F_None; 163 if (!Binary) 164 OpenFlags |= sys::fs::F_Text; 165 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error, 166 OpenFlags); 167 if (!error.empty()) { 168 errs() << error << '\n'; 169 delete FDOut; 170 return nullptr; 171 } 172 173 return FDOut; 174 } 175 176 // main - Entry point for the llc compiler. 177 // 178 int main(int argc, char **argv) { 179 sys::PrintStackTraceOnErrorSignal(); 180 PrettyStackTraceProgram X(argc, argv); 181 182 // Enable debug stream buffering. 183 EnableDebugBuffering = true; 184 185 LLVMContext &Context = getGlobalContext(); 186 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 187 188 // Initialize targets first, so that --version shows registered targets. 189 InitializeAllTargets(); 190 InitializeAllTargetMCs(); 191 InitializeAllAsmPrinters(); 192 InitializeAllAsmParsers(); 193 194 // Initialize codegen and IR passes used by llc so that the -print-after, 195 // -print-before, and -stop-after options work. 196 PassRegistry *Registry = PassRegistry::getPassRegistry(); 197 initializeCore(*Registry); 198 initializeCodeGen(*Registry); 199 initializeLoopStrengthReducePass(*Registry); 200 initializeLowerIntrinsicsPass(*Registry); 201 initializeUnreachableBlockElimPass(*Registry); 202 203 // Register the target printer for --version. 204 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 205 206 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 207 208 // Compile the module TimeCompilations times to give better compile time 209 // metrics. 210 for (unsigned I = TimeCompilations; I; --I) 211 if (int RetVal = compileModule(argv, Context)) 212 return RetVal; 213 return 0; 214 } 215 216 static int compileModule(char **argv, LLVMContext &Context) { 217 // Load the module to be compiled... 218 SMDiagnostic Err; 219 std::unique_ptr<Module> M; 220 Module *mod = nullptr; 221 Triple TheTriple; 222 223 bool SkipModule = MCPU == "help" || 224 (!MAttrs.empty() && MAttrs.front() == "help"); 225 226 // If user asked for the 'native' CPU, autodetect here. If autodection fails, 227 // this will set the CPU to an empty string which tells the target to 228 // pick a basic default. 229 if (MCPU == "native") 230 MCPU = sys::getHostCPUName(); 231 232 // If user just wants to list available options, skip module loading 233 if (!SkipModule) { 234 M.reset(ParseIRFile(InputFilename, Err, Context)); 235 mod = M.get(); 236 if (mod == nullptr) { 237 Err.print(argv[0], errs()); 238 return 1; 239 } 240 241 // If we are supposed to override the target triple, do so now. 242 if (!TargetTriple.empty()) 243 mod->setTargetTriple(Triple::normalize(TargetTriple)); 244 TheTriple = Triple(mod->getTargetTriple()); 245 } else { 246 TheTriple = Triple(Triple::normalize(TargetTriple)); 247 } 248 249 if (TheTriple.getTriple().empty()) 250 TheTriple.setTriple(sys::getDefaultTargetTriple()); 251 252 // Get the target specific parser. 253 std::string Error; 254 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 255 Error); 256 if (!TheTarget) { 257 errs() << argv[0] << ": " << Error; 258 return 1; 259 } 260 261 // Package up features to be passed to target/subtarget 262 std::string FeaturesStr; 263 if (MAttrs.size()) { 264 SubtargetFeatures Features; 265 for (unsigned i = 0; i != MAttrs.size(); ++i) 266 Features.AddFeature(MAttrs[i]); 267 FeaturesStr = Features.getString(); 268 } 269 270 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 271 switch (OptLevel) { 272 default: 273 errs() << argv[0] << ": invalid optimization level.\n"; 274 return 1; 275 case ' ': break; 276 case '0': OLvl = CodeGenOpt::None; break; 277 case '1': OLvl = CodeGenOpt::Less; break; 278 case '2': OLvl = CodeGenOpt::Default; break; 279 case '3': OLvl = CodeGenOpt::Aggressive; break; 280 } 281 282 TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 283 Options.DisableIntegratedAS = NoIntegratedAssembler; 284 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 285 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 286 Options.MCOptions.AsmVerbose = AsmVerbose; 287 288 std::unique_ptr<TargetMachine> target( 289 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr, 290 Options, RelocModel, CMModel, OLvl)); 291 assert(target.get() && "Could not allocate target machine!"); 292 293 // If we don't have a module then just exit now. We do this down 294 // here since the CPU/Feature help is underneath the target machine 295 // creation. 296 if (SkipModule) 297 return 0; 298 299 assert(mod && "Should have exited if we didn't have a module!"); 300 TargetMachine &Target = *target.get(); 301 302 if (GenerateSoftFloatCalls) 303 FloatABIForCalls = FloatABI::Soft; 304 305 // Figure out where we are going to send the output. 306 std::unique_ptr<tool_output_file> Out( 307 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0])); 308 if (!Out) return 1; 309 310 // Build up all of the passes that we want to do to the module. 311 PassManager PM; 312 313 // Add an appropriate TargetLibraryInfo pass for the module's triple. 314 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple); 315 if (DisableSimplifyLibCalls) 316 TLI->disableAllFunctions(); 317 PM.add(TLI); 318 319 // Add the target data from the target machine, if it exists, or the module. 320 if (const DataLayout *DL = Target.getDataLayout()) 321 mod->setDataLayout(DL); 322 PM.add(new DataLayoutPass(mod)); 323 324 if (RelaxAll.getNumOccurrences() > 0 && 325 FileType != TargetMachine::CGFT_ObjectFile) 326 errs() << argv[0] 327 << ": warning: ignoring -mc-relax-all because filetype != obj"; 328 329 { 330 formatted_raw_ostream FOS(Out->os()); 331 332 AnalysisID StartAfterID = nullptr; 333 AnalysisID StopAfterID = nullptr; 334 const PassRegistry *PR = PassRegistry::getPassRegistry(); 335 if (!StartAfter.empty()) { 336 const PassInfo *PI = PR->getPassInfo(StartAfter); 337 if (!PI) { 338 errs() << argv[0] << ": start-after pass is not registered.\n"; 339 return 1; 340 } 341 StartAfterID = PI->getTypeInfo(); 342 } 343 if (!StopAfter.empty()) { 344 const PassInfo *PI = PR->getPassInfo(StopAfter); 345 if (!PI) { 346 errs() << argv[0] << ": stop-after pass is not registered.\n"; 347 return 1; 348 } 349 StopAfterID = PI->getTypeInfo(); 350 } 351 352 // Ask the target to add backend passes as necessary. 353 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify, 354 StartAfterID, StopAfterID)) { 355 errs() << argv[0] << ": target does not support generation of this" 356 << " file type!\n"; 357 return 1; 358 } 359 360 // Before executing passes, print the final values of the LLVM options. 361 cl::PrintOptionValues(); 362 363 PM.run(*mod); 364 } 365 366 // Declare success. 367 Out->keep(); 368 369 return 0; 370 } 371