1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVMTargetMachine class.
11 //
12 //===----------------------------------------------------------------------===//
13 
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/Analysis/LoopPass.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/GCStrategy.h"
21 #include "llvm/Target/TargetOptions.h"
22 #include "llvm/Target/TargetAsmInfo.h"
23 #include "llvm/Target/TargetRegistry.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FormattedStream.h"
27 using namespace llvm;
28 
29 namespace llvm {
30   bool EnableFastISel;
31 }
32 
33 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
34     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
35 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
36     cl::desc("Print LLVM IR input to isel pass"));
37 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
38     cl::desc("Dump emitter generated instructions as assembly"));
39 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
40     cl::desc("Dump garbage collector data"));
41 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
42     cl::desc("Verify generated machine code"),
43     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
44 
45 // When this works it will be on by default.
46 static cl::opt<bool>
47 DisablePostRAScheduler("disable-post-RA-scheduler",
48                        cl::desc("Disable scheduling after register allocation"),
49                        cl::init(true));
50 
51 // Enable or disable FastISel. Both options are needed, because
52 // FastISel is enabled by default with -fast, and we wish to be
53 // able to enable or disable fast-isel independently from -fast.
54 static cl::opt<cl::boolOrDefault>
55 EnableFastISelOption("fast-isel", cl::Hidden,
56   cl::desc("Enable the experimental \"fast\" instruction selector"));
57 
58 FileModel::Model
59 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
60                                        formatted_raw_ostream &Out,
61                                        CodeGenFileType FileType,
62                                        CodeGenOpt::Level OptLevel) {
63   // Add common CodeGen passes.
64   if (addCommonCodeGenPasses(PM, OptLevel))
65     return FileModel::Error;
66 
67   // Fold redundant debug labels.
68   PM.add(createDebugLabelFoldingPass());
69 
70   if (PrintMachineCode)
71     PM.add(createMachineFunctionPrinterPass(cerr));
72 
73   if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
74     PM.add(createMachineFunctionPrinterPass(cerr));
75 
76   if (OptLevel != CodeGenOpt::None)
77     PM.add(createCodePlacementOptPass());
78 
79   switch (FileType) {
80   default:
81     break;
82   case TargetMachine::AssemblyFile:
83     if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
84       return FileModel::Error;
85     return FileModel::AsmFile;
86   case TargetMachine::ObjectFile:
87     if (getMachOWriterInfo())
88       return FileModel::MachOFile;
89     else if (getELFWriterInfo())
90       return FileModel::ElfFile;
91   }
92 
93   return FileModel::Error;
94 }
95 
96 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
97                                            CodeGenOpt::Level OptLevel,
98                                            bool Verbose,
99                                            formatted_raw_ostream &Out) {
100   FunctionPass *Printer = getTarget().createAsmPrinter(Out, *this, Verbose);
101   if (!Printer)
102     return true;
103 
104   PM.add(Printer);
105   return false;
106 }
107 
108 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
109 /// be split up (e.g., to add an object writer pass), this method can be used to
110 /// finish up adding passes to emit the file, if necessary.
111 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
112                                                   MachineCodeEmitter *MCE,
113                                                   CodeGenOpt::Level OptLevel) {
114   if (MCE)
115     addSimpleCodeEmitter(PM, OptLevel, *MCE);
116   if (PrintEmittedAsm)
117     addAssemblyEmitter(PM, OptLevel, true, ferrs());
118 
119   PM.add(createGCInfoDeleter());
120 
121   // Delete machine code for this function
122   PM.add(createMachineCodeDeleter());
123 
124   return false; // success!
125 }
126 
127 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
128 /// be split up (e.g., to add an object writer pass), this method can be used to
129 /// finish up adding passes to emit the file, if necessary.
130 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
131                                                   JITCodeEmitter *JCE,
132                                                   CodeGenOpt::Level OptLevel) {
133   if (JCE)
134     addSimpleCodeEmitter(PM, OptLevel, *JCE);
135   if (PrintEmittedAsm)
136     addAssemblyEmitter(PM, OptLevel, true, ferrs());
137 
138   PM.add(createGCInfoDeleter());
139 
140   // Delete machine code for this function
141   PM.add(createMachineCodeDeleter());
142 
143   return false; // success!
144 }
145 
146 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
147 /// be split up (e.g., to add an object writer pass), this method can be used to
148 /// finish up adding passes to emit the file, if necessary.
149 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
150                                                   ObjectCodeEmitter *OCE,
151                                                   CodeGenOpt::Level OptLevel) {
152   if (OCE)
153     addSimpleCodeEmitter(PM, OptLevel, *OCE);
154   if (PrintEmittedAsm)
155     addAssemblyEmitter(PM, OptLevel, true, ferrs());
156 
157   PM.add(createGCInfoDeleter());
158 
159   // Delete machine code for this function
160   PM.add(createMachineCodeDeleter());
161 
162   return false; // success!
163 }
164 
165 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
166 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
167 /// actually outputting the machine code and resolving things like the address
168 /// of functions.  This method should returns true if machine code emission is
169 /// not supported.
170 ///
171 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
172                                                    MachineCodeEmitter &MCE,
173                                                    CodeGenOpt::Level OptLevel) {
174   // Add common CodeGen passes.
175   if (addCommonCodeGenPasses(PM, OptLevel))
176     return true;
177 
178   if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
179     PM.add(createMachineFunctionPrinterPass(cerr));
180 
181   addCodeEmitter(PM, OptLevel, MCE);
182   if (PrintEmittedAsm)
183     addAssemblyEmitter(PM, OptLevel, true, ferrs());
184 
185   PM.add(createGCInfoDeleter());
186 
187   // Delete machine code for this function
188   PM.add(createMachineCodeDeleter());
189 
190   return false; // success!
191 }
192 
193 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
194 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
195 /// actually outputting the machine code and resolving things like the address
196 /// of functions.  This method should returns true if machine code emission is
197 /// not supported.
198 ///
199 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
200                                                    JITCodeEmitter &JCE,
201                                                    CodeGenOpt::Level OptLevel) {
202   // Add common CodeGen passes.
203   if (addCommonCodeGenPasses(PM, OptLevel))
204     return true;
205 
206   if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
207     PM.add(createMachineFunctionPrinterPass(cerr));
208 
209   addCodeEmitter(PM, OptLevel, JCE);
210   if (PrintEmittedAsm)
211     addAssemblyEmitter(PM, OptLevel, true, ferrs());
212 
213   PM.add(createGCInfoDeleter());
214 
215   // Delete machine code for this function
216   PM.add(createMachineCodeDeleter());
217 
218   return false; // success!
219 }
220 
221 static void printAndVerify(PassManagerBase &PM,
222                            bool allowDoubleDefs = false) {
223   if (PrintMachineCode)
224     PM.add(createMachineFunctionPrinterPass(cerr));
225 
226   if (VerifyMachineCode)
227     PM.add(createMachineVerifierPass(allowDoubleDefs));
228 }
229 
230 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
231 /// emitting to assembly files or machine code output.
232 ///
233 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
234                                                CodeGenOpt::Level OptLevel) {
235   // Standard LLVM-Level Passes.
236 
237   // Run loop strength reduction before anything else.
238   if (OptLevel != CodeGenOpt::None) {
239     PM.add(createLoopStrengthReducePass(getTargetLowering()));
240     if (PrintLSR)
241       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
242   }
243 
244   // Turn exception handling constructs into something the code generators can
245   // handle.
246   if (!getTargetAsmInfo()->doesSupportExceptionHandling())
247     PM.add(createLowerInvokePass(getTargetLowering()));
248   else
249     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
250 
251   PM.add(createGCLoweringPass());
252 
253   // Make sure that no unreachable blocks are instruction selected.
254   PM.add(createUnreachableBlockEliminationPass());
255 
256   if (OptLevel != CodeGenOpt::None)
257     PM.add(createCodeGenPreparePass(getTargetLowering()));
258 
259   PM.add(createStackProtectorPass(getTargetLowering()));
260 
261   if (PrintISelInput)
262     PM.add(createPrintFunctionPass("\n\n"
263                                    "*** Final LLVM Code input to ISel ***\n",
264                                    &errs()));
265 
266   // Standard Lower-Level Passes.
267 
268   // Enable FastISel with -fast, but allow that to be overridden.
269   if (EnableFastISelOption == cl::BOU_TRUE ||
270       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
271     EnableFastISel = true;
272 
273   // Ask the target for an isel.
274   if (addInstSelector(PM, OptLevel))
275     return true;
276 
277   // Print the instruction selected machine code...
278   printAndVerify(PM, /* allowDoubleDefs= */ true);
279 
280   if (OptLevel != CodeGenOpt::None) {
281     PM.add(createMachineLICMPass());
282     PM.add(createMachineSinkingPass());
283     printAndVerify(PM, /* allowDoubleDefs= */ true);
284   }
285 
286   // Run pre-ra passes.
287   if (addPreRegAlloc(PM, OptLevel))
288     printAndVerify(PM);
289 
290   // Perform register allocation.
291   PM.add(createRegisterAllocator());
292 
293   // Perform stack slot coloring.
294   if (OptLevel != CodeGenOpt::None)
295     PM.add(createStackSlotColoringPass(OptLevel >= CodeGenOpt::Aggressive));
296 
297   printAndVerify(PM);           // Print the register-allocated code
298 
299   // Run post-ra passes.
300   if (addPostRegAlloc(PM, OptLevel))
301     printAndVerify(PM);
302 
303   PM.add(createLowerSubregsPass());
304   printAndVerify(PM);
305 
306   // Insert prolog/epilog code.  Eliminate abstract frame index references...
307   PM.add(createPrologEpilogCodeInserter());
308   printAndVerify(PM);
309 
310   // Second pass scheduler.
311   if (OptLevel != CodeGenOpt::None && !DisablePostRAScheduler) {
312     PM.add(createPostRAScheduler());
313     printAndVerify(PM);
314   }
315 
316   // Branch folding must be run after regalloc and prolog/epilog insertion.
317   if (OptLevel != CodeGenOpt::None) {
318     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
319     printAndVerify(PM);
320   }
321 
322   PM.add(createGCMachineCodeAnalysisPass());
323   printAndVerify(PM);
324 
325   if (PrintGCInfo)
326     PM.add(createGCInfoPrinter(*cerr));
327 
328   return false;
329 }
330