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 using namespace llvm; 34 35 namespace llvm { 36 bool EnableFastISel; 37 } 38 39 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden, 40 cl::desc("Disable Post Regalloc")); 41 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 42 cl::desc("Disable branch folding")); 43 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 44 cl::desc("Disable tail duplication")); 45 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 46 cl::desc("Disable pre-register allocation tail duplication")); 47 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden, 48 cl::desc("Disable code placement")); 49 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 50 cl::desc("Disable Stack Slot Coloring")); 51 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 52 cl::desc("Disable Machine LICM")); 53 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 54 cl::Hidden, 55 cl::desc("Disable Machine LICM")); 56 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 57 cl::desc("Disable Machine Sinking")); 58 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 59 cl::desc("Disable Loop Strength Reduction Pass")); 60 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 61 cl::desc("Disable Codegen Prepare")); 62 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 63 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 64 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 65 cl::desc("Print LLVM IR input to isel pass")); 66 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 67 cl::desc("Dump garbage collector data")); 68 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 69 cl::desc("Verify generated machine code"), 70 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL)); 71 72 static cl::opt<cl::boolOrDefault> 73 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 74 cl::init(cl::BOU_UNSET)); 75 76 static bool getVerboseAsm() { 77 switch (AsmVerbose) { 78 default: 79 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); 80 case cl::BOU_TRUE: return true; 81 case cl::BOU_FALSE: return false; 82 } 83 } 84 85 // Enable or disable FastISel. Both options are needed, because 86 // FastISel is enabled by default with -fast, and we wish to be 87 // able to enable or disable fast-isel independently from -O0. 88 static cl::opt<cl::boolOrDefault> 89 EnableFastISelOption("fast-isel", cl::Hidden, 90 cl::desc("Enable the \"fast\" instruction selector")); 91 92 // Enable or disable an experimental optimization to split GEPs 93 // and run a special GVN pass which does not examine loads, in 94 // an effort to factor out redundancy implicit in complex GEPs. 95 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden, 96 cl::desc("Split GEPs and run no-load GVN")); 97 98 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 99 const std::string &Triple) 100 : TargetMachine(T), TargetTriple(Triple) { 101 AsmInfo = T.createAsmInfo(TargetTriple); 102 } 103 104 // Set the default code model for the JIT for a generic target. 105 // FIXME: Is small right here? or .is64Bit() ? Large : Small? 106 void LLVMTargetMachine::setCodeModelForJIT() { 107 setCodeModel(CodeModel::Small); 108 } 109 110 // Set the default code model for static compilation for a generic target. 111 void LLVMTargetMachine::setCodeModelForStatic() { 112 setCodeModel(CodeModel::Small); 113 } 114 115 bool 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 const MCAsmInfo &MAI = *getMCAsmInfo(); 127 OwningPtr<MCStreamer> AsmStreamer; 128 129 switch (FileType) { 130 default: return true; 131 case CGFT_AssemblyFile: { 132 MCInstPrinter *InstPrinter = 133 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI); 134 AsmStreamer.reset(createAsmStreamer(*Context, Out, 135 getTargetData()->isLittleEndian(), 136 getVerboseAsm(), InstPrinter, 137 /*codeemitter*/0)); 138 break; 139 } 140 case CGFT_ObjectFile: { 141 // Create the code emitter for the target if it exists. If not, .o file 142 // emission fails. 143 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context); 144 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple); 145 if (MCE == 0 || TAB == 0) 146 return true; 147 148 AsmStreamer.reset(createMachOStreamer(*Context, *TAB, Out, MCE)); 149 break; 150 } 151 case CGFT_Null: 152 // The Null output is intended for use for performance analysis and testing, 153 // not real users. 154 AsmStreamer.reset(createNullStreamer(*Context)); 155 break; 156 } 157 158 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 159 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 160 if (Printer == 0) 161 return true; 162 163 // If successful, createAsmPrinter took ownership of AsmStreamer. 164 AsmStreamer.take(); 165 166 PM.add(Printer); 167 168 // Make sure the code model is set. 169 setCodeModelForStatic(); 170 PM.add(createGCInfoDeleter()); 171 return false; 172 } 173 174 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to 175 /// get machine code emitted. This uses a JITCodeEmitter object to handle 176 /// actually outputting the machine code and resolving things like the address 177 /// of functions. This method should returns true if machine code emission is 178 /// not supported. 179 /// 180 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM, 181 JITCodeEmitter &JCE, 182 CodeGenOpt::Level OptLevel, 183 bool DisableVerify) { 184 // Make sure the code model is set. 185 setCodeModelForJIT(); 186 187 // Add common CodeGen passes. 188 MCContext *Ctx = 0; 189 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 190 return true; 191 192 addCodeEmitter(PM, OptLevel, JCE); 193 PM.add(createGCInfoDeleter()); 194 195 return false; // success! 196 } 197 198 static void printNoVerify(PassManagerBase &PM, const char *Banner) { 199 if (PrintMachineCode) 200 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 201 } 202 203 static void printAndVerify(PassManagerBase &PM, 204 const char *Banner, 205 bool allowDoubleDefs = false) { 206 if (PrintMachineCode) 207 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 208 209 if (VerifyMachineCode) 210 PM.add(createMachineVerifierPass(allowDoubleDefs)); 211 } 212 213 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both 214 /// emitting to assembly files or machine code output. 215 /// 216 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, 217 CodeGenOpt::Level OptLevel, 218 bool DisableVerify, 219 MCContext *&OutContext) { 220 // Standard LLVM-Level Passes. 221 222 // Before running any passes, run the verifier to determine if the input 223 // coming from the front-end and/or optimizer is valid. 224 if (!DisableVerify) 225 PM.add(createVerifierPass()); 226 227 // Optionally, tun split-GEPs and no-load GVN. 228 if (EnableSplitGEPGVN) { 229 PM.add(createGEPSplitterPass()); 230 PM.add(createGVNPass(/*NoLoads=*/true)); 231 } 232 233 // Run loop strength reduction before anything else. 234 if (OptLevel != CodeGenOpt::None && !DisableLSR) { 235 PM.add(createLoopStrengthReducePass(getTargetLowering())); 236 if (PrintLSR) 237 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); 238 } 239 240 // Turn exception handling constructs into something the code generators can 241 // handle. 242 switch (getMCAsmInfo()->getExceptionHandlingType()) { 243 case ExceptionHandling::SjLj: 244 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 245 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 246 // catch info can get misplaced when a selector ends up more than one block 247 // removed from the parent invoke(s). This could happen when a landing 248 // pad is shared by multiple invokes and is also a target of a normal 249 // edge from elsewhere. 250 PM.add(createSjLjEHPass(getTargetLowering())); 251 PM.add(createDwarfEHPass(this, OptLevel==CodeGenOpt::None)); 252 break; 253 case ExceptionHandling::Dwarf: 254 PM.add(createDwarfEHPass(this, OptLevel==CodeGenOpt::None)); 255 break; 256 case ExceptionHandling::None: 257 PM.add(createLowerInvokePass(getTargetLowering())); 258 break; 259 } 260 261 PM.add(createGCLoweringPass()); 262 263 // Make sure that no unreachable blocks are instruction selected. 264 PM.add(createUnreachableBlockEliminationPass()); 265 266 if (OptLevel != CodeGenOpt::None && !DisableCGP) 267 PM.add(createCodeGenPreparePass(getTargetLowering())); 268 269 PM.add(createStackProtectorPass(getTargetLowering())); 270 271 if (PrintISelInput) 272 PM.add(createPrintFunctionPass("\n\n" 273 "*** Final LLVM Code input to ISel ***\n", 274 &dbgs())); 275 276 // All passes which modify the LLVM IR are now complete; run the verifier 277 // to ensure that the IR is valid. 278 if (!DisableVerify) 279 PM.add(createVerifierPass()); 280 281 // Standard Lower-Level Passes. 282 283 // Install a MachineModuleInfo class, which is an immutable pass that holds 284 // all the per-module stuff we're generating, including MCContext. 285 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo()); 286 PM.add(MMI); 287 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref. 288 289 290 // Set up a MachineFunction for the rest of CodeGen to work on. 291 PM.add(new MachineFunctionAnalysis(*this, OptLevel)); 292 293 // Enable FastISel with -fast, but allow that to be overridden. 294 if (EnableFastISelOption == cl::BOU_TRUE || 295 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE)) 296 EnableFastISel = true; 297 298 // Ask the target for an isel. 299 if (addInstSelector(PM, OptLevel)) 300 return true; 301 302 // Print the instruction selected machine code... 303 printAndVerify(PM, "After Instruction Selection", 304 /* allowDoubleDefs= */ true); 305 306 // Optimize PHIs before DCE: removing dead PHI cycles may make more 307 // instructions dead. 308 if (OptLevel != CodeGenOpt::None) 309 PM.add(createOptimizePHIsPass()); 310 311 // Delete dead machine instructions regardless of optimization level. 312 PM.add(createDeadMachineInstructionElimPass()); 313 printAndVerify(PM, "After codegen DCE pass", 314 /* allowDoubleDefs= */ true); 315 316 if (OptLevel != CodeGenOpt::None) { 317 PM.add(createOptimizeExtsPass()); 318 if (!DisableMachineLICM) 319 PM.add(createMachineLICMPass()); 320 PM.add(createMachineCSEPass()); 321 if (!DisableMachineSink) 322 PM.add(createMachineSinkingPass()); 323 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes", 324 /* allowDoubleDefs= */ true); 325 } 326 327 // Pre-ra tail duplication. 328 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) { 329 PM.add(createTailDuplicatePass(true)); 330 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate", 331 /* allowDoubleDefs= */ true); 332 } 333 334 // Run pre-ra passes. 335 if (addPreRegAlloc(PM, OptLevel)) 336 printAndVerify(PM, "After PreRegAlloc passes", 337 /* allowDoubleDefs= */ true); 338 339 // Perform register allocation. 340 PM.add(createRegisterAllocator()); 341 printAndVerify(PM, "After Register Allocation"); 342 343 // Perform stack slot coloring and post-ra machine LICM. 344 if (OptLevel != CodeGenOpt::None) { 345 // FIXME: Re-enable coloring with register when it's capable of adding 346 // kill markers. 347 if (!DisableSSC) 348 PM.add(createStackSlotColoringPass(false)); 349 350 // Run post-ra machine LICM to hoist reloads / remats. 351 if (!DisablePostRAMachineLICM) 352 PM.add(createMachineLICMPass(false)); 353 354 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM"); 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 printNoVerify(PM, "After BranchFolding"); 382 } 383 384 // Tail duplication. 385 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) { 386 PM.add(createTailDuplicatePass(false)); 387 printNoVerify(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 printNoVerify(PM, "After CodePlacementOpt"); 398 } 399 400 if (addPreEmitPass(PM, OptLevel)) 401 printNoVerify(PM, "After PreEmit passes"); 402 403 return false; 404 } 405