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/Assembly/PrintModulePass.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/GCStrategy.h"
21 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
22 #include "llvm/Target/TargetOptions.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/Target/TargetRegistry.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/FormattedStream.h"
35 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
36 cl::desc("Disable Post Regalloc"));
37 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
38 cl::desc("Disable branch folding"));
39 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
40 cl::desc("Disable tail duplication"));
41 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
42 cl::desc("Disable code placement"));
43 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
44 cl::desc("Disable Stack Slot Coloring"));
45 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
46 cl::desc("Disable Machine LICM"));
47 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
48 cl::desc("Disable Machine Sinking"));
49 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
50 cl::desc("Disable Loop Strength Reduction Pass"));
51 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
52 cl::desc("Disable Codegen Prepare"));
53 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
54 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
55 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
56 cl::desc("Print LLVM IR input to isel pass"));
57 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
58 cl::desc("Dump emitter generated instructions as assembly"));
59 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
60 cl::desc("Dump garbage collector data"));
61 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
62 cl::desc("Verify generated machine code"),
63 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
65 // Enable or disable FastISel. Both options are needed, because
66 // FastISel is enabled by default with -fast, and we wish to be
67 // able to enable or disable fast-isel independently from -O0.
68 static cl::opt<cl::boolOrDefault>
69 EnableFastISelOption("fast-isel", cl::Hidden,
70 cl::desc("Enable the \"fast\" instruction selector"));
72 // Enable or disable an experimental optimization to split GEPs
73 // and run a special GVN pass which does not examine loads, in
74 // an effort to factor out redundancy implicit in complex GEPs.
75 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
76 cl::desc("Split GEPs and run no-load GVN"));
78 static cl::opt<bool> PreAllocTailDup("pre-regalloc-taildup", cl::Hidden,
79 cl::desc("Pre-register allocation tail duplication"));
81 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
82 const std::string &TargetTriple)
84 AsmInfo = T.createAsmInfo(TargetTriple);
87 // Set the default code model for the JIT for a generic target.
88 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
90 LLVMTargetMachine::setCodeModelForJIT() {
91 setCodeModel(CodeModel::Small);
94 // Set the default code model for static compilation for a generic target.
96 LLVMTargetMachine::setCodeModelForStatic() {
97 setCodeModel(CodeModel::Small);
101 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
102 formatted_raw_ostream &Out,
103 CodeGenFileType FileType,
104 CodeGenOpt::Level OptLevel) {
105 // Add common CodeGen passes.
106 if (addCommonCodeGenPasses(PM, OptLevel))
107 return FileModel::Error;
112 case TargetMachine::AssemblyFile:
113 if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
114 return FileModel::Error;
115 return FileModel::AsmFile;
116 case TargetMachine::ObjectFile:
117 if (getMachOWriterInfo())
118 return FileModel::MachOFile;
119 else if (getELFWriterInfo())
120 return FileModel::ElfFile;
123 return FileModel::Error;
126 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
127 CodeGenOpt::Level OptLevel,
129 formatted_raw_ostream &Out) {
130 FunctionPass *Printer =
131 getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
139 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
140 /// be split up (e.g., to add an object writer pass), this method can be used to
141 /// finish up adding passes to emit the file, if necessary.
142 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
143 MachineCodeEmitter *MCE,
144 CodeGenOpt::Level OptLevel) {
145 // Make sure the code model is set.
146 setCodeModelForStatic();
149 addSimpleCodeEmitter(PM, OptLevel, *MCE);
151 addAssemblyEmitter(PM, OptLevel, true, ferrs());
153 PM.add(createGCInfoDeleter());
155 return false; // success!
158 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
159 /// be split up (e.g., to add an object writer pass), this method can be used to
160 /// finish up adding passes to emit the file, if necessary.
161 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
163 CodeGenOpt::Level OptLevel) {
164 // Make sure the code model is set.
165 setCodeModelForJIT();
168 addSimpleCodeEmitter(PM, OptLevel, *JCE);
170 addAssemblyEmitter(PM, OptLevel, true, ferrs());
172 PM.add(createGCInfoDeleter());
174 return false; // success!
177 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
178 /// be split up (e.g., to add an object writer pass), this method can be used to
179 /// finish up adding passes to emit the file, if necessary.
180 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
181 ObjectCodeEmitter *OCE,
182 CodeGenOpt::Level OptLevel) {
183 // Make sure the code model is set.
184 setCodeModelForStatic();
187 addSimpleCodeEmitter(PM, OptLevel, *OCE);
189 addAssemblyEmitter(PM, OptLevel, true, ferrs());
191 PM.add(createGCInfoDeleter());
193 return false; // success!
196 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
197 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
198 /// actually outputting the machine code and resolving things like the address
199 /// of functions. This method should returns true if machine code emission is
202 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
203 MachineCodeEmitter &MCE,
204 CodeGenOpt::Level OptLevel) {
205 // Make sure the code model is set.
206 setCodeModelForJIT();
208 // Add common CodeGen passes.
209 if (addCommonCodeGenPasses(PM, OptLevel))
212 addCodeEmitter(PM, OptLevel, MCE);
214 addAssemblyEmitter(PM, OptLevel, true, ferrs());
216 PM.add(createGCInfoDeleter());
218 return false; // success!
221 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
222 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
223 /// actually outputting the machine code and resolving things like the address
224 /// of functions. This method should returns true if machine code emission is
227 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
229 CodeGenOpt::Level OptLevel) {
230 // Make sure the code model is set.
231 setCodeModelForJIT();
233 // Add common CodeGen passes.
234 if (addCommonCodeGenPasses(PM, OptLevel))
237 addCodeEmitter(PM, OptLevel, JCE);
239 addAssemblyEmitter(PM, OptLevel, true, ferrs());
241 PM.add(createGCInfoDeleter());
243 return false; // success!
246 static void printAndVerify(PassManagerBase &PM,
248 bool allowDoubleDefs = false) {
249 if (PrintMachineCode)
250 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
252 if (VerifyMachineCode)
253 PM.add(createMachineVerifierPass(allowDoubleDefs));
256 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
257 /// emitting to assembly files or machine code output.
259 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
260 CodeGenOpt::Level OptLevel) {
261 // Standard LLVM-Level Passes.
263 // Optionally, tun split-GEPs and no-load GVN.
264 if (EnableSplitGEPGVN) {
265 PM.add(createGEPSplitterPass());
266 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
269 // Run loop strength reduction before anything else.
270 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
271 PM.add(createLoopStrengthReducePass(getTargetLowering()));
273 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
276 // Turn exception handling constructs into something the code generators can
278 switch (getMCAsmInfo()->getExceptionHandlingType())
280 case ExceptionHandling::SjLj:
281 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
282 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
283 PM.add(createSjLjEHPass(getTargetLowering()));
285 case ExceptionHandling::Dwarf:
286 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
288 case ExceptionHandling::None:
289 PM.add(createLowerInvokePass(getTargetLowering()));
293 PM.add(createGCLoweringPass());
295 // Make sure that no unreachable blocks are instruction selected.
296 PM.add(createUnreachableBlockEliminationPass());
298 if (OptLevel != CodeGenOpt::None && !DisableCGP)
299 PM.add(createCodeGenPreparePass(getTargetLowering()));
301 PM.add(createStackProtectorPass(getTargetLowering()));
304 PM.add(createPrintFunctionPass("\n\n"
305 "*** Final LLVM Code input to ISel ***\n",
308 // Standard Lower-Level Passes.
310 // Set up a MachineFunction for the rest of CodeGen to work on.
311 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
313 // Enable FastISel with -fast, but allow that to be overridden.
314 if (EnableFastISelOption == cl::BOU_TRUE ||
315 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
316 EnableFastISel = true;
318 // Ask the target for an isel.
319 if (addInstSelector(PM, OptLevel))
322 // Print the instruction selected machine code...
323 printAndVerify(PM, "After Instruction Selection",
324 /* allowDoubleDefs= */ true);
326 if (OptLevel != CodeGenOpt::None) {
327 if (!DisableMachineLICM)
328 PM.add(createMachineLICMPass());
329 if (!DisableMachineSink)
330 PM.add(createMachineSinkingPass());
331 printAndVerify(PM, "After MachineLICM and MachineSinking",
332 /* allowDoubleDefs= */ true);
335 // Pre-ra tail duplication.
336 if (OptLevel != CodeGenOpt::None &&
337 !DisableTailDuplicate && PreAllocTailDup) {
338 PM.add(createTailDuplicatePass(true));
339 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
342 // Run pre-ra passes.
343 if (addPreRegAlloc(PM, OptLevel))
344 printAndVerify(PM, "After PreRegAlloc passes",
345 /* allowDoubleDefs= */ true);
347 // Perform register allocation.
348 PM.add(createRegisterAllocator());
349 printAndVerify(PM, "After Register Allocation");
351 // Perform stack slot coloring.
352 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
353 // FIXME: Re-enable coloring with register when it's capable of adding
355 PM.add(createStackSlotColoringPass(false));
356 printAndVerify(PM, "After StackSlotColoring");
359 // Run post-ra passes.
360 if (addPostRegAlloc(PM, OptLevel))
361 printAndVerify(PM, "After PostRegAlloc passes");
363 PM.add(createLowerSubregsPass());
364 printAndVerify(PM, "After LowerSubregs");
366 // Insert prolog/epilog code. Eliminate abstract frame index references...
367 PM.add(createPrologEpilogCodeInserter());
368 printAndVerify(PM, "After PrologEpilogCodeInserter");
370 // Run pre-sched2 passes.
371 if (addPreSched2(PM, OptLevel))
372 printAndVerify(PM, "After PreSched2 passes");
374 // Second pass scheduler.
375 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
376 PM.add(createPostRAScheduler(OptLevel));
377 printAndVerify(PM, "After PostRAScheduler");
380 // Branch folding must be run after regalloc and prolog/epilog insertion.
381 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
382 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
383 printAndVerify(PM, "After BranchFolding");
387 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
388 PM.add(createTailDuplicatePass(false));
389 printAndVerify(PM, "After TailDuplicate");
392 PM.add(createGCMachineCodeAnalysisPass());
395 PM.add(createGCInfoPrinter(dbgs()));
397 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
398 PM.add(createCodePlacementOptPass());
399 printAndVerify(PM, "After CodePlacementOpt");
402 if (addPreEmitPass(PM, OptLevel))
403 printAndVerify(PM, "After PreEmit passes");