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/TargetOptions.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/StandardPasses.h"
40 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
41 cl::desc("Disable Post Regalloc"));
42 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
43 cl::desc("Disable branch folding"));
44 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
45 cl::desc("Disable tail duplication"));
46 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
47 cl::desc("Disable pre-register allocation tail duplication"));
48 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
49 cl::desc("Disable code placement"));
50 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
51 cl::desc("Disable Stack Slot Coloring"));
52 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
53 cl::desc("Disable Machine LICM"));
54 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
56 cl::desc("Disable Machine LICM"));
57 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
58 cl::desc("Disable Machine Sinking"));
59 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
60 cl::desc("Disable Loop Strength Reduction Pass"));
61 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
62 cl::desc("Disable Codegen Prepare"));
63 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
64 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
65 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
66 cl::desc("Print LLVM IR input to isel pass"));
67 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
68 cl::desc("Dump garbage collector data"));
69 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
70 cl::desc("Show encoding in .s output"));
71 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
72 cl::desc("Show instruction structure in .s output"));
73 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
74 cl::desc("Enable MC API logging"));
75 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
76 cl::desc("Verify generated machine code"),
77 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
79 static cl::opt<cl::boolOrDefault>
80 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
81 cl::init(cl::BOU_UNSET));
83 static bool getVerboseAsm() {
86 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
87 case cl::BOU_TRUE: return true;
88 case cl::BOU_FALSE: return false;
92 // Enable or disable FastISel. Both options are needed, because
93 // FastISel is enabled by default with -fast, and we wish to be
94 // able to enable or disable fast-isel independently from -O0.
95 static cl::opt<cl::boolOrDefault>
96 EnableFastISelOption("fast-isel", cl::Hidden,
97 cl::desc("Enable the \"fast\" instruction selector"));
99 // Enable or disable an experimental optimization to split GEPs
100 // and run a special GVN pass which does not examine loads, in
101 // an effort to factor out redundancy implicit in complex GEPs.
102 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
103 cl::desc("Split GEPs and run no-load GVN"));
105 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
106 const std::string &Triple)
107 : TargetMachine(T), TargetTriple(Triple) {
108 AsmInfo = T.createAsmInfo(TargetTriple);
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 const MCAsmInfo &MAI = *getMCAsmInfo();
134 OwningPtr<MCStreamer> AsmStreamer;
137 default: return true;
138 case CGFT_AssemblyFile: {
139 MCInstPrinter *InstPrinter =
140 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
142 // Create a code emitter if asked to show the encoding.
143 MCCodeEmitter *MCE = 0;
145 MCE = getTarget().createCodeEmitter(*this, *Context);
147 AsmStreamer.reset(getTarget().createAsmStreamer(*Context, Out,
148 getTargetData()->isLittleEndian(),
154 case CGFT_ObjectFile: {
155 // Create the code emitter for the target if it exists. If not, .o file
157 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
158 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
159 if (MCE == 0 || TAB == 0)
162 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context,
165 AsmStreamer.get()->InitSections();
169 // The Null output is intended for use for performance analysis and testing,
171 AsmStreamer.reset(createNullStreamer(*Context));
176 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
178 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
179 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
183 // If successful, createAsmPrinter took ownership of AsmStreamer.
188 // Make sure the code model is set.
189 setCodeModelForStatic();
190 PM.add(createGCInfoDeleter());
194 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
195 /// get machine code emitted. This uses a JITCodeEmitter object to handle
196 /// actually outputting the machine code and resolving things like the address
197 /// of functions. This method should returns true if machine code emission is
200 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
202 CodeGenOpt::Level OptLevel,
203 bool DisableVerify) {
204 // Make sure the code model is set.
205 setCodeModelForJIT();
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,
225 CodeGenOpt::Level OptLevel,
226 bool DisableVerify) {
227 // Add common CodeGen passes.
228 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
230 // Make sure the code model is set.
231 setCodeModelForJIT();
233 return false; // success!
236 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
237 if (PrintMachineCode)
238 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
241 static void printAndVerify(PassManagerBase &PM,
242 const char *Banner) {
243 if (PrintMachineCode)
244 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
246 if (VerifyMachineCode)
247 PM.add(createMachineVerifierPass());
250 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
251 /// emitting to assembly files or machine code output.
253 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
254 CodeGenOpt::Level OptLevel,
256 MCContext *&OutContext) {
257 // Standard LLVM-Level Passes.
259 // Basic AliasAnalysis support.
260 createStandardAliasAnalysisPasses(&PM);
262 // Before running any passes, run the verifier to determine if the input
263 // coming from the front-end and/or optimizer is valid.
265 PM.add(createVerifierPass());
267 // Optionally, tun split-GEPs and no-load GVN.
268 if (EnableSplitGEPGVN) {
269 PM.add(createGEPSplitterPass());
270 PM.add(createGVNPass(/*NoLoads=*/true));
273 // Run loop strength reduction before anything else.
274 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
275 PM.add(createLoopStrengthReducePass(getTargetLowering()));
277 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
280 PM.add(createGCLoweringPass());
282 // Make sure that no unreachable blocks are instruction selected.
283 PM.add(createUnreachableBlockEliminationPass());
285 // Turn exception handling constructs into something the code generators can
287 switch (getMCAsmInfo()->getExceptionHandlingType()) {
288 case ExceptionHandling::SjLj:
289 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
290 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
291 // catch info can get misplaced when a selector ends up more than one block
292 // removed from the parent invoke(s). This could happen when a landing
293 // pad is shared by multiple invokes and is also a target of a normal
294 // edge from elsewhere.
295 PM.add(createSjLjEHPass(getTargetLowering()));
297 case ExceptionHandling::Dwarf:
298 PM.add(createDwarfEHPass(this));
300 case ExceptionHandling::None:
301 PM.add(createLowerInvokePass(getTargetLowering()));
303 // The lower invoke pass may create unreachable code. Remove it.
304 PM.add(createUnreachableBlockEliminationPass());
308 if (OptLevel != CodeGenOpt::None && !DisableCGP)
309 PM.add(createCodeGenPreparePass(getTargetLowering()));
311 PM.add(createStackProtectorPass(getTargetLowering()));
313 addPreISel(PM, OptLevel);
316 PM.add(createPrintFunctionPass("\n\n"
317 "*** Final LLVM Code input to ISel ***\n",
320 // All passes which modify the LLVM IR are now complete; run the verifier
321 // to ensure that the IR is valid.
323 PM.add(createVerifierPass());
325 // Standard Lower-Level Passes.
327 // Install a MachineModuleInfo class, which is an immutable pass that holds
328 // all the per-module stuff we're generating, including MCContext.
329 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo());
331 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
333 // Set up a MachineFunction for the rest of CodeGen to work on.
334 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
336 // Enable FastISel with -fast, but allow that to be overridden.
337 if (EnableFastISelOption == cl::BOU_TRUE ||
338 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
339 EnableFastISel = true;
341 // Ask the target for an isel.
342 if (addInstSelector(PM, OptLevel))
345 // Print the instruction selected machine code...
346 printAndVerify(PM, "After Instruction Selection");
348 // Optimize PHIs before DCE: removing dead PHI cycles may make more
349 // instructions dead.
350 if (OptLevel != CodeGenOpt::None)
351 PM.add(createOptimizePHIsPass());
353 // If the target requests it, assign local variables to stack slots relative
354 // to one another and simplify frame index references where possible.
355 PM.add(createLocalStackSlotAllocationPass());
357 if (OptLevel != CodeGenOpt::None) {
358 // With optimization, dead code should already be eliminated. However
359 // there is one known exception: lowered code for arguments that are only
360 // used by tail calls, where the tail calls reuse the incoming stack
361 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
362 PM.add(createDeadMachineInstructionElimPass());
363 printAndVerify(PM, "After codegen DCE pass");
365 PM.add(createPeepholeOptimizerPass());
366 if (!DisableMachineLICM)
367 PM.add(createMachineLICMPass());
368 PM.add(createMachineCSEPass());
369 if (!DisableMachineSink)
370 PM.add(createMachineSinkingPass());
371 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
374 // Pre-ra tail duplication.
375 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
376 PM.add(createTailDuplicatePass(true));
377 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
380 // Run pre-ra passes.
381 if (addPreRegAlloc(PM, OptLevel))
382 printAndVerify(PM, "After PreRegAlloc passes");
384 // Perform register allocation.
385 PM.add(createRegisterAllocator(OptLevel));
386 printAndVerify(PM, "After Register Allocation");
388 // Perform stack slot coloring and post-ra machine LICM.
389 if (OptLevel != CodeGenOpt::None) {
390 // FIXME: Re-enable coloring with register when it's capable of adding
393 PM.add(createStackSlotColoringPass(false));
395 // Run post-ra machine LICM to hoist reloads / remats.
396 if (!DisablePostRAMachineLICM)
397 PM.add(createMachineLICMPass(false));
399 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
402 // Run post-ra passes.
403 if (addPostRegAlloc(PM, OptLevel))
404 printAndVerify(PM, "After PostRegAlloc passes");
406 PM.add(createLowerSubregsPass());
407 printAndVerify(PM, "After LowerSubregs");
409 // Insert prolog/epilog code. Eliminate abstract frame index references...
410 PM.add(createPrologEpilogCodeInserter());
411 printAndVerify(PM, "After PrologEpilogCodeInserter");
413 // Run pre-sched2 passes.
414 if (addPreSched2(PM, OptLevel))
415 printAndVerify(PM, "After PreSched2 passes");
417 // Second pass scheduler.
418 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
419 PM.add(createPostRAScheduler(OptLevel));
420 printAndVerify(PM, "After PostRAScheduler");
423 // Branch folding must be run after regalloc and prolog/epilog insertion.
424 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
425 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
426 printNoVerify(PM, "After BranchFolding");
430 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
431 PM.add(createTailDuplicatePass(false));
432 printNoVerify(PM, "After TailDuplicate");
435 PM.add(createGCMachineCodeAnalysisPass());
438 PM.add(createGCInfoPrinter(dbgs()));
440 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
441 PM.add(createCodePlacementOptPass());
442 printNoVerify(PM, "After CodePlacementOpt");
445 if (addPreEmitPass(PM, OptLevel))
446 printNoVerify(PM, "After PreEmit passes");