1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVMTargetMachine class.
12 //===----------------------------------------------------------------------===//
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/TargetLowering.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Target/TargetAsmInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetRegistry.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/ADT/OwningPtr.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/StandardPasses.h"
42 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
43 cl::desc("Disable Post Regalloc"));
44 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
45 cl::desc("Disable branch folding"));
46 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
47 cl::desc("Disable tail duplication"));
48 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
49 cl::desc("Disable pre-register allocation tail duplication"));
50 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
51 cl::desc("Disable code placement"));
52 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
53 cl::desc("Disable Stack Slot Coloring"));
54 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
55 cl::desc("Disable Machine LICM"));
56 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
58 cl::desc("Disable Machine LICM"));
59 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
60 cl::desc("Disable Machine Sinking"));
61 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
62 cl::desc("Disable Loop Strength Reduction Pass"));
63 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
64 cl::desc("Disable Codegen Prepare"));
65 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
66 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
67 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
68 cl::desc("Print LLVM IR input to isel pass"));
69 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
70 cl::desc("Dump garbage collector data"));
71 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
72 cl::desc("Show encoding in .s output"));
73 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
74 cl::desc("Show instruction structure in .s output"));
75 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
76 cl::desc("Enable MC API logging"));
77 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
78 cl::desc("Verify generated machine code"),
79 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
81 static cl::opt<cl::boolOrDefault>
82 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
83 cl::init(cl::BOU_UNSET));
85 static bool getVerboseAsm() {
88 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
89 case cl::BOU_TRUE: return true;
90 case cl::BOU_FALSE: return false;
94 // Enable or disable FastISel. Both options are needed, because
95 // FastISel is enabled by default with -fast, and we wish to be
96 // able to enable or disable fast-isel independently from -O0.
97 static cl::opt<cl::boolOrDefault>
98 EnableFastISelOption("fast-isel", cl::Hidden,
99 cl::desc("Enable the \"fast\" instruction selector"));
101 // Enable or disable an experimental optimization to split GEPs
102 // and run a special GVN pass which does not examine loads, in
103 // an effort to factor out redundancy implicit in complex GEPs.
104 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
105 cl::desc("Split GEPs and run no-load GVN"));
107 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
108 const std::string &Triple)
109 : TargetMachine(T), TargetTriple(Triple) {
110 AsmInfo = T.createAsmInfo(TargetTriple);
113 // Set the default code model for the JIT for a generic target.
114 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
115 void LLVMTargetMachine::setCodeModelForJIT() {
116 setCodeModel(CodeModel::Small);
119 // Set the default code model for static compilation for a generic target.
120 void LLVMTargetMachine::setCodeModelForStatic() {
121 setCodeModel(CodeModel::Small);
124 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
125 formatted_raw_ostream &Out,
126 CodeGenFileType FileType,
127 CodeGenOpt::Level OptLevel,
128 bool DisableVerify) {
129 // Add common CodeGen passes.
130 MCContext *Context = 0;
131 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
133 assert(Context != 0 && "Failed to get MCContext");
135 const MCAsmInfo &MAI = *getMCAsmInfo();
136 OwningPtr<MCStreamer> AsmStreamer;
139 default: return true;
140 case CGFT_AssemblyFile: {
141 MCInstPrinter *InstPrinter =
142 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
144 // Create a code emitter if asked to show the encoding.
145 MCCodeEmitter *MCE = 0;
147 MCE = getTarget().createCodeEmitter(*this, *Context);
149 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
155 AsmStreamer.reset(S);
158 case CGFT_ObjectFile: {
159 // Create the code emitter for the target if it exists. If not, .o file
161 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
162 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
163 if (MCE == 0 || TAB == 0)
166 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context,
169 AsmStreamer.get()->InitSections();
173 // The Null output is intended for use for performance analysis and testing,
175 AsmStreamer.reset(createNullStreamer(*Context));
180 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
182 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
183 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
187 // If successful, createAsmPrinter took ownership of AsmStreamer.
192 // Make sure the code model is set.
193 setCodeModelForStatic();
194 PM.add(createGCInfoDeleter());
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
204 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
206 CodeGenOpt::Level OptLevel,
207 bool DisableVerify) {
208 // Make sure the code model is set.
209 setCodeModelForJIT();
211 // Add common CodeGen passes.
213 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
216 addCodeEmitter(PM, OptLevel, JCE);
217 PM.add(createGCInfoDeleter());
219 return false; // success!
222 /// addPassesToEmitMC - Add passes to the specified pass manager to get
223 /// machine code emitted with the MCJIT. This method returns true if machine
224 /// code is not supported. It fills the MCContext Ctx pointer which can be
225 /// used to build custom MCStreamer.
227 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
229 CodeGenOpt::Level OptLevel,
230 bool DisableVerify) {
231 // Add common CodeGen passes.
232 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
234 // Make sure the code model is set.
235 setCodeModelForJIT();
237 return false; // success!
240 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
241 if (PrintMachineCode)
242 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
245 static void printAndVerify(PassManagerBase &PM,
246 const char *Banner) {
247 if (PrintMachineCode)
248 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
250 if (VerifyMachineCode)
251 PM.add(createMachineVerifierPass());
254 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
255 /// emitting to assembly files or machine code output.
257 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
258 CodeGenOpt::Level OptLevel,
260 MCContext *&OutContext) {
261 // Standard LLVM-Level Passes.
263 // Basic AliasAnalysis support.
264 createStandardAliasAnalysisPasses(&PM);
266 // Before running any passes, run the verifier to determine if the input
267 // coming from the front-end and/or optimizer is valid.
269 PM.add(createVerifierPass());
271 // Optionally, tun split-GEPs and no-load GVN.
272 if (EnableSplitGEPGVN) {
273 PM.add(createGEPSplitterPass());
274 PM.add(createGVNPass(/*NoLoads=*/true));
277 // Run loop strength reduction before anything else.
278 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
279 PM.add(createLoopStrengthReducePass(getTargetLowering()));
281 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
284 PM.add(createGCLoweringPass());
286 // Make sure that no unreachable blocks are instruction selected.
287 PM.add(createUnreachableBlockEliminationPass());
289 // Turn exception handling constructs into something the code generators can
291 switch (getMCAsmInfo()->getExceptionHandlingType()) {
292 case ExceptionHandling::SjLj:
293 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
294 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
295 // catch info can get misplaced when a selector ends up more than one block
296 // removed from the parent invoke(s). This could happen when a landing
297 // pad is shared by multiple invokes and is also a target of a normal
298 // edge from elsewhere.
299 PM.add(createSjLjEHPass(getTargetLowering()));
301 case ExceptionHandling::Dwarf:
302 PM.add(createDwarfEHPass(this));
304 case ExceptionHandling::None:
305 PM.add(createLowerInvokePass(getTargetLowering()));
307 // The lower invoke pass may create unreachable code. Remove it.
308 PM.add(createUnreachableBlockEliminationPass());
312 if (OptLevel != CodeGenOpt::None && !DisableCGP)
313 PM.add(createCodeGenPreparePass(getTargetLowering()));
315 PM.add(createStackProtectorPass(getTargetLowering()));
317 addPreISel(PM, OptLevel);
320 PM.add(createPrintFunctionPass("\n\n"
321 "*** Final LLVM Code input to ISel ***\n",
324 // All passes which modify the LLVM IR are now complete; run the verifier
325 // to ensure that the IR is valid.
327 PM.add(createVerifierPass());
329 // Standard Lower-Level Passes.
331 // Install a MachineModuleInfo class, which is an immutable pass that holds
332 // all the per-module stuff we're generating, including MCContext.
333 TargetAsmInfo *TAI = new TargetAsmInfo(*this);
334 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), TAI);
336 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
338 // Set up a MachineFunction for the rest of CodeGen to work on.
339 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
341 // Enable FastISel with -fast, but allow that to be overridden.
342 if (EnableFastISelOption == cl::BOU_TRUE ||
343 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
344 EnableFastISel = true;
346 // Ask the target for an isel.
347 if (addInstSelector(PM, OptLevel))
350 // Print the instruction selected machine code...
351 printAndVerify(PM, "After Instruction Selection");
353 // Expand pseudo-instructions emitted by ISel.
354 PM.add(createExpandISelPseudosPass());
356 // Optimize PHIs before DCE: removing dead PHI cycles may make more
357 // instructions dead.
358 if (OptLevel != CodeGenOpt::None)
359 PM.add(createOptimizePHIsPass());
361 // If the target requests it, assign local variables to stack slots relative
362 // to one another and simplify frame index references where possible.
363 PM.add(createLocalStackSlotAllocationPass());
365 if (OptLevel != CodeGenOpt::None) {
366 // With optimization, dead code should already be eliminated. However
367 // there is one known exception: lowered code for arguments that are only
368 // used by tail calls, where the tail calls reuse the incoming stack
369 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
370 PM.add(createDeadMachineInstructionElimPass());
371 printAndVerify(PM, "After codegen DCE pass");
373 if (!DisableMachineLICM)
374 PM.add(createMachineLICMPass());
375 PM.add(createMachineCSEPass());
376 if (!DisableMachineSink)
377 PM.add(createMachineSinkingPass());
378 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
380 PM.add(createPeepholeOptimizerPass());
381 printAndVerify(PM, "After codegen peephole optimization pass");
384 // Pre-ra tail duplication.
385 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
386 PM.add(createTailDuplicatePass(true));
387 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
390 // Run pre-ra passes.
391 if (addPreRegAlloc(PM, OptLevel))
392 printAndVerify(PM, "After PreRegAlloc passes");
394 // Perform register allocation.
395 PM.add(createRegisterAllocator(OptLevel));
396 printAndVerify(PM, "After Register Allocation");
398 // Perform stack slot coloring and post-ra machine LICM.
399 if (OptLevel != CodeGenOpt::None) {
400 // FIXME: Re-enable coloring with register when it's capable of adding
403 PM.add(createStackSlotColoringPass(false));
405 // Run post-ra machine LICM to hoist reloads / remats.
406 if (!DisablePostRAMachineLICM)
407 PM.add(createMachineLICMPass(false));
409 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
412 // Run post-ra passes.
413 if (addPostRegAlloc(PM, OptLevel))
414 printAndVerify(PM, "After PostRegAlloc passes");
416 PM.add(createLowerSubregsPass());
417 printAndVerify(PM, "After LowerSubregs");
419 // Insert prolog/epilog code. Eliminate abstract frame index references...
420 PM.add(createPrologEpilogCodeInserter());
421 printAndVerify(PM, "After PrologEpilogCodeInserter");
423 // Run pre-sched2 passes.
424 if (addPreSched2(PM, OptLevel))
425 printAndVerify(PM, "After PreSched2 passes");
427 // Second pass scheduler.
428 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
429 PM.add(createPostRAScheduler(OptLevel));
430 printAndVerify(PM, "After PostRAScheduler");
433 // Branch folding must be run after regalloc and prolog/epilog insertion.
434 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
435 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
436 printNoVerify(PM, "After BranchFolding");
440 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
441 PM.add(createTailDuplicatePass(false));
442 printNoVerify(PM, "After TailDuplicate");
445 PM.add(createGCMachineCodeAnalysisPass());
448 PM.add(createGCInfoPrinter(dbgs()));
450 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
451 PM.add(createCodePlacementOptPass());
452 printNoVerify(PM, "After CodePlacementOpt");
455 if (addPreEmitPass(PM, OptLevel))
456 printNoVerify(PM, "After PreEmit passes");