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<bool> EnableMachineCSE("enable-machine-cse", cl::Hidden,
71 cl::desc("Enable Machine CSE"));
73 static cl::opt<cl::boolOrDefault>
74 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
75 cl::init(cl::BOU_UNSET));
77 static bool getVerboseAsm() {
80 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
81 case cl::BOU_TRUE: return true;
82 case cl::BOU_FALSE: return false;
86 // Enable or disable FastISel. Both options are needed, because
87 // FastISel is enabled by default with -fast, and we wish to be
88 // able to enable or disable fast-isel independently from -O0.
89 static cl::opt<cl::boolOrDefault>
90 EnableFastISelOption("fast-isel", cl::Hidden,
91 cl::desc("Enable the \"fast\" instruction selector"));
93 // Enable or disable an experimental optimization to split GEPs
94 // and run a special GVN pass which does not examine loads, in
95 // an effort to factor out redundancy implicit in complex GEPs.
96 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
97 cl::desc("Split GEPs and run no-load GVN"));
99 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
100 const std::string &TargetTriple)
102 AsmInfo = T.createAsmInfo(TargetTriple);
105 // Set the default code model for the JIT for a generic target.
106 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
108 LLVMTargetMachine::setCodeModelForJIT() {
109 setCodeModel(CodeModel::Small);
112 // Set the default code model for static compilation for a generic target.
114 LLVMTargetMachine::setCodeModelForStatic() {
115 setCodeModel(CodeModel::Small);
118 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
119 formatted_raw_ostream &Out,
120 CodeGenFileType FileType,
121 CodeGenOpt::Level OptLevel,
122 bool DisableVerify) {
123 // Add common CodeGen passes.
124 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify))
127 OwningPtr<MCContext> Context(new MCContext());
128 OwningPtr<MCStreamer> AsmStreamer;
130 formatted_raw_ostream *LegacyOutput;
132 default: return true;
133 case CGFT_AssemblyFile: {
134 const MCAsmInfo &MAI = *getMCAsmInfo();
135 MCInstPrinter *InstPrinter =
136 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, Out);
137 AsmStreamer.reset(createAsmStreamer(*Context, Out, MAI,
138 getTargetData()->isLittleEndian(),
139 getVerboseAsm(), InstPrinter,
141 // Set the AsmPrinter's "O" to the output file.
145 case CGFT_ObjectFile: {
146 // Create the code emitter for the target if it exists. If not, .o file
148 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
152 AsmStreamer.reset(createMachOStreamer(*Context, Out, MCE));
154 // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
155 // force it to come out stderr.
156 // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
158 LegacyOutput = new formatted_raw_ostream(errs());
162 // The Null output is intended for use for performance analysis and testing,
164 AsmStreamer.reset(createNullStreamer(*Context));
165 // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
166 // force it to come out stderr.
167 // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
169 LegacyOutput = new formatted_raw_ostream(errs());
173 // Create the AsmPrinter, which takes ownership of Context and AsmStreamer
175 FunctionPass *Printer =
176 getTarget().createAsmPrinter(*LegacyOutput, *this, *Context, *AsmStreamer,
181 // If successful, createAsmPrinter took ownership of AsmStreamer and Context.
182 Context.take(); AsmStreamer.take();
186 // Make sure the code model is set.
187 setCodeModelForStatic();
188 PM.add(createGCInfoDeleter());
192 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
193 /// get machine code emitted. This uses a JITCodeEmitter object to handle
194 /// actually outputting the machine code and resolving things like the address
195 /// of functions. This method should returns true if machine code emission is
198 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
200 CodeGenOpt::Level OptLevel,
201 bool DisableVerify) {
202 // Make sure the code model is set.
203 setCodeModelForJIT();
205 // Add common CodeGen passes.
206 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify))
209 addCodeEmitter(PM, OptLevel, JCE);
210 PM.add(createGCInfoDeleter());
212 return false; // success!
215 static void printNoVerify(PassManagerBase &PM,
216 const char *Banner) {
217 if (PrintMachineCode)
218 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
221 static void printAndVerify(PassManagerBase &PM,
223 bool allowDoubleDefs = false) {
224 if (PrintMachineCode)
225 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
227 if (VerifyMachineCode)
228 PM.add(createMachineVerifierPass(allowDoubleDefs));
231 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
232 /// emitting to assembly files or machine code output.
234 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
235 CodeGenOpt::Level OptLevel,
236 bool DisableVerify) {
237 // Standard LLVM-Level Passes.
239 // Before running any passes, run the verifier to determine if the input
240 // coming from the front-end and/or optimizer is valid.
242 PM.add(createVerifierPass());
244 // Optionally, tun split-GEPs and no-load GVN.
245 if (EnableSplitGEPGVN) {
246 PM.add(createGEPSplitterPass());
247 PM.add(createGVNPass(/*NoLoads=*/true));
250 // Run loop strength reduction before anything else.
251 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
252 PM.add(createLoopStrengthReducePass(getTargetLowering()));
254 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
257 // Turn exception handling constructs into something the code generators can
259 switch (getMCAsmInfo()->getExceptionHandlingType())
261 case ExceptionHandling::SjLj:
262 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
263 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
264 // catch info can get misplaced when a selector ends up more than one block
265 // removed from the parent invoke(s). This could happen when a landing
266 // pad is shared by multiple invokes and is also a target of a normal
267 // edge from elsewhere.
268 PM.add(createSjLjEHPass(getTargetLowering()));
269 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
271 case ExceptionHandling::Dwarf:
272 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
274 case ExceptionHandling::None:
275 PM.add(createLowerInvokePass(getTargetLowering()));
279 PM.add(createGCLoweringPass());
281 // Make sure that no unreachable blocks are instruction selected.
282 PM.add(createUnreachableBlockEliminationPass());
284 if (OptLevel != CodeGenOpt::None && !DisableCGP)
285 PM.add(createCodeGenPreparePass(getTargetLowering()));
287 PM.add(createStackProtectorPass(getTargetLowering()));
290 PM.add(createPrintFunctionPass("\n\n"
291 "*** Final LLVM Code input to ISel ***\n",
294 // All passes which modify the LLVM IR are now complete; run the verifier
295 // to ensure that the IR is valid.
297 PM.add(createVerifierPass());
299 // Standard Lower-Level Passes.
301 // Set up a MachineFunction for the rest of CodeGen to work on.
302 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
304 // Enable FastISel with -fast, but allow that to be overridden.
305 if (EnableFastISelOption == cl::BOU_TRUE ||
306 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
307 EnableFastISel = true;
309 // Ask the target for an isel.
310 if (addInstSelector(PM, OptLevel))
313 // Print the instruction selected machine code...
314 printAndVerify(PM, "After Instruction Selection",
315 /* allowDoubleDefs= */ true);
317 // Optimize PHIs before DCE: removing dead PHI cycles may make more
318 // instructions dead.
319 if (OptLevel != CodeGenOpt::None)
320 PM.add(createOptimizePHIsPass());
322 // Delete dead machine instructions regardless of optimization level.
323 PM.add(createDeadMachineInstructionElimPass());
324 printAndVerify(PM, "After codegen DCE pass",
325 /* allowDoubleDefs= */ true);
327 if (OptLevel != CodeGenOpt::None) {
328 PM.add(createOptimizeExtsPass());
329 if (!DisableMachineLICM)
330 PM.add(createMachineLICMPass());
331 //if (EnableMachineCSE)
332 PM.add(createMachineCSEPass());
333 if (!DisableMachineSink)
334 PM.add(createMachineSinkingPass());
335 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes",
336 /* allowDoubleDefs= */ true);
339 // Pre-ra tail duplication.
340 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
341 PM.add(createTailDuplicatePass(true));
342 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
343 /* allowDoubleDefs= */ true);
346 // Run pre-ra passes.
347 if (addPreRegAlloc(PM, OptLevel))
348 printAndVerify(PM, "After PreRegAlloc passes",
349 /* allowDoubleDefs= */ true);
351 // Perform register allocation.
352 PM.add(createRegisterAllocator());
353 printAndVerify(PM, "After Register Allocation");
355 // Perform stack slot coloring.
356 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
357 // FIXME: Re-enable coloring with register when it's capable of adding
359 PM.add(createStackSlotColoringPass(false));
360 printAndVerify(PM, "After StackSlotColoring");
363 // Run post-ra passes.
364 if (addPostRegAlloc(PM, OptLevel))
365 printAndVerify(PM, "After PostRegAlloc passes");
367 PM.add(createLowerSubregsPass());
368 printAndVerify(PM, "After LowerSubregs");
370 // Insert prolog/epilog code. Eliminate abstract frame index references...
371 PM.add(createPrologEpilogCodeInserter());
372 printAndVerify(PM, "After PrologEpilogCodeInserter");
374 // Run pre-sched2 passes.
375 if (addPreSched2(PM, OptLevel))
376 printAndVerify(PM, "After PreSched2 passes");
378 // Second pass scheduler.
379 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
380 PM.add(createPostRAScheduler(OptLevel));
381 printAndVerify(PM, "After PostRAScheduler");
384 // Branch folding must be run after regalloc and prolog/epilog insertion.
385 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
386 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
387 printNoVerify(PM, "After BranchFolding");
391 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
392 PM.add(createTailDuplicatePass(false));
393 printNoVerify(PM, "After TailDuplicate");
396 PM.add(createGCMachineCodeAnalysisPass());
399 PM.add(createGCInfoPrinter(dbgs()));
401 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
402 PM.add(createCodePlacementOptPass());
403 printNoVerify(PM, "After CodePlacementOpt");
406 if (addPreEmitPass(PM, OptLevel))
407 printNoVerify(PM, "After PreEmit passes");