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/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetRegistry.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/ADT/OwningPtr.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FormattedStream.h"
47 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
48 cl::desc("Disable Post Regalloc"));
49 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
50 cl::desc("Disable branch folding"));
51 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
52 cl::desc("Disable tail duplication"));
53 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
54 cl::desc("Disable pre-register allocation tail duplication"));
55 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
56 cl::desc("Disable code placement"));
57 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
58 cl::desc("Disable Stack Slot Coloring"));
59 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
60 cl::desc("Disable Machine LICM"));
61 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
63 cl::desc("Disable Machine LICM"));
64 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
65 cl::desc("Disable Machine Sinking"));
66 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
67 cl::desc("Disable Loop Strength Reduction Pass"));
68 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
69 cl::desc("Disable Codegen Prepare"));
70 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
71 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
72 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
73 cl::desc("Print LLVM IR input to isel pass"));
74 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
75 cl::desc("Dump garbage collector data"));
76 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
77 cl::desc("Show encoding in .s output"));
78 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
79 cl::desc("Show instruction structure in .s output"));
80 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
81 cl::desc("Enable MC API logging"));
82 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
83 cl::desc("Verify generated machine code"),
84 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
86 static cl::opt<cl::boolOrDefault>
87 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
88 cl::init(cl::BOU_UNSET));
90 static bool getVerboseAsm() {
93 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
94 case cl::BOU_TRUE: return true;
95 case cl::BOU_FALSE: return false;
99 // Enable or disable FastISel. Both options are needed, because
100 // FastISel is enabled by default with -fast, and we wish to be
101 // able to enable or disable fast-isel independently from -O0.
102 static cl::opt<cl::boolOrDefault>
103 EnableFastISelOption("fast-isel", cl::Hidden,
104 cl::desc("Enable the \"fast\" instruction selector"));
106 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
107 StringRef CPU, StringRef FS,
109 : TargetMachine(T, Triple, CPU, FS) {
110 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM);
111 AsmInfo = T.createMCAsmInfo(Triple);
114 // Set the default code model for the JIT for a generic target.
115 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
116 void LLVMTargetMachine::setCodeModelForJIT() {
117 setCodeModel(CodeModel::Small);
120 // Set the default code model for static compilation for a generic target.
121 void LLVMTargetMachine::setCodeModelForStatic() {
122 setCodeModel(CodeModel::Small);
125 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
126 formatted_raw_ostream &Out,
127 CodeGenFileType FileType,
128 CodeGenOpt::Level OptLevel,
129 bool DisableVerify) {
130 // Add common CodeGen passes.
131 MCContext *Context = 0;
132 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
134 assert(Context != 0 && "Failed to get MCContext");
136 if (hasMCSaveTempLabels())
137 Context->setAllowTemporaryLabels(false);
139 const MCAsmInfo &MAI = *getMCAsmInfo();
140 OwningPtr<MCStreamer> AsmStreamer;
143 default: return true;
144 case CGFT_AssemblyFile: {
145 MCInstPrinter *InstPrinter =
146 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
148 // Create a code emitter if asked to show the encoding.
149 MCCodeEmitter *MCE = 0;
150 TargetAsmBackend *TAB = 0;
151 if (ShowMCEncoding) {
152 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
153 MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI, *Context);
154 TAB = getTarget().createAsmBackend(getTargetTriple());
157 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
164 AsmStreamer.reset(S);
167 case CGFT_ObjectFile: {
168 // Create the code emitter for the target if it exists. If not, .o file
170 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
171 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI,
173 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
174 if (MCE == 0 || TAB == 0)
177 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(),
178 *Context, *TAB, Out, MCE,
180 hasMCNoExecStack()));
181 AsmStreamer.get()->InitSections();
185 // The Null output is intended for use for performance analysis and testing,
187 AsmStreamer.reset(createNullStreamer(*Context));
192 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
194 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
195 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
199 // If successful, createAsmPrinter took ownership of AsmStreamer.
204 // Make sure the code model is set.
205 setCodeModelForStatic();
206 PM.add(createGCInfoDeleter());
210 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
211 /// get machine code emitted. This uses a JITCodeEmitter object to handle
212 /// actually outputting the machine code and resolving things like the address
213 /// of functions. This method should returns true if machine code emission is
216 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
218 CodeGenOpt::Level OptLevel,
219 bool DisableVerify) {
220 // Make sure the code model is set.
221 setCodeModelForJIT();
223 // Add common CodeGen passes.
225 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
228 addCodeEmitter(PM, OptLevel, JCE);
229 PM.add(createGCInfoDeleter());
231 return false; // success!
234 /// addPassesToEmitMC - Add passes to the specified pass manager to get
235 /// machine code emitted with the MCJIT. This method returns true if machine
236 /// code is not supported. It fills the MCContext Ctx pointer which can be
237 /// used to build custom MCStreamer.
239 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
242 CodeGenOpt::Level OptLevel,
243 bool DisableVerify) {
244 // Add common CodeGen passes.
245 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
248 if (hasMCSaveTempLabels())
249 Ctx->setAllowTemporaryLabels(false);
251 // Create the code emitter for the target if it exists. If not, .o file
253 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
254 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(),STI, *Ctx);
255 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
256 if (MCE == 0 || TAB == 0)
259 OwningPtr<MCStreamer> AsmStreamer;
260 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(), *Ctx,
263 hasMCNoExecStack()));
264 AsmStreamer.get()->InitSections();
266 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
267 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
271 // If successful, createAsmPrinter took ownership of AsmStreamer.
276 // Make sure the code model is set.
277 setCodeModelForJIT();
279 return false; // success!
282 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
283 if (PrintMachineCode)
284 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
287 static void printAndVerify(PassManagerBase &PM,
288 const char *Banner) {
289 if (PrintMachineCode)
290 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
292 if (VerifyMachineCode)
293 PM.add(createMachineVerifierPass(Banner));
296 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
297 /// emitting to assembly files or machine code output.
299 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
300 CodeGenOpt::Level OptLevel,
302 MCContext *&OutContext) {
303 // Standard LLVM-Level Passes.
305 // Basic AliasAnalysis support.
306 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
307 // BasicAliasAnalysis wins if they disagree. This is intended to help
308 // support "obvious" type-punning idioms.
309 PM.add(createTypeBasedAliasAnalysisPass());
310 PM.add(createBasicAliasAnalysisPass());
312 // Before running any passes, run the verifier to determine if the input
313 // coming from the front-end and/or optimizer is valid.
315 PM.add(createVerifierPass());
317 // Run loop strength reduction before anything else.
318 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
319 PM.add(createLoopStrengthReducePass(getTargetLowering()));
321 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
324 PM.add(createGCLoweringPass());
326 // Make sure that no unreachable blocks are instruction selected.
327 PM.add(createUnreachableBlockEliminationPass());
329 // Turn exception handling constructs into something the code generators can
331 switch (getMCAsmInfo()->getExceptionHandlingType()) {
332 case ExceptionHandling::SjLj:
333 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
334 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
335 // catch info can get misplaced when a selector ends up more than one block
336 // removed from the parent invoke(s). This could happen when a landing
337 // pad is shared by multiple invokes and is also a target of a normal
338 // edge from elsewhere.
339 PM.add(createSjLjEHPass(getTargetLowering()));
341 case ExceptionHandling::DwarfCFI:
342 case ExceptionHandling::ARM:
343 case ExceptionHandling::Win64:
344 PM.add(createDwarfEHPass(this));
346 case ExceptionHandling::None:
347 PM.add(createLowerInvokePass(getTargetLowering()));
349 // The lower invoke pass may create unreachable code. Remove it.
350 PM.add(createUnreachableBlockEliminationPass());
354 if (OptLevel != CodeGenOpt::None && !DisableCGP)
355 PM.add(createCodeGenPreparePass(getTargetLowering()));
357 PM.add(createStackProtectorPass(getTargetLowering()));
359 addPreISel(PM, OptLevel);
362 PM.add(createPrintFunctionPass("\n\n"
363 "*** Final LLVM Code input to ISel ***\n",
366 // All passes which modify the LLVM IR are now complete; run the verifier
367 // to ensure that the IR is valid.
369 PM.add(createVerifierPass());
371 // Standard Lower-Level Passes.
373 // Install a MachineModuleInfo class, which is an immutable pass that holds
374 // all the per-module stuff we're generating, including MCContext.
375 TargetAsmInfo *TAI = new TargetAsmInfo(*this);
376 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
378 &getTargetLowering()->getObjFileLowering(),
381 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
383 // Set up a MachineFunction for the rest of CodeGen to work on.
384 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
386 // Enable FastISel with -fast, but allow that to be overridden.
387 if (EnableFastISelOption == cl::BOU_TRUE ||
388 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
389 EnableFastISel = true;
391 // Ask the target for an isel.
392 if (addInstSelector(PM, OptLevel))
395 // Print the instruction selected machine code...
396 printAndVerify(PM, "After Instruction Selection");
398 // Expand pseudo-instructions emitted by ISel.
399 PM.add(createExpandISelPseudosPass());
401 // Pre-ra tail duplication.
402 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
403 PM.add(createTailDuplicatePass(true));
404 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
407 // Optimize PHIs before DCE: removing dead PHI cycles may make more
408 // instructions dead.
409 if (OptLevel != CodeGenOpt::None)
410 PM.add(createOptimizePHIsPass());
412 // If the target requests it, assign local variables to stack slots relative
413 // to one another and simplify frame index references where possible.
414 PM.add(createLocalStackSlotAllocationPass());
416 if (OptLevel != CodeGenOpt::None) {
417 // With optimization, dead code should already be eliminated. However
418 // there is one known exception: lowered code for arguments that are only
419 // used by tail calls, where the tail calls reuse the incoming stack
420 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
421 PM.add(createDeadMachineInstructionElimPass());
422 printAndVerify(PM, "After codegen DCE pass");
424 if (!DisableMachineLICM)
425 PM.add(createMachineLICMPass());
426 PM.add(createMachineCSEPass());
427 if (!DisableMachineSink)
428 PM.add(createMachineSinkingPass());
429 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
431 PM.add(createPeepholeOptimizerPass());
432 printAndVerify(PM, "After codegen peephole optimization pass");
435 // Run pre-ra passes.
436 if (addPreRegAlloc(PM, OptLevel))
437 printAndVerify(PM, "After PreRegAlloc passes");
439 // Perform register allocation.
440 PM.add(createRegisterAllocator(OptLevel));
441 printAndVerify(PM, "After Register Allocation");
443 // Perform stack slot coloring and post-ra machine LICM.
444 if (OptLevel != CodeGenOpt::None) {
445 // FIXME: Re-enable coloring with register when it's capable of adding
448 PM.add(createStackSlotColoringPass(false));
450 // Run post-ra machine LICM to hoist reloads / remats.
451 if (!DisablePostRAMachineLICM)
452 PM.add(createMachineLICMPass(false));
454 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
457 // Run post-ra passes.
458 if (addPostRegAlloc(PM, OptLevel))
459 printAndVerify(PM, "After PostRegAlloc passes");
461 PM.add(createLowerSubregsPass());
462 printAndVerify(PM, "After LowerSubregs");
464 // Insert prolog/epilog code. Eliminate abstract frame index references...
465 PM.add(createPrologEpilogCodeInserter());
466 printAndVerify(PM, "After PrologEpilogCodeInserter");
468 // Run pre-sched2 passes.
469 if (addPreSched2(PM, OptLevel))
470 printAndVerify(PM, "After PreSched2 passes");
472 // Second pass scheduler.
473 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
474 PM.add(createPostRAScheduler(OptLevel));
475 printAndVerify(PM, "After PostRAScheduler");
478 // Branch folding must be run after regalloc and prolog/epilog insertion.
479 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
480 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
481 printNoVerify(PM, "After BranchFolding");
485 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
486 PM.add(createTailDuplicatePass(false));
487 printNoVerify(PM, "After TailDuplicate");
490 PM.add(createGCMachineCodeAnalysisPass());
493 PM.add(createGCInfoPrinter(dbgs()));
495 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
496 PM.add(createCodePlacementOptPass());
497 printNoVerify(PM, "After CodePlacementOpt");
500 if (addPreEmitPass(PM, OptLevel))
501 printNoVerify(PM, "After PreEmit passes");