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