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/FileWriters.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/Target/TargetRegistry.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/FormattedStream.h"
36 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
37 cl::desc("Disable Post Regalloc"));
38 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
39 cl::desc("Disable branch folding"));
40 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
41 cl::desc("Disable tail duplication"));
42 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
43 cl::desc("Disable pre-register allocation tail duplication"));
44 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
45 cl::desc("Disable code placement"));
46 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
47 cl::desc("Disable Stack Slot Coloring"));
48 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
49 cl::desc("Disable Machine LICM"));
50 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
51 cl::desc("Disable Machine Sinking"));
52 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
53 cl::desc("Disable Loop Strength Reduction Pass"));
54 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
55 cl::desc("Disable Codegen Prepare"));
56 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
57 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
58 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
59 cl::desc("Print LLVM IR input to isel pass"));
60 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
61 cl::desc("Dump emitter generated instructions as assembly"));
62 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
63 cl::desc("Dump garbage collector data"));
64 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
65 cl::desc("Verify generated machine code"),
66 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
69 // Enable or disable FastISel. Both options are needed, because
70 // FastISel is enabled by default with -fast, and we wish to be
71 // able to enable or disable fast-isel independently from -O0.
72 static cl::opt<cl::boolOrDefault>
73 EnableFastISelOption("fast-isel", cl::Hidden,
74 cl::desc("Enable the \"fast\" instruction selector"));
76 // Enable or disable an experimental optimization to split GEPs
77 // and run a special GVN pass which does not examine loads, in
78 // an effort to factor out redundancy implicit in complex GEPs.
79 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
80 cl::desc("Split GEPs and run no-load GVN"));
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 (!addObjectFileEmitter(PM, OptLevel, Out))
119 return FileModel::MachOFile;
120 else if (getELFWriterInfo())
121 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 bool LLVMTargetMachine::addObjectFileEmitter(PassManagerBase &PM,
140 CodeGenOpt::Level OptLevel,
141 formatted_raw_ostream &Out) {
142 MCCodeEmitter *Emitter = getTarget().createCodeEmitter(*this);
146 PM.add(createMachOWriter(Out, *this, getMCAsmInfo(), Emitter));
150 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
151 /// be split up (e.g., to add an object writer pass), this method can be used to
152 /// finish up adding passes to emit the file, if necessary.
153 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
154 MachineCodeEmitter *MCE,
155 CodeGenOpt::Level OptLevel) {
156 // Make sure the code model is set.
157 setCodeModelForStatic();
160 addSimpleCodeEmitter(PM, OptLevel, *MCE);
162 addAssemblyEmitter(PM, OptLevel, true, ferrs());
164 PM.add(createGCInfoDeleter());
166 return false; // success!
169 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
170 /// be split up (e.g., to add an object writer pass), this method can be used to
171 /// finish up adding passes to emit the file, if necessary.
172 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
174 CodeGenOpt::Level OptLevel) {
175 // Make sure the code model is set.
176 setCodeModelForJIT();
179 addSimpleCodeEmitter(PM, OptLevel, *JCE);
181 addAssemblyEmitter(PM, OptLevel, true, ferrs());
183 PM.add(createGCInfoDeleter());
185 return false; // success!
188 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
189 /// be split up (e.g., to add an object writer pass), this method can be used to
190 /// finish up adding passes to emit the file, if necessary.
191 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
192 ObjectCodeEmitter *OCE,
193 CodeGenOpt::Level OptLevel) {
194 // Make sure the code model is set.
195 setCodeModelForStatic();
198 addSimpleCodeEmitter(PM, OptLevel, *OCE);
200 addAssemblyEmitter(PM, OptLevel, true, ferrs());
202 PM.add(createGCInfoDeleter());
204 return false; // success!
207 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
208 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
209 /// actually outputting the machine code and resolving things like the address
210 /// of functions. This method should returns true if machine code emission is
213 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
214 MachineCodeEmitter &MCE,
215 CodeGenOpt::Level OptLevel) {
216 // Make sure the code model is set.
217 setCodeModelForJIT();
219 // Add common CodeGen passes.
220 if (addCommonCodeGenPasses(PM, OptLevel))
223 addCodeEmitter(PM, OptLevel, MCE);
225 addAssemblyEmitter(PM, OptLevel, true, ferrs());
227 PM.add(createGCInfoDeleter());
229 return false; // success!
232 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
233 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
234 /// actually outputting the machine code and resolving things like the address
235 /// of functions. This method should returns true if machine code emission is
238 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
240 CodeGenOpt::Level OptLevel) {
241 // Make sure the code model is set.
242 setCodeModelForJIT();
244 // Add common CodeGen passes.
245 if (addCommonCodeGenPasses(PM, OptLevel))
248 addCodeEmitter(PM, OptLevel, JCE);
250 addAssemblyEmitter(PM, OptLevel, true, ferrs());
252 PM.add(createGCInfoDeleter());
254 return false; // success!
257 static void printAndVerify(PassManagerBase &PM,
259 bool allowDoubleDefs = false) {
260 if (PrintMachineCode)
261 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
263 if (VerifyMachineCode)
264 PM.add(createMachineVerifierPass(allowDoubleDefs));
267 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
268 /// emitting to assembly files or machine code output.
270 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
271 CodeGenOpt::Level OptLevel) {
272 // Standard LLVM-Level Passes.
274 // Optionally, tun split-GEPs and no-load GVN.
275 if (EnableSplitGEPGVN) {
276 PM.add(createGEPSplitterPass());
277 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
280 // Run loop strength reduction before anything else.
281 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
282 PM.add(createLoopStrengthReducePass(getTargetLowering()));
284 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
287 // Turn exception handling constructs into something the code generators can
289 switch (getMCAsmInfo()->getExceptionHandlingType())
291 case ExceptionHandling::SjLj:
292 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
293 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
294 // catch info can get misplaced when a selector ends up more than one block
295 // removed from the parent invoke(s). This could happen when a landing
296 // pad is shared by multiple invokes and is also a target of a normal
297 // edge from elsewhere.
298 PM.add(createSjLjEHPass(getTargetLowering()));
299 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
301 case ExceptionHandling::Dwarf:
302 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
304 case ExceptionHandling::None:
305 PM.add(createLowerInvokePass(getTargetLowering()));
309 PM.add(createGCLoweringPass());
311 // Make sure that no unreachable blocks are instruction selected.
312 PM.add(createUnreachableBlockEliminationPass());
314 if (OptLevel != CodeGenOpt::None && !DisableCGP)
315 PM.add(createCodeGenPreparePass(getTargetLowering()));
317 PM.add(createStackProtectorPass(getTargetLowering()));
320 PM.add(createPrintFunctionPass("\n\n"
321 "*** Final LLVM Code input to ISel ***\n",
324 // Standard Lower-Level Passes.
326 // Set up a MachineFunction for the rest of CodeGen to work on.
327 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
329 // Enable FastISel with -fast, but allow that to be overridden.
330 if (EnableFastISelOption == cl::BOU_TRUE ||
331 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
332 EnableFastISel = true;
334 // Ask the target for an isel.
335 if (addInstSelector(PM, OptLevel))
338 // Print the instruction selected machine code...
339 printAndVerify(PM, "After Instruction Selection",
340 /* allowDoubleDefs= */ true);
342 if (OptLevel != CodeGenOpt::None) {
343 PM.add(createOptimizeExtsPass());
344 if (!DisableMachineLICM)
345 PM.add(createMachineLICMPass());
346 if (!DisableMachineSink)
347 PM.add(createMachineSinkingPass());
348 printAndVerify(PM, "After MachineLICM and MachineSinking",
349 /* allowDoubleDefs= */ true);
352 // Pre-ra tail duplication.
353 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
354 PM.add(createTailDuplicatePass(true));
355 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
356 /* allowDoubleDefs= */ true);
359 // Run pre-ra passes.
360 if (addPreRegAlloc(PM, OptLevel))
361 printAndVerify(PM, "After PreRegAlloc passes",
362 /* allowDoubleDefs= */ true);
364 // Perform register allocation.
365 PM.add(createRegisterAllocator());
366 printAndVerify(PM, "After Register Allocation");
368 // Perform stack slot coloring.
369 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
370 // FIXME: Re-enable coloring with register when it's capable of adding
372 PM.add(createStackSlotColoringPass(false));
373 printAndVerify(PM, "After StackSlotColoring");
376 // Run post-ra passes.
377 if (addPostRegAlloc(PM, OptLevel))
378 printAndVerify(PM, "After PostRegAlloc passes");
380 PM.add(createLowerSubregsPass());
381 printAndVerify(PM, "After LowerSubregs");
383 // Insert prolog/epilog code. Eliminate abstract frame index references...
384 PM.add(createPrologEpilogCodeInserter());
385 printAndVerify(PM, "After PrologEpilogCodeInserter");
387 // Run pre-sched2 passes.
388 if (addPreSched2(PM, OptLevel))
389 printAndVerify(PM, "After PreSched2 passes");
391 // Second pass scheduler.
392 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
393 PM.add(createPostRAScheduler(OptLevel));
394 printAndVerify(PM, "After PostRAScheduler");
397 // Branch folding must be run after regalloc and prolog/epilog insertion.
398 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
399 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
400 printAndVerify(PM, "After BranchFolding");
404 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
405 PM.add(createTailDuplicatePass(false));
406 printAndVerify(PM, "After TailDuplicate");
409 PM.add(createGCMachineCodeAnalysisPass());
412 PM.add(createGCInfoPrinter(dbgs()));
414 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
415 PM.add(createCodePlacementOptPass());
416 printAndVerify(PM, "After CodePlacementOpt");
419 if (addPreEmitPass(PM, OptLevel))
420 printAndVerify(PM, "After PreEmit passes");