LLVMTargetMachine.cpp revision ffef8acc3e3398bdd04e947c7949befdd52faf86
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/CodeGen/Passes.h"
19#include "llvm/CodeGen/GCStrategy.h"
20#include "llvm/CodeGen/MachineFunctionAnalysis.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"
27using namespace llvm;
28
29namespace llvm {
30  bool EnableFastISel;
31}
32
33static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
34    cl::desc("Print LLVM IR produced by the loop-reduce pass"));
35static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
36    cl::desc("Print LLVM IR input to isel pass"));
37static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
38    cl::desc("Dump emitter generated instructions as assembly"));
39static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
40    cl::desc("Dump garbage collector data"));
41static 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.
46static cl::opt<bool>
47DisablePostRAScheduler("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.
54static cl::opt<cl::boolOrDefault>
55EnableFastISelOption("fast-isel", cl::Hidden,
56  cl::desc("Enable the experimental \"fast\" instruction selector"));
57
58FileModel::Model
59LLVMTargetMachine::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
96bool 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.
111bool 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  return false; // success!
122}
123
124/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
125/// be split up (e.g., to add an object writer pass), this method can be used to
126/// finish up adding passes to emit the file, if necessary.
127bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
128                                                  JITCodeEmitter *JCE,
129                                                  CodeGenOpt::Level OptLevel) {
130  if (JCE)
131    addSimpleCodeEmitter(PM, OptLevel, *JCE);
132  if (PrintEmittedAsm)
133    addAssemblyEmitter(PM, OptLevel, true, ferrs());
134
135  PM.add(createGCInfoDeleter());
136
137  return false; // success!
138}
139
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.
143bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
144                                                  ObjectCodeEmitter *OCE,
145                                                  CodeGenOpt::Level OptLevel) {
146  if (OCE)
147    addSimpleCodeEmitter(PM, OptLevel, *OCE);
148  if (PrintEmittedAsm)
149    addAssemblyEmitter(PM, OptLevel, true, ferrs());
150
151  PM.add(createGCInfoDeleter());
152
153  return false; // success!
154}
155
156/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
157/// get machine code emitted.  This uses a MachineCodeEmitter object to handle
158/// actually outputting the machine code and resolving things like the address
159/// of functions.  This method should returns true if machine code emission is
160/// not supported.
161///
162bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
163                                                   MachineCodeEmitter &MCE,
164                                                   CodeGenOpt::Level OptLevel) {
165  // Add common CodeGen passes.
166  if (addCommonCodeGenPasses(PM, OptLevel))
167    return true;
168
169  if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
170    PM.add(createMachineFunctionPrinterPass(cerr));
171
172  addCodeEmitter(PM, OptLevel, MCE);
173  if (PrintEmittedAsm)
174    addAssemblyEmitter(PM, OptLevel, true, ferrs());
175
176  PM.add(createGCInfoDeleter());
177
178  return false; // success!
179}
180
181/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
182/// get machine code emitted.  This uses a MachineCodeEmitter object to handle
183/// actually outputting the machine code and resolving things like the address
184/// of functions.  This method should returns true if machine code emission is
185/// not supported.
186///
187bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
188                                                   JITCodeEmitter &JCE,
189                                                   CodeGenOpt::Level OptLevel) {
190  // Add common CodeGen passes.
191  if (addCommonCodeGenPasses(PM, OptLevel))
192    return true;
193
194  if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
195    PM.add(createMachineFunctionPrinterPass(cerr));
196
197  addCodeEmitter(PM, OptLevel, JCE);
198  if (PrintEmittedAsm)
199    addAssemblyEmitter(PM, OptLevel, true, ferrs());
200
201  PM.add(createGCInfoDeleter());
202
203  return false; // success!
204}
205
206static void printAndVerify(PassManagerBase &PM,
207                           bool allowDoubleDefs = false) {
208  if (PrintMachineCode)
209    PM.add(createMachineFunctionPrinterPass(cerr));
210
211  if (VerifyMachineCode)
212    PM.add(createMachineVerifierPass(allowDoubleDefs));
213}
214
215/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
216/// emitting to assembly files or machine code output.
217///
218bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
219                                               CodeGenOpt::Level OptLevel) {
220  // Standard LLVM-Level Passes.
221
222  // Run loop strength reduction before anything else.
223  if (OptLevel != CodeGenOpt::None) {
224    PM.add(createLoopStrengthReducePass(getTargetLowering()));
225    if (PrintLSR)
226      PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
227  }
228
229  // Turn exception handling constructs into something the code generators can
230  // handle.
231  switch (getTargetAsmInfo()->getExceptionHandlingType())
232  {
233  // SjLj piggy-backs on dwarf for this bit
234  case ExceptionHandling::SjLj:
235  case ExceptionHandling::Dwarf:
236    PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
237    break;
238  case ExceptionHandling::None:
239    PM.add(createLowerInvokePass(getTargetLowering()));
240    break;
241  }
242
243  PM.add(createGCLoweringPass());
244
245  // Make sure that no unreachable blocks are instruction selected.
246  PM.add(createUnreachableBlockEliminationPass());
247
248  if (OptLevel != CodeGenOpt::None)
249    PM.add(createCodeGenPreparePass(getTargetLowering()));
250
251  PM.add(createStackProtectorPass(getTargetLowering()));
252
253  if (PrintISelInput)
254    PM.add(createPrintFunctionPass("\n\n"
255                                   "*** Final LLVM Code input to ISel ***\n",
256                                   &errs()));
257
258  // Standard Lower-Level Passes.
259
260  // Set up a MachineFunction for the rest of CodeGen to work on.
261  PM.add(new MachineFunctionAnalysis(*this, OptLevel));
262
263  // Enable FastISel with -fast, but allow that to be overridden.
264  if (EnableFastISelOption == cl::BOU_TRUE ||
265      (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
266    EnableFastISel = true;
267
268  // Ask the target for an isel.
269  if (addInstSelector(PM, OptLevel))
270    return true;
271
272  // Print the instruction selected machine code...
273  printAndVerify(PM, /* allowDoubleDefs= */ true);
274
275  if (OptLevel != CodeGenOpt::None) {
276    PM.add(createMachineLICMPass());
277    PM.add(createMachineSinkingPass());
278    printAndVerify(PM, /* allowDoubleDefs= */ true);
279  }
280
281  // Run pre-ra passes.
282  if (addPreRegAlloc(PM, OptLevel))
283    printAndVerify(PM);
284
285  // Perform register allocation.
286  PM.add(createRegisterAllocator());
287
288  // Perform stack slot coloring.
289  if (OptLevel != CodeGenOpt::None)
290    // FIXME: Re-enable coloring with register when it's capable of adding
291    // kill markers.
292    PM.add(createStackSlotColoringPass(false));
293
294  printAndVerify(PM);           // Print the register-allocated code
295
296  // Run post-ra passes.
297  if (addPostRegAlloc(PM, OptLevel))
298    printAndVerify(PM);
299
300  PM.add(createLowerSubregsPass());
301  printAndVerify(PM);
302
303  // Insert prolog/epilog code.  Eliminate abstract frame index references...
304  PM.add(createPrologEpilogCodeInserter());
305  printAndVerify(PM);
306
307  // Second pass scheduler.
308  if (OptLevel != CodeGenOpt::None && !DisablePostRAScheduler) {
309    PM.add(createPostRAScheduler());
310    printAndVerify(PM);
311  }
312
313  // Branch folding must be run after regalloc and prolog/epilog insertion.
314  if (OptLevel != CodeGenOpt::None) {
315    PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
316    printAndVerify(PM);
317  }
318
319  PM.add(createGCMachineCodeAnalysisPass());
320  printAndVerify(PM);
321
322  if (PrintGCInfo)
323    PM.add(createGCInfoPrinter(*cerr));
324
325  return false;
326}
327