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"
39 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
40 cl::desc("Disable Post Regalloc"));
41 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
42 cl::desc("Disable branch folding"));
43 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
44 cl::desc("Disable tail duplication"));
45 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
46 cl::desc("Disable pre-register allocation tail duplication"));
47 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
48 cl::desc("Disable code placement"));
49 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
50 cl::desc("Disable Stack Slot Coloring"));
51 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
52 cl::desc("Disable Machine LICM"));
53 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
55 cl::desc("Disable Machine LICM"));
56 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
57 cl::desc("Disable Machine Sinking"));
58 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
59 cl::desc("Disable Loop Strength Reduction Pass"));
60 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
61 cl::desc("Disable Codegen Prepare"));
62 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
63 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
64 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
65 cl::desc("Print LLVM IR input to isel pass"));
66 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
67 cl::desc("Dump garbage collector data"));
68 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
69 cl::desc("Show encoding in .s output"));
70 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
71 cl::desc("Show instruction structure in .s output"));
72 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
73 cl::desc("Enable MC API logging"));
74 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
75 cl::desc("Verify generated machine code"),
76 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
78 static cl::opt<cl::boolOrDefault>
79 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
80 cl::init(cl::BOU_UNSET));
82 static bool getVerboseAsm() {
85 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
86 case cl::BOU_TRUE: return true;
87 case cl::BOU_FALSE: return false;
91 // Enable or disable FastISel. Both options are needed, because
92 // FastISel is enabled by default with -fast, and we wish to be
93 // able to enable or disable fast-isel independently from -O0.
94 static cl::opt<cl::boolOrDefault>
95 EnableFastISelOption("fast-isel", cl::Hidden,
96 cl::desc("Enable the \"fast\" instruction selector"));
98 // Enable or disable an experimental optimization to split GEPs
99 // and run a special GVN pass which does not examine loads, in
100 // an effort to factor out redundancy implicit in complex GEPs.
101 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
102 cl::desc("Split GEPs and run no-load GVN"));
104 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
105 const std::string &Triple)
106 : TargetMachine(T), TargetTriple(Triple) {
107 AsmInfo = T.createAsmInfo(TargetTriple);
110 // Set the default code model for the JIT for a generic target.
111 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
112 void LLVMTargetMachine::setCodeModelForJIT() {
113 setCodeModel(CodeModel::Small);
116 // Set the default code model for static compilation for a generic target.
117 void LLVMTargetMachine::setCodeModelForStatic() {
118 setCodeModel(CodeModel::Small);
121 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
122 formatted_raw_ostream &Out,
123 CodeGenFileType FileType,
124 CodeGenOpt::Level OptLevel,
125 bool DisableVerify) {
126 // Add common CodeGen passes.
127 MCContext *Context = 0;
128 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
130 assert(Context != 0 && "Failed to get MCContext");
132 const MCAsmInfo &MAI = *getMCAsmInfo();
133 OwningPtr<MCStreamer> AsmStreamer;
136 default: return true;
137 case CGFT_AssemblyFile: {
138 MCInstPrinter *InstPrinter =
139 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
141 // Create a code emitter if asked to show the encoding.
143 // FIXME: These are currently leaked.
144 MCCodeEmitter *MCE = 0;
146 MCE = getTarget().createCodeEmitter(*this, *Context);
148 AsmStreamer.reset(createAsmStreamer(*Context, Out,
149 getTargetData()->isLittleEndian(),
150 getVerboseAsm(), InstPrinter,
154 case CGFT_ObjectFile: {
155 // Create the code emitter for the target if it exists. If not, .o file
158 // FIXME: These are currently leaked.
159 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
160 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
161 if (MCE == 0 || TAB == 0)
164 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context,
170 // The Null output is intended for use for performance analysis and testing,
172 AsmStreamer.reset(createNullStreamer(*Context));
177 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
179 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
180 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
184 // If successful, createAsmPrinter took ownership of AsmStreamer.
189 // Make sure the code model is set.
190 setCodeModelForStatic();
191 PM.add(createGCInfoDeleter());
195 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
196 /// get machine code emitted. This uses a JITCodeEmitter object to handle
197 /// actually outputting the machine code and resolving things like the address
198 /// of functions. This method should returns true if machine code emission is
201 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
203 CodeGenOpt::Level OptLevel,
204 bool DisableVerify) {
205 // Make sure the code model is set.
206 setCodeModelForJIT();
208 // Add common CodeGen passes.
210 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
213 addCodeEmitter(PM, OptLevel, JCE);
214 PM.add(createGCInfoDeleter());
216 return false; // success!
219 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
220 if (PrintMachineCode)
221 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
224 static void printAndVerify(PassManagerBase &PM,
226 bool allowDoubleDefs = false) {
227 if (PrintMachineCode)
228 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
230 if (VerifyMachineCode)
231 PM.add(createMachineVerifierPass(allowDoubleDefs));
234 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
235 /// emitting to assembly files or machine code output.
237 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
238 CodeGenOpt::Level OptLevel,
240 MCContext *&OutContext) {
241 // Standard LLVM-Level Passes.
243 // Before running any passes, run the verifier to determine if the input
244 // coming from the front-end and/or optimizer is valid.
246 PM.add(createVerifierPass());
248 // Optionally, tun split-GEPs and no-load GVN.
249 if (EnableSplitGEPGVN) {
250 PM.add(createGEPSplitterPass());
251 PM.add(createGVNPass(/*NoLoads=*/true));
254 // Run loop strength reduction before anything else.
255 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
256 PM.add(createLoopStrengthReducePass(getTargetLowering()));
258 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
261 // Turn exception handling constructs into something the code generators can
263 switch (getMCAsmInfo()->getExceptionHandlingType()) {
264 case ExceptionHandling::SjLj:
265 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
266 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
267 // catch info can get misplaced when a selector ends up more than one block
268 // removed from the parent invoke(s). This could happen when a landing
269 // pad is shared by multiple invokes and is also a target of a normal
270 // edge from elsewhere.
271 PM.add(createSjLjEHPass(getTargetLowering()));
272 PM.add(createDwarfEHPass(this, OptLevel==CodeGenOpt::None));
274 case ExceptionHandling::Dwarf:
275 PM.add(createDwarfEHPass(this, OptLevel==CodeGenOpt::None));
277 case ExceptionHandling::None:
278 PM.add(createLowerInvokePass(getTargetLowering()));
282 PM.add(createGCLoweringPass());
284 // Make sure that no unreachable blocks are instruction selected.
285 PM.add(createUnreachableBlockEliminationPass());
287 if (OptLevel != CodeGenOpt::None && !DisableCGP)
288 PM.add(createCodeGenPreparePass(getTargetLowering()));
290 PM.add(createStackProtectorPass(getTargetLowering()));
293 PM.add(createPrintFunctionPass("\n\n"
294 "*** Final LLVM Code input to ISel ***\n",
297 // All passes which modify the LLVM IR are now complete; run the verifier
298 // to ensure that the IR is valid.
300 PM.add(createVerifierPass());
302 // Standard Lower-Level Passes.
304 // Install a MachineModuleInfo class, which is an immutable pass that holds
305 // all the per-module stuff we're generating, including MCContext.
306 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo());
308 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
311 // Set up a MachineFunction for the rest of CodeGen to work on.
312 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
314 // Enable FastISel with -fast, but allow that to be overridden.
315 if (EnableFastISelOption == cl::BOU_TRUE ||
316 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
317 EnableFastISel = true;
319 // Ask the target for an isel.
320 if (addInstSelector(PM, OptLevel))
323 // Print the instruction selected machine code...
324 printAndVerify(PM, "After Instruction Selection",
325 /* allowDoubleDefs= */ true);
327 // Optimize PHIs before DCE: removing dead PHI cycles may make more
328 // instructions dead.
329 if (OptLevel != CodeGenOpt::None)
330 PM.add(createOptimizePHIsPass());
332 if (OptLevel != CodeGenOpt::None) {
333 // With optimization, dead code should already be eliminated. However
334 // there is one known exception: lowered code for arguments that are only
335 // used by tail calls, where the tail calls reuse the incoming stack
336 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
337 PM.add(createDeadMachineInstructionElimPass());
338 printAndVerify(PM, "After codegen DCE pass",
339 /* allowDoubleDefs= */ true);
341 PM.add(createOptimizeExtsPass());
342 if (!DisableMachineLICM)
343 PM.add(createMachineLICMPass());
344 PM.add(createMachineCSEPass());
345 if (!DisableMachineSink)
346 PM.add(createMachineSinkingPass());
347 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes",
348 /* allowDoubleDefs= */ true);
351 // Pre-ra tail duplication.
352 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
353 PM.add(createTailDuplicatePass(true));
354 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
355 /* allowDoubleDefs= */ true);
358 // Run pre-ra passes.
359 if (addPreRegAlloc(PM, OptLevel))
360 printAndVerify(PM, "After PreRegAlloc passes",
361 /* allowDoubleDefs= */ true);
363 // Perform register allocation.
364 PM.add(createRegisterAllocator(OptLevel));
365 printAndVerify(PM, "After Register Allocation");
367 // Perform stack slot coloring and post-ra machine LICM.
368 if (OptLevel != CodeGenOpt::None) {
369 // FIXME: Re-enable coloring with register when it's capable of adding
372 PM.add(createStackSlotColoringPass(false));
374 // Run post-ra machine LICM to hoist reloads / remats.
375 if (!DisablePostRAMachineLICM)
376 PM.add(createMachineLICMPass(false));
378 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
381 // Run post-ra passes.
382 if (addPostRegAlloc(PM, OptLevel))
383 printAndVerify(PM, "After PostRegAlloc passes");
385 PM.add(createLowerSubregsPass());
386 printAndVerify(PM, "After LowerSubregs");
388 // Insert prolog/epilog code. Eliminate abstract frame index references...
389 PM.add(createPrologEpilogCodeInserter());
390 printAndVerify(PM, "After PrologEpilogCodeInserter");
392 // Run pre-sched2 passes.
393 if (addPreSched2(PM, OptLevel))
394 printAndVerify(PM, "After PreSched2 passes");
396 // Second pass scheduler.
397 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
398 PM.add(createPostRAScheduler(OptLevel));
399 printAndVerify(PM, "After PostRAScheduler");
402 // Branch folding must be run after regalloc and prolog/epilog insertion.
403 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
404 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
405 printNoVerify(PM, "After BranchFolding");
409 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
410 PM.add(createTailDuplicatePass(false));
411 printNoVerify(PM, "After TailDuplicate");
414 PM.add(createGCMachineCodeAnalysisPass());
417 PM.add(createGCInfoPrinter(dbgs()));
419 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
420 PM.add(createCodePlacementOptPass());
421 printNoVerify(PM, "After CodePlacementOpt");
424 if (addPreEmitPass(PM, OptLevel))
425 printNoVerify(PM, "After PreEmit passes");