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