LLVMTargetMachine.cpp revision a7b8c2b6a416052bd7b48d3c0d702d266c6ac3a2
1//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===// 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 file implements the LLVMTargetMachine class. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/Target/TargetMachine.h" 15#include "llvm/PassManager.h" 16#include "llvm/Analysis/Verifier.h" 17#include "llvm/Assembly/PrintModulePass.h" 18#include "llvm/CodeGen/AsmPrinter.h" 19#include "llvm/CodeGen/MachineFunctionAnalysis.h" 20#include "llvm/CodeGen/MachineModuleInfo.h" 21#include "llvm/CodeGen/GCStrategy.h" 22#include "llvm/CodeGen/Passes.h" 23#include "llvm/Target/TargetLowering.h" 24#include "llvm/Target/TargetOptions.h" 25#include "llvm/MC/MCAsmInfo.h" 26#include "llvm/MC/MCStreamer.h" 27#include "llvm/Target/TargetAsmInfo.h" 28#include "llvm/Target/TargetData.h" 29#include "llvm/Target/TargetRegistry.h" 30#include "llvm/Transforms/Scalar.h" 31#include "llvm/ADT/OwningPtr.h" 32#include "llvm/Support/CommandLine.h" 33#include "llvm/Support/Debug.h" 34#include "llvm/Support/FormattedStream.h" 35#include "llvm/Support/StandardPasses.h" 36using namespace llvm; 37 38namespace llvm { 39 bool EnableFastISel; 40} 41 42static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden, 43 cl::desc("Disable Post Regalloc")); 44static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 45 cl::desc("Disable branch folding")); 46static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 47 cl::desc("Disable tail duplication")); 48static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 49 cl::desc("Disable pre-register allocation tail duplication")); 50static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden, 51 cl::desc("Disable code placement")); 52static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 53 cl::desc("Disable Stack Slot Coloring")); 54static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 55 cl::desc("Disable Machine LICM")); 56static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 57 cl::Hidden, 58 cl::desc("Disable Machine LICM")); 59static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 60 cl::desc("Disable Machine Sinking")); 61static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 62 cl::desc("Disable Loop Strength Reduction Pass")); 63static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 64 cl::desc("Disable Codegen Prepare")); 65static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 66 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 67static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 68 cl::desc("Print LLVM IR input to isel pass")); 69static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 70 cl::desc("Dump garbage collector data")); 71static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 72 cl::desc("Show encoding in .s output")); 73static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden, 74 cl::desc("Show instruction structure in .s output")); 75static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden, 76 cl::desc("Enable MC API logging")); 77static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 78 cl::desc("Verify generated machine code"), 79 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL)); 80 81static cl::opt<cl::boolOrDefault> 82AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 83 cl::init(cl::BOU_UNSET)); 84 85static bool getVerboseAsm() { 86 switch (AsmVerbose) { 87 default: 88 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); 89 case cl::BOU_TRUE: return true; 90 case cl::BOU_FALSE: return false; 91 } 92} 93 94// Enable or disable FastISel. Both options are needed, because 95// FastISel is enabled by default with -fast, and we wish to be 96// able to enable or disable fast-isel independently from -O0. 97static cl::opt<cl::boolOrDefault> 98EnableFastISelOption("fast-isel", cl::Hidden, 99 cl::desc("Enable the \"fast\" instruction selector")); 100 101LLVMTargetMachine::LLVMTargetMachine(const Target &T, 102 const std::string &Triple) 103 : TargetMachine(T), TargetTriple(Triple) { 104 AsmInfo = T.createAsmInfo(TargetTriple); 105} 106 107// Set the default code model for the JIT for a generic target. 108// FIXME: Is small right here? or .is64Bit() ? Large : Small? 109void LLVMTargetMachine::setCodeModelForJIT() { 110 setCodeModel(CodeModel::Small); 111} 112 113// Set the default code model for static compilation for a generic target. 114void LLVMTargetMachine::setCodeModelForStatic() { 115 setCodeModel(CodeModel::Small); 116} 117 118bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM, 119 formatted_raw_ostream &Out, 120 CodeGenFileType FileType, 121 CodeGenOpt::Level OptLevel, 122 bool DisableVerify) { 123 // Add common CodeGen passes. 124 MCContext *Context = 0; 125 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context)) 126 return true; 127 assert(Context != 0 && "Failed to get MCContext"); 128 129 if (hasMCSaveTempLabels()) 130 Context->setAllowTemporaryLabels(false); 131 132 const MCAsmInfo &MAI = *getMCAsmInfo(); 133 OwningPtr<MCStreamer> AsmStreamer; 134 135 switch (FileType) { 136 default: return true; 137 case CGFT_AssemblyFile: { 138 MCInstPrinter *InstPrinter = 139 getTarget().createMCInstPrinter(*this, MAI.getAssemblerDialect(), MAI); 140 141 // Create a code emitter if asked to show the encoding. 142 MCCodeEmitter *MCE = 0; 143 TargetAsmBackend *TAB = 0; 144 if (ShowMCEncoding) { 145 MCE = getTarget().createCodeEmitter(*this, *Context); 146 TAB = getTarget().createAsmBackend(TargetTriple); 147 } 148 149 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out, 150 getVerboseAsm(), 151 hasMCUseLoc(), 152 InstPrinter, 153 MCE, TAB, 154 ShowMCInst); 155 AsmStreamer.reset(S); 156 break; 157 } 158 case CGFT_ObjectFile: { 159 // Create the code emitter for the target if it exists. If not, .o file 160 // emission fails. 161 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context); 162 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple); 163 if (MCE == 0 || TAB == 0) 164 return true; 165 166 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context, 167 *TAB, Out, MCE, 168 hasMCRelaxAll(), 169 hasMCNoExecStack())); 170 AsmStreamer.get()->InitSections(); 171 break; 172 } 173 case CGFT_Null: 174 // The Null output is intended for use for performance analysis and testing, 175 // not real users. 176 AsmStreamer.reset(createNullStreamer(*Context)); 177 break; 178 } 179 180 if (EnableMCLogging) 181 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs())); 182 183 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 184 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 185 if (Printer == 0) 186 return true; 187 188 // If successful, createAsmPrinter took ownership of AsmStreamer. 189 AsmStreamer.take(); 190 191 PM.add(Printer); 192 193 // Make sure the code model is set. 194 setCodeModelForStatic(); 195 PM.add(createGCInfoDeleter()); 196 return false; 197} 198 199/// addPassesToEmitMachineCode - Add passes to the specified pass manager to 200/// get machine code emitted. This uses a JITCodeEmitter object to handle 201/// actually outputting the machine code and resolving things like the address 202/// of functions. This method should returns true if machine code emission is 203/// not supported. 204/// 205bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM, 206 JITCodeEmitter &JCE, 207 CodeGenOpt::Level OptLevel, 208 bool DisableVerify) { 209 // Make sure the code model is set. 210 setCodeModelForJIT(); 211 212 // Add common CodeGen passes. 213 MCContext *Ctx = 0; 214 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 215 return true; 216 217 addCodeEmitter(PM, OptLevel, JCE); 218 PM.add(createGCInfoDeleter()); 219 220 return false; // success! 221} 222 223/// addPassesToEmitMC - Add passes to the specified pass manager to get 224/// machine code emitted with the MCJIT. This method returns true if machine 225/// code is not supported. It fills the MCContext Ctx pointer which can be 226/// used to build custom MCStreamer. 227/// 228bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, 229 MCContext *&Ctx, 230 raw_ostream &Out, 231 CodeGenOpt::Level OptLevel, 232 bool DisableVerify) { 233 // Add common CodeGen passes. 234 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 235 return true; 236 237 if (hasMCSaveTempLabels()) 238 Ctx->setAllowTemporaryLabels(false); 239 240 // Create the code emitter for the target if it exists. If not, .o file 241 // emission fails. 242 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Ctx); 243 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple); 244 if (MCE == 0 || TAB == 0) 245 return true; 246 247 OwningPtr<MCStreamer> AsmStreamer; 248 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Ctx, 249 *TAB, Out, MCE, 250 hasMCRelaxAll(), 251 hasMCNoExecStack())); 252 AsmStreamer.get()->InitSections(); 253 254 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 255 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 256 if (Printer == 0) 257 return true; 258 259 // If successful, createAsmPrinter took ownership of AsmStreamer. 260 AsmStreamer.take(); 261 262 PM.add(Printer); 263 264 // Make sure the code model is set. 265 setCodeModelForJIT(); 266 267 return false; // success! 268} 269 270static void printNoVerify(PassManagerBase &PM, const char *Banner) { 271 if (PrintMachineCode) 272 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 273} 274 275static void printAndVerify(PassManagerBase &PM, 276 const char *Banner) { 277 if (PrintMachineCode) 278 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 279 280 if (VerifyMachineCode) 281 PM.add(createMachineVerifierPass(Banner)); 282} 283 284/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both 285/// emitting to assembly files or machine code output. 286/// 287bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, 288 CodeGenOpt::Level OptLevel, 289 bool DisableVerify, 290 MCContext *&OutContext) { 291 // Standard LLVM-Level Passes. 292 293 // Basic AliasAnalysis support. 294 createStandardAliasAnalysisPasses(&PM); 295 296 // Before running any passes, run the verifier to determine if the input 297 // coming from the front-end and/or optimizer is valid. 298 if (!DisableVerify) 299 PM.add(createVerifierPass()); 300 301 // Run loop strength reduction before anything else. 302 if (OptLevel != CodeGenOpt::None && !DisableLSR) { 303 PM.add(createLoopStrengthReducePass(getTargetLowering())); 304 if (PrintLSR) 305 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); 306 } 307 308 PM.add(createGCLoweringPass()); 309 310 // Make sure that no unreachable blocks are instruction selected. 311 PM.add(createUnreachableBlockEliminationPass()); 312 313 // Turn exception handling constructs into something the code generators can 314 // handle. 315 switch (getMCAsmInfo()->getExceptionHandlingType()) { 316 case ExceptionHandling::SjLj: 317 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 318 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 319 // catch info can get misplaced when a selector ends up more than one block 320 // removed from the parent invoke(s). This could happen when a landing 321 // pad is shared by multiple invokes and is also a target of a normal 322 // edge from elsewhere. 323 PM.add(createSjLjEHPass(getTargetLowering())); 324 // FALLTHROUGH 325 case ExceptionHandling::DwarfCFI: 326 case ExceptionHandling::DwarfTable: 327 case ExceptionHandling::ARM: 328 PM.add(createDwarfEHPass(this)); 329 break; 330 case ExceptionHandling::None: 331 PM.add(createLowerInvokePass(getTargetLowering())); 332 333 // The lower invoke pass may create unreachable code. Remove it. 334 PM.add(createUnreachableBlockEliminationPass()); 335 break; 336 } 337 338 if (OptLevel != CodeGenOpt::None && !DisableCGP) 339 PM.add(createCodeGenPreparePass(getTargetLowering())); 340 341 PM.add(createStackProtectorPass(getTargetLowering())); 342 343 addPreISel(PM, OptLevel); 344 345 if (PrintISelInput) 346 PM.add(createPrintFunctionPass("\n\n" 347 "*** Final LLVM Code input to ISel ***\n", 348 &dbgs())); 349 350 // All passes which modify the LLVM IR are now complete; run the verifier 351 // to ensure that the IR is valid. 352 if (!DisableVerify) 353 PM.add(createVerifierPass()); 354 355 // Standard Lower-Level Passes. 356 357 // Install a MachineModuleInfo class, which is an immutable pass that holds 358 // all the per-module stuff we're generating, including MCContext. 359 TargetAsmInfo *TAI = new TargetAsmInfo(*this); 360 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), TAI); 361 PM.add(MMI); 362 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref. 363 364 // Set up a MachineFunction for the rest of CodeGen to work on. 365 PM.add(new MachineFunctionAnalysis(*this, OptLevel)); 366 367 // Enable FastISel with -fast, but allow that to be overridden. 368 if (EnableFastISelOption == cl::BOU_TRUE || 369 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE)) 370 EnableFastISel = true; 371 372 // Ask the target for an isel. 373 if (addInstSelector(PM, OptLevel)) 374 return true; 375 376 // Print the instruction selected machine code... 377 printAndVerify(PM, "After Instruction Selection"); 378 379 // Expand pseudo-instructions emitted by ISel. 380 PM.add(createExpandISelPseudosPass()); 381 382 // Optimize PHIs before DCE: removing dead PHI cycles may make more 383 // instructions dead. 384 if (OptLevel != CodeGenOpt::None) 385 PM.add(createOptimizePHIsPass()); 386 387 // If the target requests it, assign local variables to stack slots relative 388 // to one another and simplify frame index references where possible. 389 PM.add(createLocalStackSlotAllocationPass()); 390 391 if (OptLevel != CodeGenOpt::None) { 392 // With optimization, dead code should already be eliminated. However 393 // there is one known exception: lowered code for arguments that are only 394 // used by tail calls, where the tail calls reuse the incoming stack 395 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 396 PM.add(createDeadMachineInstructionElimPass()); 397 printAndVerify(PM, "After codegen DCE pass"); 398 399 if (!DisableMachineLICM) 400 PM.add(createMachineLICMPass()); 401 PM.add(createMachineCSEPass()); 402 if (!DisableMachineSink) 403 PM.add(createMachineSinkingPass()); 404 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes"); 405 406 PM.add(createPeepholeOptimizerPass()); 407 printAndVerify(PM, "After codegen peephole optimization pass"); 408 } 409 410 // Pre-ra tail duplication. 411 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) { 412 PM.add(createTailDuplicatePass(true)); 413 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate"); 414 } 415 416 // Run pre-ra passes. 417 if (addPreRegAlloc(PM, OptLevel)) 418 printAndVerify(PM, "After PreRegAlloc passes"); 419 420 // Perform register allocation. 421 PM.add(createRegisterAllocator(OptLevel)); 422 printAndVerify(PM, "After Register Allocation"); 423 424 // Perform stack slot coloring and post-ra machine LICM. 425 if (OptLevel != CodeGenOpt::None) { 426 // FIXME: Re-enable coloring with register when it's capable of adding 427 // kill markers. 428 if (!DisableSSC) 429 PM.add(createStackSlotColoringPass(false)); 430 431 // Run post-ra machine LICM to hoist reloads / remats. 432 if (!DisablePostRAMachineLICM) 433 PM.add(createMachineLICMPass(false)); 434 435 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM"); 436 } 437 438 // Run post-ra passes. 439 if (addPostRegAlloc(PM, OptLevel)) 440 printAndVerify(PM, "After PostRegAlloc passes"); 441 442 PM.add(createLowerSubregsPass()); 443 printAndVerify(PM, "After LowerSubregs"); 444 445 // Insert prolog/epilog code. Eliminate abstract frame index references... 446 PM.add(createPrologEpilogCodeInserter()); 447 printAndVerify(PM, "After PrologEpilogCodeInserter"); 448 449 // Run pre-sched2 passes. 450 if (addPreSched2(PM, OptLevel)) 451 printAndVerify(PM, "After PreSched2 passes"); 452 453 // Second pass scheduler. 454 if (OptLevel != CodeGenOpt::None && !DisablePostRA) { 455 PM.add(createPostRAScheduler(OptLevel)); 456 printAndVerify(PM, "After PostRAScheduler"); 457 } 458 459 // Branch folding must be run after regalloc and prolog/epilog insertion. 460 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) { 461 PM.add(createBranchFoldingPass(getEnableTailMergeDefault())); 462 printNoVerify(PM, "After BranchFolding"); 463 } 464 465 // Tail duplication. 466 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) { 467 PM.add(createTailDuplicatePass(false)); 468 printNoVerify(PM, "After TailDuplicate"); 469 } 470 471 PM.add(createGCMachineCodeAnalysisPass()); 472 473 if (PrintGCInfo) 474 PM.add(createGCInfoPrinter(dbgs())); 475 476 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) { 477 PM.add(createCodePlacementOptPass()); 478 printNoVerify(PM, "After CodePlacementOpt"); 479 } 480 481 if (addPreEmitPass(PM, OptLevel)) 482 printNoVerify(PM, "After PreEmit passes"); 483 484 return false; 485} 486