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