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/TargetData.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetRegisterInfo.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"
41 #include "llvm/Support/TargetRegistry.h"
44 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
45 cl::desc("Disable Post Regalloc"));
46 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
47 cl::desc("Disable branch folding"));
48 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
49 cl::desc("Disable tail duplication"));
50 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
51 cl::desc("Disable pre-register allocation tail duplication"));
52 static cl::opt<bool> EnableBlockPlacement("enable-block-placement",
53 cl::Hidden, cl::desc("Enable probability-driven block placement"));
54 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
55 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
56 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
57 cl::desc("Disable code placement"));
58 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
59 cl::desc("Disable Stack Slot Coloring"));
60 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
61 cl::desc("Disable Machine Dead Code Elimination"));
62 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
63 cl::desc("Disable Machine LICM"));
64 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
65 cl::desc("Disable Machine Common Subexpression Elimination"));
66 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
68 cl::desc("Disable Machine LICM"));
69 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
70 cl::desc("Disable Machine Sinking"));
71 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
72 cl::desc("Disable Loop Strength Reduction Pass"));
73 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
74 cl::desc("Disable Codegen Prepare"));
75 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
76 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
77 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
78 cl::desc("Print LLVM IR input to isel pass"));
79 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
80 cl::desc("Dump garbage collector data"));
81 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
82 cl::desc("Show encoding in .s output"));
83 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
84 cl::desc("Show instruction structure in .s output"));
85 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
86 cl::desc("Verify generated machine code"),
87 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
89 static cl::opt<cl::boolOrDefault>
90 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
91 cl::init(cl::BOU_UNSET));
93 static bool getVerboseAsm() {
95 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
96 case cl::BOU_TRUE: return true;
97 case cl::BOU_FALSE: return false;
101 // Enable or disable FastISel. Both options are needed, because
102 // FastISel is enabled by default with -fast, and we wish to be
103 // able to enable or disable fast-isel independently from -O0.
104 static cl::opt<cl::boolOrDefault>
105 EnableFastISelOption("fast-isel", cl::Hidden,
106 cl::desc("Enable the \"fast\" instruction selector"));
108 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
109 StringRef CPU, StringRef FS,
110 TargetOptions Options,
111 Reloc::Model RM, CodeModel::Model CM,
112 CodeGenOpt::Level OL)
113 : TargetMachine(T, Triple, CPU, FS, Options) {
114 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
115 AsmInfo = T.createMCAsmInfo(Triple);
116 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
117 // and if the old one gets included then MCAsmInfo will be NULL and
118 // we'll crash later.
119 // Provide the user with a useful error message about what's wrong.
120 assert(AsmInfo && "MCAsmInfo not initialized."
121 "Make sure you include the correct TargetSelect.h"
122 "and that InitializeAllTargetMCs() is being invoked!");
125 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
126 formatted_raw_ostream &Out,
127 CodeGenFileType FileType,
128 bool DisableVerify) {
129 // Add common CodeGen passes.
130 MCContext *Context = 0;
131 if (addCommonCodeGenPasses(PM, DisableVerify, Context))
133 assert(Context != 0 && "Failed to get MCContext");
135 if (hasMCSaveTempLabels())
136 Context->setAllowTemporaryLabels(false);
138 const MCAsmInfo &MAI = *getMCAsmInfo();
139 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
140 OwningPtr<MCStreamer> AsmStreamer;
143 case CGFT_AssemblyFile: {
144 MCInstPrinter *InstPrinter =
145 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
147 // Create a code emitter if asked to show the encoding.
148 MCCodeEmitter *MCE = 0;
149 MCAsmBackend *MAB = 0;
150 if (ShowMCEncoding) {
151 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
152 MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
153 MAB = getTarget().createMCAsmBackend(getTargetTriple());
156 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
160 hasMCUseDwarfDirectory(),
164 AsmStreamer.reset(S);
167 case CGFT_ObjectFile: {
168 // Create the code emitter for the target if it exists. If not, .o file
170 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
172 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
173 if (MCE == 0 || MAB == 0)
176 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
178 MCE, hasMCRelaxAll(),
179 hasMCNoExecStack()));
180 AsmStreamer.get()->InitSections();
184 // The Null output is intended for use for performance analysis and testing,
186 AsmStreamer.reset(createNullStreamer(*Context));
190 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
191 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
195 // If successful, createAsmPrinter took ownership of AsmStreamer.
200 PM.add(createGCInfoDeleter());
204 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
205 /// get machine code emitted. This uses a JITCodeEmitter object to handle
206 /// actually outputting the machine code and resolving things like the address
207 /// of functions. This method should returns true if machine code emission is
210 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
212 bool DisableVerify) {
213 // Add common CodeGen passes.
215 if (addCommonCodeGenPasses(PM, DisableVerify, Ctx))
218 addCodeEmitter(PM, JCE);
219 PM.add(createGCInfoDeleter());
221 return false; // success!
224 /// addPassesToEmitMC - Add passes to the specified pass manager to get
225 /// machine code emitted with the MCJIT. This method returns true if machine
226 /// code is not supported. It fills the MCContext Ctx pointer which can be
227 /// used to build custom MCStreamer.
229 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
232 bool DisableVerify) {
233 // Add common CodeGen passes.
234 if (addCommonCodeGenPasses(PM, DisableVerify, Ctx))
237 if (hasMCSaveTempLabels())
238 Ctx->setAllowTemporaryLabels(false);
240 // Create the code emitter for the target if it exists. If not, .o file
242 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
243 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
244 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
245 if (MCE == 0 || MAB == 0)
248 OwningPtr<MCStreamer> AsmStreamer;
249 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
252 hasMCNoExecStack()));
253 AsmStreamer.get()->InitSections();
255 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
256 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
260 // If successful, createAsmPrinter took ownership of AsmStreamer.
265 return false; // success!
268 void LLVMTargetMachine::printNoVerify(PassManagerBase &PM,
269 const char *Banner) const {
270 if (Options.PrintMachineCode)
271 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
274 void LLVMTargetMachine::printAndVerify(PassManagerBase &PM,
275 const char *Banner) const {
276 if (Options.PrintMachineCode)
277 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
279 if (VerifyMachineCode)
280 PM.add(createMachineVerifierPass(Banner));
283 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
284 /// emitting to assembly files or machine code output.
286 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
288 MCContext *&OutContext) {
289 // Standard LLVM-Level Passes.
291 // Basic AliasAnalysis support.
292 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
293 // BasicAliasAnalysis wins if they disagree. This is intended to help
294 // support "obvious" type-punning idioms.
295 PM.add(createTypeBasedAliasAnalysisPass());
296 PM.add(createBasicAliasAnalysisPass());
298 // Before running any passes, run the verifier to determine if the input
299 // coming from the front-end and/or optimizer is valid.
301 PM.add(createVerifierPass());
303 // Run loop strength reduction before anything else.
304 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
305 PM.add(createLoopStrengthReducePass(getTargetLowering()));
307 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
310 PM.add(createGCLoweringPass());
312 // Make sure that no unreachable blocks are instruction selected.
313 PM.add(createUnreachableBlockEliminationPass());
315 // Turn exception handling constructs into something the code generators can
317 switch (getMCAsmInfo()->getExceptionHandlingType()) {
318 case ExceptionHandling::SjLj:
319 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
320 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
321 // catch info can get misplaced when a selector ends up more than one block
322 // removed from the parent invoke(s). This could happen when a landing
323 // pad is shared by multiple invokes and is also a target of a normal
324 // edge from elsewhere.
325 PM.add(createSjLjEHPass(getTargetLowering()));
327 case ExceptionHandling::DwarfCFI:
328 case ExceptionHandling::ARM:
329 case ExceptionHandling::Win64:
330 PM.add(createDwarfEHPass(this));
332 case ExceptionHandling::None:
333 PM.add(createLowerInvokePass(getTargetLowering()));
335 // The lower invoke pass may create unreachable code. Remove it.
336 PM.add(createUnreachableBlockEliminationPass());
340 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
341 PM.add(createCodeGenPreparePass(getTargetLowering()));
343 PM.add(createStackProtectorPass(getTargetLowering()));
348 PM.add(createPrintFunctionPass("\n\n"
349 "*** Final LLVM Code input to ISel ***\n",
352 // All passes which modify the LLVM IR are now complete; run the verifier
353 // to ensure that the IR is valid.
355 PM.add(createVerifierPass());
357 // Standard Lower-Level Passes.
359 // Install a MachineModuleInfo class, which is an immutable pass that holds
360 // all the per-module stuff we're generating, including MCContext.
361 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
363 &getTargetLowering()->getObjFileLowering());
365 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
367 // Set up a MachineFunction for the rest of CodeGen to work on.
368 PM.add(new MachineFunctionAnalysis(*this));
370 // Enable FastISel with -fast, but allow that to be overridden.
371 if (EnableFastISelOption == cl::BOU_TRUE ||
372 (getOptLevel() == CodeGenOpt::None &&
373 EnableFastISelOption != cl::BOU_FALSE))
374 Options.EnableFastISel = true;
376 // Ask the target for an isel.
377 if (addInstSelector(PM))
380 // Print the instruction selected machine code...
381 printAndVerify(PM, "After Instruction Selection");
383 // Expand pseudo-instructions emitted by ISel.
384 PM.add(createExpandISelPseudosPass());
386 // Pre-ra tail duplication.
387 if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) {
388 PM.add(createTailDuplicatePass(true));
389 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
392 // Optimize PHIs before DCE: removing dead PHI cycles may make more
393 // instructions dead.
394 if (getOptLevel() != CodeGenOpt::None)
395 PM.add(createOptimizePHIsPass());
397 // If the target requests it, assign local variables to stack slots relative
398 // to one another and simplify frame index references where possible.
399 PM.add(createLocalStackSlotAllocationPass());
401 if (getOptLevel() != CodeGenOpt::None) {
402 // With optimization, dead code should already be eliminated. However
403 // there is one known exception: lowered code for arguments that are only
404 // used by tail calls, where the tail calls reuse the incoming stack
405 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
406 if (!DisableMachineDCE)
407 PM.add(createDeadMachineInstructionElimPass());
408 printAndVerify(PM, "After codegen DCE pass");
410 if (!DisableMachineLICM)
411 PM.add(createMachineLICMPass());
412 if (!DisableMachineCSE)
413 PM.add(createMachineCSEPass());
414 if (!DisableMachineSink)
415 PM.add(createMachineSinkingPass());
416 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
418 PM.add(createPeepholeOptimizerPass());
419 printAndVerify(PM, "After codegen peephole optimization pass");
422 // Run pre-ra passes.
423 if (addPreRegAlloc(PM))
424 printAndVerify(PM, "After PreRegAlloc passes");
426 // Perform register allocation.
427 PM.add(createRegisterAllocator(getOptLevel()));
428 printAndVerify(PM, "After Register Allocation");
430 // Perform stack slot coloring and post-ra machine LICM.
431 if (getOptLevel() != CodeGenOpt::None) {
432 // FIXME: Re-enable coloring with register when it's capable of adding
435 PM.add(createStackSlotColoringPass(false));
437 // Run post-ra machine LICM to hoist reloads / remats.
438 if (!DisablePostRAMachineLICM)
439 PM.add(createMachineLICMPass(false));
441 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
444 // Run post-ra passes.
445 if (addPostRegAlloc(PM))
446 printAndVerify(PM, "After PostRegAlloc passes");
448 // Insert prolog/epilog code. Eliminate abstract frame index references...
449 PM.add(createPrologEpilogCodeInserter());
450 printAndVerify(PM, "After PrologEpilogCodeInserter");
452 // Branch folding must be run after regalloc and prolog/epilog insertion.
453 if (getOptLevel() != CodeGenOpt::None && !DisableBranchFold) {
454 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
455 printNoVerify(PM, "After BranchFolding");
459 if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) {
460 PM.add(createTailDuplicatePass(false));
461 printNoVerify(PM, "After TailDuplicate");
465 if (getOptLevel() != CodeGenOpt::None) {
466 PM.add(createMachineCopyPropagationPass());
467 printNoVerify(PM, "After copy propagation pass");
470 // Expand pseudo instructions before second scheduling pass.
471 PM.add(createExpandPostRAPseudosPass());
472 printNoVerify(PM, "After ExpandPostRAPseudos");
474 // Run pre-sched2 passes.
475 if (addPreSched2(PM))
476 printNoVerify(PM, "After PreSched2 passes");
478 // Second pass scheduler.
479 if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
480 PM.add(createPostRAScheduler(getOptLevel()));
481 printNoVerify(PM, "After PostRAScheduler");
484 PM.add(createGCMachineCodeAnalysisPass());
487 PM.add(createGCInfoPrinter(dbgs()));
489 if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace) {
490 if (EnableBlockPlacement) {
491 // MachineBlockPlacement is an experimental pass which is disabled by
492 // default currently. Eventually it should subsume CodePlacementOpt, so
493 // when enabled, the other is disabled.
494 PM.add(createMachineBlockPlacementPass());
495 printNoVerify(PM, "After MachineBlockPlacement");
497 PM.add(createCodePlacementOptPass());
498 printNoVerify(PM, "After CodePlacementOpt");
501 // Run a separate pass to collect block placement statistics.
502 if (EnableBlockPlacementStats) {
503 PM.add(createMachineBlockPlacementStatsPass());
504 printNoVerify(PM, "After MachineBlockPlacementStats");
508 if (addPreEmitPass(PM))
509 printNoVerify(PM, "After PreEmit passes");