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