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)
107 : TargetMachine(T, Triple, CPU, FS) {
108 AsmInfo = T.createMCAsmInfo(Triple);
111 // Set the default code model for the JIT for a generic target.
112 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
113 void LLVMTargetMachine::setCodeModelForJIT() {
114 setCodeModel(CodeModel::Small);
117 // Set the default code model for static compilation for a generic target.
118 void LLVMTargetMachine::setCodeModelForStatic() {
119 setCodeModel(CodeModel::Small);
122 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
123 formatted_raw_ostream &Out,
124 CodeGenFileType FileType,
125 CodeGenOpt::Level OptLevel,
126 bool DisableVerify) {
127 // Add common CodeGen passes.
128 MCContext *Context = 0;
129 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
131 assert(Context != 0 && "Failed to get MCContext");
133 if (hasMCSaveTempLabels())
134 Context->setAllowTemporaryLabels(false);
136 const MCAsmInfo &MAI = *getMCAsmInfo();
137 OwningPtr<MCStreamer> AsmStreamer;
140 default: return true;
141 case CGFT_AssemblyFile: {
142 MCInstPrinter *InstPrinter =
143 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
145 // Create a code emitter if asked to show the encoding.
146 MCCodeEmitter *MCE = 0;
147 TargetAsmBackend *TAB = 0;
148 if (ShowMCEncoding) {
149 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
150 MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI, *Context);
151 TAB = getTarget().createAsmBackend(getTargetTriple());
154 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
161 AsmStreamer.reset(S);
164 case CGFT_ObjectFile: {
165 // Create the code emitter for the target if it exists. If not, .o file
167 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
168 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI,
170 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
171 if (MCE == 0 || TAB == 0)
174 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(),
175 *Context, *TAB, Out, MCE,
177 hasMCNoExecStack()));
178 AsmStreamer.get()->InitSections();
182 // The Null output is intended for use for performance analysis and testing,
184 AsmStreamer.reset(createNullStreamer(*Context));
189 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
191 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
192 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
196 // If successful, createAsmPrinter took ownership of AsmStreamer.
201 // Make sure the code model is set.
202 setCodeModelForStatic();
203 PM.add(createGCInfoDeleter());
207 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
208 /// get machine code emitted. This uses a JITCodeEmitter 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
213 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
215 CodeGenOpt::Level OptLevel,
216 bool DisableVerify) {
217 // Make sure the code model is set.
218 setCodeModelForJIT();
220 // Add common CodeGen passes.
222 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
225 addCodeEmitter(PM, OptLevel, JCE);
226 PM.add(createGCInfoDeleter());
228 return false; // success!
231 /// addPassesToEmitMC - Add passes to the specified pass manager to get
232 /// machine code emitted with the MCJIT. This method returns true if machine
233 /// code is not supported. It fills the MCContext Ctx pointer which can be
234 /// used to build custom MCStreamer.
236 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
239 CodeGenOpt::Level OptLevel,
240 bool DisableVerify) {
241 // Add common CodeGen passes.
242 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
245 if (hasMCSaveTempLabels())
246 Ctx->setAllowTemporaryLabels(false);
248 // Create the code emitter for the target if it exists. If not, .o file
250 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
251 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(),STI, *Ctx);
252 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
253 if (MCE == 0 || TAB == 0)
256 OwningPtr<MCStreamer> AsmStreamer;
257 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(), *Ctx,
260 hasMCNoExecStack()));
261 AsmStreamer.get()->InitSections();
263 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
264 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
268 // If successful, createAsmPrinter took ownership of AsmStreamer.
273 // Make sure the code model is set.
274 setCodeModelForJIT();
276 return false; // success!
279 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
280 if (PrintMachineCode)
281 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
284 static void printAndVerify(PassManagerBase &PM,
285 const char *Banner) {
286 if (PrintMachineCode)
287 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
289 if (VerifyMachineCode)
290 PM.add(createMachineVerifierPass(Banner));
293 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
294 /// emitting to assembly files or machine code output.
296 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
297 CodeGenOpt::Level OptLevel,
299 MCContext *&OutContext) {
300 // Standard LLVM-Level Passes.
302 // Basic AliasAnalysis support.
303 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
304 // BasicAliasAnalysis wins if they disagree. This is intended to help
305 // support "obvious" type-punning idioms.
306 PM.add(createTypeBasedAliasAnalysisPass());
307 PM.add(createBasicAliasAnalysisPass());
309 // Before running any passes, run the verifier to determine if the input
310 // coming from the front-end and/or optimizer is valid.
312 PM.add(createVerifierPass());
314 // Run loop strength reduction before anything else.
315 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
316 PM.add(createLoopStrengthReducePass(getTargetLowering()));
318 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
321 PM.add(createGCLoweringPass());
323 // Make sure that no unreachable blocks are instruction selected.
324 PM.add(createUnreachableBlockEliminationPass());
326 // Turn exception handling constructs into something the code generators can
328 switch (getMCAsmInfo()->getExceptionHandlingType()) {
329 case ExceptionHandling::SjLj:
330 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
331 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
332 // catch info can get misplaced when a selector ends up more than one block
333 // removed from the parent invoke(s). This could happen when a landing
334 // pad is shared by multiple invokes and is also a target of a normal
335 // edge from elsewhere.
336 PM.add(createSjLjEHPass(getTargetLowering()));
338 case ExceptionHandling::DwarfCFI:
339 case ExceptionHandling::ARM:
340 case ExceptionHandling::Win64:
341 PM.add(createDwarfEHPass(this));
343 case ExceptionHandling::None:
344 PM.add(createLowerInvokePass(getTargetLowering()));
346 // The lower invoke pass may create unreachable code. Remove it.
347 PM.add(createUnreachableBlockEliminationPass());
351 if (OptLevel != CodeGenOpt::None && !DisableCGP)
352 PM.add(createCodeGenPreparePass(getTargetLowering()));
354 PM.add(createStackProtectorPass(getTargetLowering()));
356 addPreISel(PM, OptLevel);
359 PM.add(createPrintFunctionPass("\n\n"
360 "*** Final LLVM Code input to ISel ***\n",
363 // All passes which modify the LLVM IR are now complete; run the verifier
364 // to ensure that the IR is valid.
366 PM.add(createVerifierPass());
368 // Standard Lower-Level Passes.
370 // Install a MachineModuleInfo class, which is an immutable pass that holds
371 // all the per-module stuff we're generating, including MCContext.
372 TargetAsmInfo *TAI = new TargetAsmInfo(*this);
373 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), TAI);
375 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
377 // Set up a MachineFunction for the rest of CodeGen to work on.
378 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
380 // Enable FastISel with -fast, but allow that to be overridden.
381 if (EnableFastISelOption == cl::BOU_TRUE ||
382 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
383 EnableFastISel = true;
385 // Ask the target for an isel.
386 if (addInstSelector(PM, OptLevel))
389 // Print the instruction selected machine code...
390 printAndVerify(PM, "After Instruction Selection");
392 // Expand pseudo-instructions emitted by ISel.
393 PM.add(createExpandISelPseudosPass());
395 // Pre-ra tail duplication.
396 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
397 PM.add(createTailDuplicatePass(true));
398 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
401 // Optimize PHIs before DCE: removing dead PHI cycles may make more
402 // instructions dead.
403 if (OptLevel != CodeGenOpt::None)
404 PM.add(createOptimizePHIsPass());
406 // If the target requests it, assign local variables to stack slots relative
407 // to one another and simplify frame index references where possible.
408 PM.add(createLocalStackSlotAllocationPass());
410 if (OptLevel != CodeGenOpt::None) {
411 // With optimization, dead code should already be eliminated. However
412 // there is one known exception: lowered code for arguments that are only
413 // used by tail calls, where the tail calls reuse the incoming stack
414 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
415 PM.add(createDeadMachineInstructionElimPass());
416 printAndVerify(PM, "After codegen DCE pass");
418 if (!DisableMachineLICM)
419 PM.add(createMachineLICMPass());
420 PM.add(createMachineCSEPass());
421 if (!DisableMachineSink)
422 PM.add(createMachineSinkingPass());
423 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
425 PM.add(createPeepholeOptimizerPass());
426 printAndVerify(PM, "After codegen peephole optimization pass");
429 // Run pre-ra passes.
430 if (addPreRegAlloc(PM, OptLevel))
431 printAndVerify(PM, "After PreRegAlloc passes");
433 // Perform register allocation.
434 PM.add(createRegisterAllocator(OptLevel));
435 printAndVerify(PM, "After Register Allocation");
437 // Perform stack slot coloring and post-ra machine LICM.
438 if (OptLevel != CodeGenOpt::None) {
439 // FIXME: Re-enable coloring with register when it's capable of adding
442 PM.add(createStackSlotColoringPass(false));
444 // Run post-ra machine LICM to hoist reloads / remats.
445 if (!DisablePostRAMachineLICM)
446 PM.add(createMachineLICMPass(false));
448 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
451 // Run post-ra passes.
452 if (addPostRegAlloc(PM, OptLevel))
453 printAndVerify(PM, "After PostRegAlloc passes");
455 PM.add(createLowerSubregsPass());
456 printAndVerify(PM, "After LowerSubregs");
458 // Insert prolog/epilog code. Eliminate abstract frame index references...
459 PM.add(createPrologEpilogCodeInserter());
460 printAndVerify(PM, "After PrologEpilogCodeInserter");
462 // Run pre-sched2 passes.
463 if (addPreSched2(PM, OptLevel))
464 printAndVerify(PM, "After PreSched2 passes");
466 // Second pass scheduler.
467 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
468 PM.add(createPostRAScheduler(OptLevel));
469 printAndVerify(PM, "After PostRAScheduler");
472 // Branch folding must be run after regalloc and prolog/epilog insertion.
473 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
474 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
475 printNoVerify(PM, "After BranchFolding");
479 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
480 PM.add(createTailDuplicatePass(false));
481 printNoVerify(PM, "After TailDuplicate");
484 PM.add(createGCMachineCodeAnalysisPass());
487 PM.add(createGCInfoPrinter(dbgs()));
489 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
490 PM.add(createCodePlacementOptPass());
491 printNoVerify(PM, "After CodePlacementOpt");
494 if (addPreEmitPass(PM, OptLevel))
495 printNoVerify(PM, "After PreEmit passes");