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,
108 Reloc::Model RM, CodeModel::Model CM)
109 : TargetMachine(T, Triple, CPU, FS) {
110 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM);
111 AsmInfo = T.createMCAsmInfo(Triple);
114 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
115 formatted_raw_ostream &Out,
116 CodeGenFileType FileType,
117 CodeGenOpt::Level OptLevel,
118 bool DisableVerify) {
119 // Add common CodeGen passes.
120 MCContext *Context = 0;
121 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
123 assert(Context != 0 && "Failed to get MCContext");
125 if (hasMCSaveTempLabels())
126 Context->setAllowTemporaryLabels(false);
128 const MCAsmInfo &MAI = *getMCAsmInfo();
129 OwningPtr<MCStreamer> AsmStreamer;
132 default: return true;
133 case CGFT_AssemblyFile: {
134 MCInstPrinter *InstPrinter =
135 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
137 // Create a code emitter if asked to show the encoding.
138 MCCodeEmitter *MCE = 0;
139 TargetAsmBackend *TAB = 0;
140 if (ShowMCEncoding) {
141 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
142 MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI, *Context);
143 TAB = getTarget().createAsmBackend(getTargetTriple());
146 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
153 AsmStreamer.reset(S);
156 case CGFT_ObjectFile: {
157 // Create the code emitter for the target if it exists. If not, .o file
159 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
160 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI,
162 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
163 if (MCE == 0 || TAB == 0)
166 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(),
167 *Context, *TAB, Out, MCE,
169 hasMCNoExecStack()));
170 AsmStreamer.get()->InitSections();
174 // The Null output is intended for use for performance analysis and testing,
176 AsmStreamer.reset(createNullStreamer(*Context));
181 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
183 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
184 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
188 // If successful, createAsmPrinter took ownership of AsmStreamer.
193 PM.add(createGCInfoDeleter());
197 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
198 /// get machine code emitted. This uses a JITCodeEmitter object to handle
199 /// actually outputting the machine code and resolving things like the address
200 /// of functions. This method should returns true if machine code emission is
203 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
205 CodeGenOpt::Level OptLevel,
206 bool DisableVerify) {
207 // Add common CodeGen passes.
209 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
212 addCodeEmitter(PM, OptLevel, JCE);
213 PM.add(createGCInfoDeleter());
215 return false; // success!
218 /// addPassesToEmitMC - Add passes to the specified pass manager to get
219 /// machine code emitted with the MCJIT. This method returns true if machine
220 /// code is not supported. It fills the MCContext Ctx pointer which can be
221 /// used to build custom MCStreamer.
223 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
226 CodeGenOpt::Level OptLevel,
227 bool DisableVerify) {
228 // Add common CodeGen passes.
229 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
232 if (hasMCSaveTempLabels())
233 Ctx->setAllowTemporaryLabels(false);
235 // Create the code emitter for the target if it exists. If not, .o file
237 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
238 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(),STI, *Ctx);
239 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple());
240 if (MCE == 0 || TAB == 0)
243 OwningPtr<MCStreamer> AsmStreamer;
244 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(), *Ctx,
247 hasMCNoExecStack()));
248 AsmStreamer.get()->InitSections();
250 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
251 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
255 // If successful, createAsmPrinter took ownership of AsmStreamer.
260 return false; // success!
263 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
264 if (PrintMachineCode)
265 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
268 static void printAndVerify(PassManagerBase &PM,
269 const char *Banner) {
270 if (PrintMachineCode)
271 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
273 if (VerifyMachineCode)
274 PM.add(createMachineVerifierPass(Banner));
277 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
278 /// emitting to assembly files or machine code output.
280 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
281 CodeGenOpt::Level OptLevel,
283 MCContext *&OutContext) {
284 // Standard LLVM-Level Passes.
286 // Basic AliasAnalysis support.
287 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
288 // BasicAliasAnalysis wins if they disagree. This is intended to help
289 // support "obvious" type-punning idioms.
290 PM.add(createTypeBasedAliasAnalysisPass());
291 PM.add(createBasicAliasAnalysisPass());
293 // Before running any passes, run the verifier to determine if the input
294 // coming from the front-end and/or optimizer is valid.
296 PM.add(createVerifierPass());
298 // Run loop strength reduction before anything else.
299 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
300 PM.add(createLoopStrengthReducePass(getTargetLowering()));
302 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
305 PM.add(createGCLoweringPass());
307 // Make sure that no unreachable blocks are instruction selected.
308 PM.add(createUnreachableBlockEliminationPass());
310 // Turn exception handling constructs into something the code generators can
312 switch (getMCAsmInfo()->getExceptionHandlingType()) {
313 case ExceptionHandling::SjLj:
314 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
315 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
316 // catch info can get misplaced when a selector ends up more than one block
317 // removed from the parent invoke(s). This could happen when a landing
318 // pad is shared by multiple invokes and is also a target of a normal
319 // edge from elsewhere.
320 PM.add(createSjLjEHPass(getTargetLowering()));
322 case ExceptionHandling::DwarfCFI:
323 case ExceptionHandling::ARM:
324 case ExceptionHandling::Win64:
325 PM.add(createDwarfEHPass(this));
327 case ExceptionHandling::None:
328 PM.add(createLowerInvokePass(getTargetLowering()));
330 // The lower invoke pass may create unreachable code. Remove it.
331 PM.add(createUnreachableBlockEliminationPass());
335 if (OptLevel != CodeGenOpt::None && !DisableCGP)
336 PM.add(createCodeGenPreparePass(getTargetLowering()));
338 PM.add(createStackProtectorPass(getTargetLowering()));
340 addPreISel(PM, OptLevel);
343 PM.add(createPrintFunctionPass("\n\n"
344 "*** Final LLVM Code input to ISel ***\n",
347 // All passes which modify the LLVM IR are now complete; run the verifier
348 // to ensure that the IR is valid.
350 PM.add(createVerifierPass());
352 // Standard Lower-Level Passes.
354 // Install a MachineModuleInfo class, which is an immutable pass that holds
355 // all the per-module stuff we're generating, including MCContext.
356 TargetAsmInfo *TAI = new TargetAsmInfo(*this);
357 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
359 &getTargetLowering()->getObjFileLowering(),
362 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
364 // Set up a MachineFunction for the rest of CodeGen to work on.
365 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
367 // Enable FastISel with -fast, but allow that to be overridden.
368 if (EnableFastISelOption == cl::BOU_TRUE ||
369 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
370 EnableFastISel = true;
372 // Ask the target for an isel.
373 if (addInstSelector(PM, OptLevel))
376 // Print the instruction selected machine code...
377 printAndVerify(PM, "After Instruction Selection");
379 // Expand pseudo-instructions emitted by ISel.
380 PM.add(createExpandISelPseudosPass());
382 // Pre-ra tail duplication.
383 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
384 PM.add(createTailDuplicatePass(true));
385 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
388 // Optimize PHIs before DCE: removing dead PHI cycles may make more
389 // instructions dead.
390 if (OptLevel != CodeGenOpt::None)
391 PM.add(createOptimizePHIsPass());
393 // If the target requests it, assign local variables to stack slots relative
394 // to one another and simplify frame index references where possible.
395 PM.add(createLocalStackSlotAllocationPass());
397 if (OptLevel != CodeGenOpt::None) {
398 // With optimization, dead code should already be eliminated. However
399 // there is one known exception: lowered code for arguments that are only
400 // used by tail calls, where the tail calls reuse the incoming stack
401 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
402 PM.add(createDeadMachineInstructionElimPass());
403 printAndVerify(PM, "After codegen DCE pass");
405 if (!DisableMachineLICM)
406 PM.add(createMachineLICMPass());
407 PM.add(createMachineCSEPass());
408 if (!DisableMachineSink)
409 PM.add(createMachineSinkingPass());
410 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
412 PM.add(createPeepholeOptimizerPass());
413 printAndVerify(PM, "After codegen peephole optimization pass");
416 // Run pre-ra passes.
417 if (addPreRegAlloc(PM, OptLevel))
418 printAndVerify(PM, "After PreRegAlloc passes");
420 // Perform register allocation.
421 PM.add(createRegisterAllocator(OptLevel));
422 printAndVerify(PM, "After Register Allocation");
424 // Perform stack slot coloring and post-ra machine LICM.
425 if (OptLevel != CodeGenOpt::None) {
426 // FIXME: Re-enable coloring with register when it's capable of adding
429 PM.add(createStackSlotColoringPass(false));
431 // Run post-ra machine LICM to hoist reloads / remats.
432 if (!DisablePostRAMachineLICM)
433 PM.add(createMachineLICMPass(false));
435 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
438 // Run post-ra passes.
439 if (addPostRegAlloc(PM, OptLevel))
440 printAndVerify(PM, "After PostRegAlloc passes");
442 PM.add(createLowerSubregsPass());
443 printAndVerify(PM, "After LowerSubregs");
445 // Insert prolog/epilog code. Eliminate abstract frame index references...
446 PM.add(createPrologEpilogCodeInserter());
447 printAndVerify(PM, "After PrologEpilogCodeInserter");
449 // Run pre-sched2 passes.
450 if (addPreSched2(PM, OptLevel))
451 printAndVerify(PM, "After PreSched2 passes");
453 // Second pass scheduler.
454 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
455 PM.add(createPostRAScheduler(OptLevel));
456 printAndVerify(PM, "After PostRAScheduler");
459 // Branch folding must be run after regalloc and prolog/epilog insertion.
460 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
461 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
462 printNoVerify(PM, "After BranchFolding");
466 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
467 PM.add(createTailDuplicatePass(false));
468 printNoVerify(PM, "After TailDuplicate");
471 PM.add(createGCMachineCodeAnalysisPass());
474 PM.add(createGCInfoPrinter(dbgs()));
476 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
477 PM.add(createCodePlacementOptPass());
478 printNoVerify(PM, "After CodePlacementOpt");
481 if (addPreEmitPass(PM, OptLevel))
482 printNoVerify(PM, "After PreEmit passes");