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