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/Verifier.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/StandardPasses.h"
41 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
42 cl::desc("Disable Post Regalloc"));
43 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
44 cl::desc("Disable branch folding"));
45 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
46 cl::desc("Disable tail duplication"));
47 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
48 cl::desc("Disable pre-register allocation tail duplication"));
49 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
50 cl::desc("Disable code placement"));
51 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
52 cl::desc("Disable Stack Slot Coloring"));
53 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
54 cl::desc("Disable Machine LICM"));
55 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
57 cl::desc("Disable Machine LICM"));
58 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
59 cl::desc("Disable Machine Sinking"));
60 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
61 cl::desc("Disable Loop Strength Reduction Pass"));
62 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
63 cl::desc("Disable Codegen Prepare"));
64 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
65 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
66 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
67 cl::desc("Print LLVM IR input to isel pass"));
68 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
69 cl::desc("Dump garbage collector data"));
70 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
71 cl::desc("Show encoding in .s output"));
72 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
73 cl::desc("Show instruction structure in .s output"));
74 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
75 cl::desc("Enable MC API logging"));
76 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
77 cl::desc("Verify generated machine code"),
78 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
80 static cl::opt<cl::boolOrDefault>
81 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
82 cl::init(cl::BOU_UNSET));
84 static bool getVerboseAsm() {
87 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
88 case cl::BOU_TRUE: return true;
89 case cl::BOU_FALSE: return false;
93 // Enable or disable FastISel. Both options are needed, because
94 // FastISel is enabled by default with -fast, and we wish to be
95 // able to enable or disable fast-isel independently from -O0.
96 static cl::opt<cl::boolOrDefault>
97 EnableFastISelOption("fast-isel", cl::Hidden,
98 cl::desc("Enable the \"fast\" instruction selector"));
100 // Enable or disable an experimental optimization to split GEPs
101 // and run a special GVN pass which does not examine loads, in
102 // an effort to factor out redundancy implicit in complex GEPs.
103 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
104 cl::desc("Split GEPs and run no-load GVN"));
106 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
107 const std::string &Triple)
108 : TargetMachine(T), TargetTriple(Triple) {
109 AsmInfo = T.createAsmInfo(TargetTriple);
112 // Set the default code model for the JIT for a generic target.
113 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
114 void LLVMTargetMachine::setCodeModelForJIT() {
115 setCodeModel(CodeModel::Small);
118 // Set the default code model for static compilation for a generic target.
119 void LLVMTargetMachine::setCodeModelForStatic() {
120 setCodeModel(CodeModel::Small);
123 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
124 formatted_raw_ostream &Out,
125 CodeGenFileType FileType,
126 CodeGenOpt::Level OptLevel,
127 bool DisableVerify) {
128 // Add common CodeGen passes.
129 MCContext *Context = 0;
130 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
132 assert(Context != 0 && "Failed to get MCContext");
134 const MCAsmInfo &MAI = *getMCAsmInfo();
135 OwningPtr<MCStreamer> AsmStreamer;
138 default: return true;
139 case CGFT_AssemblyFile: {
140 MCInstPrinter *InstPrinter =
141 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
143 // Create a code emitter if asked to show the encoding.
144 MCCodeEmitter *MCE = 0;
146 MCE = getTarget().createCodeEmitter(*this, *Context);
148 const TargetLoweringObjectFile &TLOF =
149 getTargetLowering()->getObjFileLowering();
150 int PointerSize = getTargetData()->getPointerSize();
154 S = getTarget().createAsmStreamer(*Context, Out,
155 getTargetData()->isLittleEndian(),
161 S = createAsmStreamerNoLoc(*Context, Out,
162 getTargetData()->isLittleEndian(),
169 AsmStreamer.reset(S);
172 case CGFT_ObjectFile: {
173 // Create the code emitter for the target if it exists. If not, .o file
175 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
176 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
177 if (MCE == 0 || TAB == 0)
180 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context,
183 AsmStreamer.get()->InitSections();
187 // The Null output is intended for use for performance analysis and testing,
189 AsmStreamer.reset(createNullStreamer(*Context));
194 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
196 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
197 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
201 // If successful, createAsmPrinter took ownership of AsmStreamer.
206 // Make sure the code model is set.
207 setCodeModelForStatic();
208 PM.add(createGCInfoDeleter());
212 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
213 /// get machine code emitted. This uses a JITCodeEmitter object to handle
214 /// actually outputting the machine code and resolving things like the address
215 /// of functions. This method should returns true if machine code emission is
218 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
220 CodeGenOpt::Level OptLevel,
221 bool DisableVerify) {
222 // Make sure the code model is set.
223 setCodeModelForJIT();
225 // Add common CodeGen passes.
227 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
230 addCodeEmitter(PM, OptLevel, JCE);
231 PM.add(createGCInfoDeleter());
233 return false; // success!
236 /// addPassesToEmitMC - Add passes to the specified pass manager to get
237 /// machine code emitted with the MCJIT. This method returns true if machine
238 /// code is not supported. It fills the MCContext Ctx pointer which can be
239 /// used to build custom MCStreamer.
241 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
243 CodeGenOpt::Level OptLevel,
244 bool DisableVerify) {
245 // Add common CodeGen passes.
246 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
248 // Make sure the code model is set.
249 setCodeModelForJIT();
251 return false; // success!
254 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
255 if (PrintMachineCode)
256 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
259 static void printAndVerify(PassManagerBase &PM,
260 const char *Banner) {
261 if (PrintMachineCode)
262 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
264 if (VerifyMachineCode)
265 PM.add(createMachineVerifierPass());
268 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
269 /// emitting to assembly files or machine code output.
271 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
272 CodeGenOpt::Level OptLevel,
274 MCContext *&OutContext) {
275 // Standard LLVM-Level Passes.
277 // Basic AliasAnalysis support.
278 createStandardAliasAnalysisPasses(&PM);
280 // Before running any passes, run the verifier to determine if the input
281 // coming from the front-end and/or optimizer is valid.
283 PM.add(createVerifierPass());
285 // Optionally, tun split-GEPs and no-load GVN.
286 if (EnableSplitGEPGVN) {
287 PM.add(createGEPSplitterPass());
288 PM.add(createGVNPass(/*NoLoads=*/true));
291 // Run loop strength reduction before anything else.
292 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
293 PM.add(createLoopStrengthReducePass(getTargetLowering()));
295 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
298 PM.add(createGCLoweringPass());
300 // Make sure that no unreachable blocks are instruction selected.
301 PM.add(createUnreachableBlockEliminationPass());
303 // Turn exception handling constructs into something the code generators can
305 switch (getMCAsmInfo()->getExceptionHandlingType()) {
306 case ExceptionHandling::SjLj:
307 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
308 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
309 // catch info can get misplaced when a selector ends up more than one block
310 // removed from the parent invoke(s). This could happen when a landing
311 // pad is shared by multiple invokes and is also a target of a normal
312 // edge from elsewhere.
313 PM.add(createSjLjEHPass(getTargetLowering()));
315 case ExceptionHandling::Dwarf:
316 PM.add(createDwarfEHPass(this));
318 case ExceptionHandling::None:
319 PM.add(createLowerInvokePass(getTargetLowering()));
321 // The lower invoke pass may create unreachable code. Remove it.
322 PM.add(createUnreachableBlockEliminationPass());
326 if (OptLevel != CodeGenOpt::None && !DisableCGP)
327 PM.add(createCodeGenPreparePass(getTargetLowering()));
329 PM.add(createStackProtectorPass(getTargetLowering()));
331 addPreISel(PM, OptLevel);
334 PM.add(createPrintFunctionPass("\n\n"
335 "*** Final LLVM Code input to ISel ***\n",
338 // All passes which modify the LLVM IR are now complete; run the verifier
339 // to ensure that the IR is valid.
341 PM.add(createVerifierPass());
343 // Standard Lower-Level Passes.
345 // Install a MachineModuleInfo class, which is an immutable pass that holds
346 // all the per-module stuff we're generating, including MCContext.
347 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo());
349 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
351 // Set up a MachineFunction for the rest of CodeGen to work on.
352 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
354 // Enable FastISel with -fast, but allow that to be overridden.
355 if (EnableFastISelOption == cl::BOU_TRUE ||
356 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
357 EnableFastISel = true;
359 // Ask the target for an isel.
360 if (addInstSelector(PM, OptLevel))
363 // Print the instruction selected machine code...
364 printAndVerify(PM, "After Instruction Selection");
366 // Expand pseudo-instructions emitted by ISel.
367 PM.add(createExpandISelPseudosPass());
369 // Optimize PHIs before DCE: removing dead PHI cycles may make more
370 // instructions dead.
371 if (OptLevel != CodeGenOpt::None)
372 PM.add(createOptimizePHIsPass());
374 // If the target requests it, assign local variables to stack slots relative
375 // to one another and simplify frame index references where possible.
376 PM.add(createLocalStackSlotAllocationPass());
378 if (OptLevel != CodeGenOpt::None) {
379 // With optimization, dead code should already be eliminated. However
380 // there is one known exception: lowered code for arguments that are only
381 // used by tail calls, where the tail calls reuse the incoming stack
382 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
383 PM.add(createDeadMachineInstructionElimPass());
384 printAndVerify(PM, "After codegen DCE pass");
386 if (!DisableMachineLICM)
387 PM.add(createMachineLICMPass());
388 PM.add(createMachineCSEPass());
389 if (!DisableMachineSink)
390 PM.add(createMachineSinkingPass());
391 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
393 PM.add(createPeepholeOptimizerPass());
394 printAndVerify(PM, "After codegen peephole optimization pass");
397 // Pre-ra tail duplication.
398 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
399 PM.add(createTailDuplicatePass(true));
400 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
403 // Run pre-ra passes.
404 if (addPreRegAlloc(PM, OptLevel))
405 printAndVerify(PM, "After PreRegAlloc passes");
407 // Perform register allocation.
408 PM.add(createRegisterAllocator(OptLevel));
409 printAndVerify(PM, "After Register Allocation");
411 // Perform stack slot coloring and post-ra machine LICM.
412 if (OptLevel != CodeGenOpt::None) {
413 // FIXME: Re-enable coloring with register when it's capable of adding
416 PM.add(createStackSlotColoringPass(false));
418 // Run post-ra machine LICM to hoist reloads / remats.
419 if (!DisablePostRAMachineLICM)
420 PM.add(createMachineLICMPass(false));
422 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
425 // Run post-ra passes.
426 if (addPostRegAlloc(PM, OptLevel))
427 printAndVerify(PM, "After PostRegAlloc passes");
429 PM.add(createLowerSubregsPass());
430 printAndVerify(PM, "After LowerSubregs");
432 // Insert prolog/epilog code. Eliminate abstract frame index references...
433 PM.add(createPrologEpilogCodeInserter());
434 printAndVerify(PM, "After PrologEpilogCodeInserter");
436 // Run pre-sched2 passes.
437 if (addPreSched2(PM, OptLevel))
438 printAndVerify(PM, "After PreSched2 passes");
440 // Second pass scheduler.
441 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
442 PM.add(createPostRAScheduler(OptLevel));
443 printAndVerify(PM, "After PostRAScheduler");
446 // Branch folding must be run after regalloc and prolog/epilog insertion.
447 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
448 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
449 printNoVerify(PM, "After BranchFolding");
453 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
454 PM.add(createTailDuplicatePass(false));
455 printNoVerify(PM, "After TailDuplicate");
458 PM.add(createGCMachineCodeAnalysisPass());
461 PM.add(createGCInfoPrinter(dbgs()));
463 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
464 PM.add(createCodePlacementOptPass());
465 printNoVerify(PM, "After CodePlacementOpt");
468 if (addPreEmitPass(PM, OptLevel))
469 printNoVerify(PM, "After PreEmit passes");