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/Pass.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.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"
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> DisableMachineSink("disable-machine-sink", cl::Hidden,
55 cl::desc("Disable Machine Sinking"));
56 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
57 cl::desc("Disable Loop Strength Reduction Pass"));
58 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
59 cl::desc("Disable Codegen Prepare"));
60 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
61 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
62 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
63 cl::desc("Print LLVM IR input to isel pass"));
64 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
65 cl::desc("Dump garbage collector data"));
66 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
67 cl::desc("Verify generated machine code"),
68 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
70 static cl::opt<cl::boolOrDefault>
71 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
72 cl::init(cl::BOU_UNSET));
74 static bool getVerboseAsm() {
77 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
78 case cl::BOU_TRUE: return true;
79 case cl::BOU_FALSE: return false;
83 // Enable or disable FastISel. Both options are needed, because
84 // FastISel is enabled by default with -fast, and we wish to be
85 // able to enable or disable fast-isel independently from -O0.
86 static cl::opt<cl::boolOrDefault>
87 EnableFastISelOption("fast-isel", cl::Hidden,
88 cl::desc("Enable the \"fast\" instruction selector"));
90 // Enable or disable an experimental optimization to split GEPs
91 // and run a special GVN pass which does not examine loads, in
92 // an effort to factor out redundancy implicit in complex GEPs.
93 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
94 cl::desc("Split GEPs and run no-load GVN"));
96 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
97 const std::string &TargetTriple)
99 AsmInfo = T.createAsmInfo(TargetTriple);
102 // Set the default code model for the JIT for a generic target.
103 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
105 LLVMTargetMachine::setCodeModelForJIT() {
106 setCodeModel(CodeModel::Small);
109 // Set the default code model for static compilation for a generic target.
111 LLVMTargetMachine::setCodeModelForStatic() {
112 setCodeModel(CodeModel::Small);
115 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
116 formatted_raw_ostream &Out,
117 CodeGenFileType FileType,
118 CodeGenOpt::Level OptLevel) {
119 // Add common CodeGen passes.
120 if (addCommonCodeGenPasses(PM, OptLevel))
123 OwningPtr<MCContext> Context(new MCContext());
124 OwningPtr<MCStreamer> AsmStreamer;
126 formatted_raw_ostream *LegacyOutput;
128 default: return true;
129 case CGFT_AssemblyFile: {
130 const MCAsmInfo &MAI = *getMCAsmInfo();
131 MCInstPrinter *InstPrinter =
132 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, Out);
133 AsmStreamer.reset(createAsmStreamer(*Context, Out, MAI,
134 getTargetData()->isLittleEndian(),
135 getVerboseAsm(), InstPrinter,
137 // Set the AsmPrinter's "O" to the output file.
141 case CGFT_ObjectFile: {
142 // Create the code emitter for the target if it exists. If not, .o file
144 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
148 AsmStreamer.reset(createMachOStreamer(*Context, Out, MCE));
150 // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
151 // force it to come out stderr.
152 // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
154 LegacyOutput = new formatted_raw_ostream(errs());
158 // The Null output is intended for use for performance analysis and testing,
160 AsmStreamer.reset(createNullStreamer(*Context));
161 // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
162 // force it to come out stderr.
163 // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
165 LegacyOutput = new formatted_raw_ostream(errs());
169 // Create the AsmPrinter, which takes ownership of Context and AsmStreamer
171 FunctionPass *Printer =
172 getTarget().createAsmPrinter(*LegacyOutput, *this, *Context, *AsmStreamer,
177 // If successful, createAsmPrinter took ownership of AsmStreamer and Context.
178 Context.take(); AsmStreamer.take();
182 // Make sure the code model is set.
183 setCodeModelForStatic();
184 PM.add(createGCInfoDeleter());
188 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
189 /// get machine code emitted. This uses a JITCodeEmitter object to handle
190 /// actually outputting the machine code and resolving things like the address
191 /// of functions. This method should returns true if machine code emission is
194 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
196 CodeGenOpt::Level OptLevel) {
197 // Make sure the code model is set.
198 setCodeModelForJIT();
200 // Add common CodeGen passes.
201 if (addCommonCodeGenPasses(PM, OptLevel))
204 addCodeEmitter(PM, OptLevel, JCE);
205 PM.add(createGCInfoDeleter());
207 return false; // success!
210 static void printAndVerify(PassManagerBase &PM,
212 bool allowDoubleDefs = false) {
213 if (PrintMachineCode)
214 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
216 if (VerifyMachineCode)
217 PM.add(createMachineVerifierPass(allowDoubleDefs));
220 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
221 /// emitting to assembly files or machine code output.
223 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
224 CodeGenOpt::Level OptLevel) {
225 // Standard LLVM-Level Passes.
227 // Optionally, tun split-GEPs and no-load GVN.
228 if (EnableSplitGEPGVN) {
229 PM.add(createGEPSplitterPass());
230 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
233 // Run loop strength reduction before anything else.
234 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
235 PM.add(createLoopStrengthReducePass(getTargetLowering()));
237 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
239 PM.add(createVerifierPass());
243 // Turn exception handling constructs into something the code generators can
245 switch (getMCAsmInfo()->getExceptionHandlingType())
247 case ExceptionHandling::SjLj:
248 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
249 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
250 // catch info can get misplaced when a selector ends up more than one block
251 // removed from the parent invoke(s). This could happen when a landing
252 // pad is shared by multiple invokes and is also a target of a normal
253 // edge from elsewhere.
254 PM.add(createSjLjEHPass(getTargetLowering()));
255 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
257 case ExceptionHandling::Dwarf:
258 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
260 case ExceptionHandling::None:
261 PM.add(createLowerInvokePass(getTargetLowering()));
265 PM.add(createGCLoweringPass());
267 // Make sure that no unreachable blocks are instruction selected.
268 PM.add(createUnreachableBlockEliminationPass());
270 if (OptLevel != CodeGenOpt::None && !DisableCGP)
271 PM.add(createCodeGenPreparePass(getTargetLowering()));
273 PM.add(createStackProtectorPass(getTargetLowering()));
276 PM.add(createPrintFunctionPass("\n\n"
277 "*** Final LLVM Code input to ISel ***\n",
280 // Standard Lower-Level Passes.
282 // Set up a MachineFunction for the rest of CodeGen to work on.
283 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
285 // Enable FastISel with -fast, but allow that to be overridden.
286 if (EnableFastISelOption == cl::BOU_TRUE ||
287 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
288 EnableFastISel = true;
290 // Ask the target for an isel.
291 if (addInstSelector(PM, OptLevel))
294 // Print the instruction selected machine code...
295 printAndVerify(PM, "After Instruction Selection",
296 /* allowDoubleDefs= */ true);
298 // Optimize PHIs before DCE: removing dead PHI cycles may make more
299 // instructions dead.
300 if (OptLevel != CodeGenOpt::None)
301 PM.add(createOptimizePHIsPass());
303 // Delete dead machine instructions regardless of optimization level.
304 PM.add(createDeadMachineInstructionElimPass());
305 printAndVerify(PM, "After codegen DCE pass",
306 /* allowDoubleDefs= */ true);
308 if (OptLevel != CodeGenOpt::None) {
309 PM.add(createOptimizeExtsPass());
310 if (!DisableMachineLICM)
311 PM.add(createMachineLICMPass());
312 if (!DisableMachineSink)
313 PM.add(createMachineSinkingPass());
314 printAndVerify(PM, "After MachineLICM and MachineSinking",
315 /* allowDoubleDefs= */ true);
318 // Pre-ra tail duplication.
319 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
320 PM.add(createTailDuplicatePass(true));
321 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
322 /* allowDoubleDefs= */ true);
325 // Run pre-ra passes.
326 if (addPreRegAlloc(PM, OptLevel))
327 printAndVerify(PM, "After PreRegAlloc passes",
328 /* allowDoubleDefs= */ true);
330 // Perform register allocation.
331 PM.add(createRegisterAllocator());
332 printAndVerify(PM, "After Register Allocation");
334 // Perform stack slot coloring.
335 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
336 // FIXME: Re-enable coloring with register when it's capable of adding
338 PM.add(createStackSlotColoringPass(false));
339 printAndVerify(PM, "After StackSlotColoring");
342 // Run post-ra passes.
343 if (addPostRegAlloc(PM, OptLevel))
344 printAndVerify(PM, "After PostRegAlloc passes");
346 PM.add(createLowerSubregsPass());
347 printAndVerify(PM, "After LowerSubregs");
349 // Insert prolog/epilog code. Eliminate abstract frame index references...
350 PM.add(createPrologEpilogCodeInserter());
351 printAndVerify(PM, "After PrologEpilogCodeInserter");
353 // Run pre-sched2 passes.
354 if (addPreSched2(PM, OptLevel))
355 printAndVerify(PM, "After PreSched2 passes");
357 // Second pass scheduler.
358 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
359 PM.add(createPostRAScheduler(OptLevel));
360 printAndVerify(PM, "After PostRAScheduler");
363 // Branch folding must be run after regalloc and prolog/epilog insertion.
364 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
365 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
366 printAndVerify(PM, "After BranchFolding");
370 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
371 PM.add(createTailDuplicatePass(false));
372 printAndVerify(PM, "After TailDuplicate");
375 PM.add(createGCMachineCodeAnalysisPass());
378 PM.add(createGCInfoPrinter(dbgs()));
380 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
381 PM.add(createCodePlacementOptPass());
382 printAndVerify(PM, "After CodePlacementOpt");
385 if (addPreEmitPass(PM, OptLevel))
386 printAndVerify(PM, "After PreEmit passes");