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));
66 // Enable or disable FastISel. Both options are needed, because
67 // FastISel is enabled by default with -fast, and we wish to be
68 // able to enable or disable fast-isel independently from -O0.
69 static cl::opt<cl::boolOrDefault>
70 EnableFastISelOption("fast-isel", cl::Hidden,
71 cl::desc("Enable the \"fast\" instruction selector"));
73 // Enable or disable an experimental optimization to split GEPs
74 // and run a special GVN pass which does not examine loads, in
75 // an effort to factor out redundancy implicit in complex GEPs.
76 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
77 cl::desc("Split GEPs and run no-load GVN"));
79 static cl::opt<bool> PreAllocTailDup("pre-regalloc-taildup", cl::Hidden,
80 cl::desc("Pre-register allocation tail duplication"));
82 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
83 const std::string &TargetTriple)
85 AsmInfo = T.createAsmInfo(TargetTriple);
88 // Set the default code model for the JIT for a generic target.
89 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
91 LLVMTargetMachine::setCodeModelForJIT() {
92 setCodeModel(CodeModel::Small);
95 // Set the default code model for static compilation for a generic target.
97 LLVMTargetMachine::setCodeModelForStatic() {
98 setCodeModel(CodeModel::Small);
102 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
103 formatted_raw_ostream &Out,
104 CodeGenFileType FileType,
105 CodeGenOpt::Level OptLevel) {
106 // Add common CodeGen passes.
107 if (addCommonCodeGenPasses(PM, OptLevel))
108 return FileModel::Error;
113 case TargetMachine::AssemblyFile:
114 if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
115 return FileModel::Error;
116 return FileModel::AsmFile;
117 case TargetMachine::ObjectFile:
118 if (getMachOWriterInfo())
119 return FileModel::MachOFile;
120 else if (getELFWriterInfo())
121 return FileModel::ElfFile;
124 return FileModel::Error;
127 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
128 CodeGenOpt::Level OptLevel,
130 formatted_raw_ostream &Out) {
131 FunctionPass *Printer =
132 getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
140 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
141 /// be split up (e.g., to add an object writer pass), this method can be used to
142 /// finish up adding passes to emit the file, if necessary.
143 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
144 MachineCodeEmitter *MCE,
145 CodeGenOpt::Level OptLevel) {
146 // Make sure the code model is set.
147 setCodeModelForStatic();
150 addSimpleCodeEmitter(PM, OptLevel, *MCE);
152 addAssemblyEmitter(PM, OptLevel, true, ferrs());
154 PM.add(createGCInfoDeleter());
156 return false; // success!
159 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
160 /// be split up (e.g., to add an object writer pass), this method can be used to
161 /// finish up adding passes to emit the file, if necessary.
162 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
164 CodeGenOpt::Level OptLevel) {
165 // Make sure the code model is set.
166 setCodeModelForJIT();
169 addSimpleCodeEmitter(PM, OptLevel, *JCE);
171 addAssemblyEmitter(PM, OptLevel, true, ferrs());
173 PM.add(createGCInfoDeleter());
175 return false; // success!
178 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
179 /// be split up (e.g., to add an object writer pass), this method can be used to
180 /// finish up adding passes to emit the file, if necessary.
181 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
182 ObjectCodeEmitter *OCE,
183 CodeGenOpt::Level OptLevel) {
184 // Make sure the code model is set.
185 setCodeModelForStatic();
188 addSimpleCodeEmitter(PM, OptLevel, *OCE);
190 addAssemblyEmitter(PM, OptLevel, true, ferrs());
192 PM.add(createGCInfoDeleter());
194 return false; // success!
197 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
198 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
199 /// actually outputting the machine code and resolving things like the address
200 /// of functions. This method should returns true if machine code emission is
203 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
204 MachineCodeEmitter &MCE,
205 CodeGenOpt::Level OptLevel) {
206 // Make sure the code model is set.
207 setCodeModelForJIT();
209 // Add common CodeGen passes.
210 if (addCommonCodeGenPasses(PM, OptLevel))
213 addCodeEmitter(PM, OptLevel, MCE);
215 addAssemblyEmitter(PM, OptLevel, true, ferrs());
217 PM.add(createGCInfoDeleter());
219 return false; // success!
222 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
223 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
224 /// actually outputting the machine code and resolving things like the address
225 /// of functions. This method should returns true if machine code emission is
228 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
230 CodeGenOpt::Level OptLevel) {
231 // Make sure the code model is set.
232 setCodeModelForJIT();
234 // Add common CodeGen passes.
235 if (addCommonCodeGenPasses(PM, OptLevel))
238 addCodeEmitter(PM, OptLevel, JCE);
240 addAssemblyEmitter(PM, OptLevel, true, ferrs());
242 PM.add(createGCInfoDeleter());
244 return false; // success!
247 static void printAndVerify(PassManagerBase &PM,
249 bool allowDoubleDefs = false) {
250 if (PrintMachineCode)
251 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
253 if (VerifyMachineCode)
254 PM.add(createMachineVerifierPass(allowDoubleDefs));
257 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
258 /// emitting to assembly files or machine code output.
260 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
261 CodeGenOpt::Level OptLevel) {
262 // Standard LLVM-Level Passes.
264 // Optionally, tun split-GEPs and no-load GVN.
265 if (EnableSplitGEPGVN) {
266 PM.add(createGEPSplitterPass());
267 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
270 // Run loop strength reduction before anything else.
271 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
272 PM.add(createLoopStrengthReducePass(getTargetLowering()));
274 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
277 // Turn exception handling constructs into something the code generators can
279 switch (getMCAsmInfo()->getExceptionHandlingType())
281 case ExceptionHandling::SjLj:
282 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
283 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
284 // catch info can get misplaced when a selector ends up more than one block
285 // removed from the parent invoke(s). This could happen when a landing
286 // pad is shared by multiple invokes and is also a target of a normal
287 // edge from elsewhere.
288 PM.add(createSjLjEHPass(getTargetLowering()));
289 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
291 case ExceptionHandling::Dwarf:
292 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
294 case ExceptionHandling::None:
295 PM.add(createLowerInvokePass(getTargetLowering()));
299 PM.add(createGCLoweringPass());
301 // Make sure that no unreachable blocks are instruction selected.
302 PM.add(createUnreachableBlockEliminationPass());
304 if (OptLevel != CodeGenOpt::None && !DisableCGP)
305 PM.add(createCodeGenPreparePass(getTargetLowering()));
307 PM.add(createStackProtectorPass(getTargetLowering()));
310 PM.add(createPrintFunctionPass("\n\n"
311 "*** Final LLVM Code input to ISel ***\n",
314 // Standard Lower-Level Passes.
316 // Set up a MachineFunction for the rest of CodeGen to work on.
317 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
319 // Enable FastISel with -fast, but allow that to be overridden.
320 if (EnableFastISelOption == cl::BOU_TRUE ||
321 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
322 EnableFastISel = true;
324 // Ask the target for an isel.
325 if (addInstSelector(PM, OptLevel))
328 // Print the instruction selected machine code...
329 printAndVerify(PM, "After Instruction Selection",
330 /* allowDoubleDefs= */ true);
332 if (OptLevel != CodeGenOpt::None) {
333 PM.add(createOptimizeExtsPass());
334 if (!DisableMachineLICM)
335 PM.add(createMachineLICMPass());
336 if (!DisableMachineSink)
337 PM.add(createMachineSinkingPass());
338 printAndVerify(PM, "After MachineLICM and MachineSinking",
339 /* allowDoubleDefs= */ true);
342 // Pre-ra tail duplication.
343 if (OptLevel != CodeGenOpt::None &&
344 !DisableTailDuplicate && PreAllocTailDup) {
345 PM.add(createTailDuplicatePass(true));
346 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
347 /* allowDoubleDefs= */ true);
350 // Run pre-ra passes.
351 if (addPreRegAlloc(PM, OptLevel))
352 printAndVerify(PM, "After PreRegAlloc passes",
353 /* allowDoubleDefs= */ true);
355 // Perform register allocation.
356 PM.add(createRegisterAllocator());
357 printAndVerify(PM, "After Register Allocation");
359 // Perform stack slot coloring.
360 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
361 // FIXME: Re-enable coloring with register when it's capable of adding
363 PM.add(createStackSlotColoringPass(false));
364 printAndVerify(PM, "After StackSlotColoring");
367 // Run post-ra passes.
368 if (addPostRegAlloc(PM, OptLevel))
369 printAndVerify(PM, "After PostRegAlloc passes");
371 PM.add(createLowerSubregsPass());
372 printAndVerify(PM, "After LowerSubregs");
374 // Insert prolog/epilog code. Eliminate abstract frame index references...
375 PM.add(createPrologEpilogCodeInserter());
376 printAndVerify(PM, "After PrologEpilogCodeInserter");
378 // Run pre-sched2 passes.
379 if (addPreSched2(PM, OptLevel))
380 printAndVerify(PM, "After PreSched2 passes");
382 // Second pass scheduler.
383 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
384 PM.add(createPostRAScheduler(OptLevel));
385 printAndVerify(PM, "After PostRAScheduler");
388 // Branch folding must be run after regalloc and prolog/epilog insertion.
389 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
390 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
391 printAndVerify(PM, "After BranchFolding");
395 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
396 PM.add(createTailDuplicatePass(false));
397 printAndVerify(PM, "After TailDuplicate");
400 PM.add(createGCMachineCodeAnalysisPass());
403 PM.add(createGCInfoPrinter(dbgs()));
405 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
406 PM.add(createCodePlacementOptPass());
407 printAndVerify(PM, "After CodePlacementOpt");
410 if (addPreEmitPass(PM, OptLevel))
411 printAndVerify(PM, "After PreEmit passes");