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/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/TargetAsmInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetRegistry.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/ADT/OwningPtr.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/FormattedStream.h"
46 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
47 cl::desc("Disable Post Regalloc"));
48 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
49 cl::desc("Disable branch folding"));
50 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
51 cl::desc("Disable tail duplication"));
52 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
53 cl::desc("Disable pre-register allocation tail duplication"));
54 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
55 cl::desc("Disable code placement"));
56 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
57 cl::desc("Disable Stack Slot Coloring"));
58 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
59 cl::desc("Disable Machine LICM"));
60 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
62 cl::desc("Disable Machine LICM"));
63 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
64 cl::desc("Disable Machine Sinking"));
65 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
66 cl::desc("Disable Loop Strength Reduction Pass"));
67 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
68 cl::desc("Disable Codegen Prepare"));
69 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
70 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
71 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
72 cl::desc("Print LLVM IR input to isel pass"));
73 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
74 cl::desc("Dump garbage collector data"));
75 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
76 cl::desc("Show encoding in .s output"));
77 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
78 cl::desc("Show instruction structure in .s output"));
79 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
80 cl::desc("Enable MC API logging"));
81 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
82 cl::desc("Verify generated machine code"),
83 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
85 static cl::opt<cl::boolOrDefault>
86 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
87 cl::init(cl::BOU_UNSET));
89 static bool getVerboseAsm() {
92 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
93 case cl::BOU_TRUE: return true;
94 case cl::BOU_FALSE: return false;
98 // Enable or disable FastISel. Both options are needed, because
99 // FastISel is enabled by default with -fast, and we wish to be
100 // able to enable or disable fast-isel independently from -O0.
101 static cl::opt<cl::boolOrDefault>
102 EnableFastISelOption("fast-isel", cl::Hidden,
103 cl::desc("Enable the \"fast\" instruction selector"));
105 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
106 StringRef CPU, StringRef FS,
108 : TargetMachine(T, Triple, CPU, FS) {
109 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM);
110 AsmInfo = T.createMCAsmInfo(Triple);
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 if (hasMCSaveTempLabels())
136 Context->setAllowTemporaryLabels(false);
138 const MCAsmInfo &MAI = *getMCAsmInfo();
139 OwningPtr<MCStreamer> AsmStreamer;
142 default: return true;
143 case CGFT_AssemblyFile: {
144 MCInstPrinter *InstPrinter =
145 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
147 // Create a code emitter if asked to show the encoding.
148 MCCodeEmitter *MCE = 0;
149 TargetAsmBackend *TAB = 0;
150 if (ShowMCEncoding) {
151 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
152 MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI, *Context);
153 TAB = getTarget().createAsmBackend(getTargetTriple());
156 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
163 AsmStreamer.reset(S);
166 case CGFT_ObjectFile: {
167 // Create the code emitter for the target if it exists. If not, .o file
169 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
170 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI,
172 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
173 if (MCE == 0 || TAB == 0)
176 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(),
177 *Context, *TAB, Out, MCE,
179 hasMCNoExecStack()));
180 AsmStreamer.get()->InitSections();
184 // The Null output is intended for use for performance analysis and testing,
186 AsmStreamer.reset(createNullStreamer(*Context));
191 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
193 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
194 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
198 // If successful, createAsmPrinter took ownership of AsmStreamer.
203 // Make sure the code model is set.
204 setCodeModelForStatic();
205 PM.add(createGCInfoDeleter());
209 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
210 /// get machine code emitted. This uses a JITCodeEmitter object to handle
211 /// actually outputting the machine code and resolving things like the address
212 /// of functions. This method should returns true if machine code emission is
215 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
217 CodeGenOpt::Level OptLevel,
218 bool DisableVerify) {
219 // Make sure the code model is set.
220 setCodeModelForJIT();
222 // Add common CodeGen passes.
224 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
227 addCodeEmitter(PM, OptLevel, JCE);
228 PM.add(createGCInfoDeleter());
230 return false; // success!
233 /// addPassesToEmitMC - Add passes to the specified pass manager to get
234 /// machine code emitted with the MCJIT. This method returns true if machine
235 /// code is not supported. It fills the MCContext Ctx pointer which can be
236 /// used to build custom MCStreamer.
238 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
241 CodeGenOpt::Level OptLevel,
242 bool DisableVerify) {
243 // Add common CodeGen passes.
244 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
247 if (hasMCSaveTempLabels())
248 Ctx->setAllowTemporaryLabels(false);
250 // Create the code emitter for the target if it exists. If not, .o file
252 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
253 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(),STI, *Ctx);
254 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
255 if (MCE == 0 || TAB == 0)
258 OwningPtr<MCStreamer> AsmStreamer;
259 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(), *Ctx,
262 hasMCNoExecStack()));
263 AsmStreamer.get()->InitSections();
265 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
266 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
270 // If successful, createAsmPrinter took ownership of AsmStreamer.
275 // Make sure the code model is set.
276 setCodeModelForJIT();
278 return false; // success!
281 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
282 if (PrintMachineCode)
283 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
286 static void printAndVerify(PassManagerBase &PM,
287 const char *Banner) {
288 if (PrintMachineCode)
289 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
291 if (VerifyMachineCode)
292 PM.add(createMachineVerifierPass(Banner));
295 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
296 /// emitting to assembly files or machine code output.
298 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
299 CodeGenOpt::Level OptLevel,
301 MCContext *&OutContext) {
302 // Standard LLVM-Level Passes.
304 // Basic AliasAnalysis support.
305 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
306 // BasicAliasAnalysis wins if they disagree. This is intended to help
307 // support "obvious" type-punning idioms.
308 PM.add(createTypeBasedAliasAnalysisPass());
309 PM.add(createBasicAliasAnalysisPass());
311 // Before running any passes, run the verifier to determine if the input
312 // coming from the front-end and/or optimizer is valid.
314 PM.add(createVerifierPass());
316 // Run loop strength reduction before anything else.
317 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
318 PM.add(createLoopStrengthReducePass(getTargetLowering()));
320 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
323 PM.add(createGCLoweringPass());
325 // Make sure that no unreachable blocks are instruction selected.
326 PM.add(createUnreachableBlockEliminationPass());
328 // Turn exception handling constructs into something the code generators can
330 switch (getMCAsmInfo()->getExceptionHandlingType()) {
331 case ExceptionHandling::SjLj:
332 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
333 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
334 // catch info can get misplaced when a selector ends up more than one block
335 // removed from the parent invoke(s). This could happen when a landing
336 // pad is shared by multiple invokes and is also a target of a normal
337 // edge from elsewhere.
338 PM.add(createSjLjEHPass(getTargetLowering()));
340 case ExceptionHandling::DwarfCFI:
341 case ExceptionHandling::ARM:
342 case ExceptionHandling::Win64:
343 PM.add(createDwarfEHPass(this));
345 case ExceptionHandling::None:
346 PM.add(createLowerInvokePass(getTargetLowering()));
348 // The lower invoke pass may create unreachable code. Remove it.
349 PM.add(createUnreachableBlockEliminationPass());
353 if (OptLevel != CodeGenOpt::None && !DisableCGP)
354 PM.add(createCodeGenPreparePass(getTargetLowering()));
356 PM.add(createStackProtectorPass(getTargetLowering()));
358 addPreISel(PM, OptLevel);
361 PM.add(createPrintFunctionPass("\n\n"
362 "*** Final LLVM Code input to ISel ***\n",
365 // All passes which modify the LLVM IR are now complete; run the verifier
366 // to ensure that the IR is valid.
368 PM.add(createVerifierPass());
370 // Standard Lower-Level Passes.
372 // Install a MachineModuleInfo class, which is an immutable pass that holds
373 // all the per-module stuff we're generating, including MCContext.
374 TargetAsmInfo *TAI = new TargetAsmInfo(*this);
375 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
376 *getRegisterInfo(), TAI);
378 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
380 // Set up a MachineFunction for the rest of CodeGen to work on.
381 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
383 // Enable FastISel with -fast, but allow that to be overridden.
384 if (EnableFastISelOption == cl::BOU_TRUE ||
385 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
386 EnableFastISel = true;
388 // Ask the target for an isel.
389 if (addInstSelector(PM, OptLevel))
392 // Print the instruction selected machine code...
393 printAndVerify(PM, "After Instruction Selection");
395 // Expand pseudo-instructions emitted by ISel.
396 PM.add(createExpandISelPseudosPass());
398 // Pre-ra tail duplication.
399 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
400 PM.add(createTailDuplicatePass(true));
401 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
404 // Optimize PHIs before DCE: removing dead PHI cycles may make more
405 // instructions dead.
406 if (OptLevel != CodeGenOpt::None)
407 PM.add(createOptimizePHIsPass());
409 // If the target requests it, assign local variables to stack slots relative
410 // to one another and simplify frame index references where possible.
411 PM.add(createLocalStackSlotAllocationPass());
413 if (OptLevel != CodeGenOpt::None) {
414 // With optimization, dead code should already be eliminated. However
415 // there is one known exception: lowered code for arguments that are only
416 // used by tail calls, where the tail calls reuse the incoming stack
417 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
418 PM.add(createDeadMachineInstructionElimPass());
419 printAndVerify(PM, "After codegen DCE pass");
421 if (!DisableMachineLICM)
422 PM.add(createMachineLICMPass());
423 PM.add(createMachineCSEPass());
424 if (!DisableMachineSink)
425 PM.add(createMachineSinkingPass());
426 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
428 PM.add(createPeepholeOptimizerPass());
429 printAndVerify(PM, "After codegen peephole optimization pass");
432 // Run pre-ra passes.
433 if (addPreRegAlloc(PM, OptLevel))
434 printAndVerify(PM, "After PreRegAlloc passes");
436 // Perform register allocation.
437 PM.add(createRegisterAllocator(OptLevel));
438 printAndVerify(PM, "After Register Allocation");
440 // Perform stack slot coloring and post-ra machine LICM.
441 if (OptLevel != CodeGenOpt::None) {
442 // FIXME: Re-enable coloring with register when it's capable of adding
445 PM.add(createStackSlotColoringPass(false));
447 // Run post-ra machine LICM to hoist reloads / remats.
448 if (!DisablePostRAMachineLICM)
449 PM.add(createMachineLICMPass(false));
451 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
454 // Run post-ra passes.
455 if (addPostRegAlloc(PM, OptLevel))
456 printAndVerify(PM, "After PostRegAlloc passes");
458 PM.add(createLowerSubregsPass());
459 printAndVerify(PM, "After LowerSubregs");
461 // Insert prolog/epilog code. Eliminate abstract frame index references...
462 PM.add(createPrologEpilogCodeInserter());
463 printAndVerify(PM, "After PrologEpilogCodeInserter");
465 // Run pre-sched2 passes.
466 if (addPreSched2(PM, OptLevel))
467 printAndVerify(PM, "After PreSched2 passes");
469 // Second pass scheduler.
470 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
471 PM.add(createPostRAScheduler(OptLevel));
472 printAndVerify(PM, "After PostRAScheduler");
475 // Branch folding must be run after regalloc and prolog/epilog insertion.
476 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
477 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
478 printNoVerify(PM, "After BranchFolding");
482 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
483 PM.add(createTailDuplicatePass(false));
484 printNoVerify(PM, "After TailDuplicate");
487 PM.add(createGCMachineCodeAnalysisPass());
490 PM.add(createGCInfoPrinter(dbgs()));
492 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
493 PM.add(createCodePlacementOptPass());
494 printNoVerify(PM, "After CodePlacementOpt");
497 if (addPreEmitPass(PM, OptLevel))
498 printNoVerify(PM, "After PreEmit passes");