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