LLVMTargetMachine.cpp revision 0823d2a654cb3a075016f6efd21359ed4f5aca21
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/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"
30using namespace llvm;
31
32namespace llvm {
33  bool EnableFastISel;
34}
35
36static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
37    cl::desc("Disable Post Regalloc"));
38static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
39    cl::desc("Disable branch folding"));
40static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
41    cl::desc("Disable tail duplication"));
42static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
43    cl::desc("Disable pre-register allocation tail duplication"));
44static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
45    cl::desc("Disable code placement"));
46static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
47    cl::desc("Disable Stack Slot Coloring"));
48static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
49    cl::desc("Disable Machine LICM"));
50static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
51    cl::desc("Disable Machine Sinking"));
52static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
53    cl::desc("Disable Loop Strength Reduction Pass"));
54static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
55    cl::desc("Disable Codegen Prepare"));
56static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
57    cl::desc("Print LLVM IR produced by the loop-reduce pass"));
58static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
59    cl::desc("Print LLVM IR input to isel pass"));
60static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
61    cl::desc("Dump garbage collector data"));
62static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
63    cl::desc("Verify generated machine code"),
64    cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
65
66
67// Enable or disable FastISel. Both options are needed, because
68// FastISel is enabled by default with -fast, and we wish to be
69// able to enable or disable fast-isel independently from -O0.
70static cl::opt<cl::boolOrDefault>
71EnableFastISelOption("fast-isel", cl::Hidden,
72  cl::desc("Enable the \"fast\" instruction selector"));
73
74// Enable or disable an experimental optimization to split GEPs
75// and run a special GVN pass which does not examine loads, in
76// an effort to factor out redundancy implicit in complex GEPs.
77static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
78    cl::desc("Split GEPs and run no-load GVN"));
79
80LLVMTargetMachine::LLVMTargetMachine(const Target &T,
81                                     const std::string &TargetTriple)
82  : TargetMachine(T) {
83  AsmInfo = T.createAsmInfo(TargetTriple);
84}
85
86// Set the default code model for the JIT for a generic target.
87// FIXME: Is small right here? or .is64Bit() ? Large : Small?
88void
89LLVMTargetMachine::setCodeModelForJIT() {
90  setCodeModel(CodeModel::Small);
91}
92
93// Set the default code model for static compilation for a generic target.
94void
95LLVMTargetMachine::setCodeModelForStatic() {
96  setCodeModel(CodeModel::Small);
97}
98
99FileModel::Model
100LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
101                                       formatted_raw_ostream &Out,
102                                       CodeGenFileType FileType,
103                                       CodeGenOpt::Level OptLevel) {
104  // Add common CodeGen passes.
105  if (addCommonCodeGenPasses(PM, OptLevel))
106    return FileModel::Error;
107
108  switch (FileType) {
109  default:
110    break;
111  case TargetMachine::AssemblyFile: {
112    FunctionPass *Printer =
113      getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(),
114                                   getAsmVerbosityDefault());
115    if (Printer == 0) break;
116    PM.add(Printer);
117    return FileModel::AsmFile;
118  }
119  case TargetMachine::ObjectFile:
120    return FileModel::Error;
121  }
122  return FileModel::Error;
123}
124
125/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
126/// be split up (e.g., to add an object writer pass), this method can be used to
127/// finish up adding passes to emit the file, if necessary.
128bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
129                                                  MachineCodeEmitter *MCE,
130                                                  CodeGenOpt::Level OptLevel) {
131  // Make sure the code model is set.
132  setCodeModelForStatic();
133
134  if (MCE)
135    addSimpleCodeEmitter(PM, OptLevel, *MCE);
136
137  PM.add(createGCInfoDeleter());
138
139  return false; // success!
140}
141
142/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
143/// be split up (e.g., to add an object writer pass), this method can be used to
144/// finish up adding passes to emit the file, if necessary.
145bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
146                                                  JITCodeEmitter *JCE,
147                                                  CodeGenOpt::Level OptLevel) {
148  // Make sure the code model is set.
149  setCodeModelForJIT();
150
151  if (JCE)
152    addSimpleCodeEmitter(PM, OptLevel, *JCE);
153
154  PM.add(createGCInfoDeleter());
155
156  return false; // success!
157}
158
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.
162bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
163                                                  ObjectCodeEmitter *OCE,
164                                                  CodeGenOpt::Level OptLevel) {
165  // Make sure the code model is set.
166  setCodeModelForStatic();
167
168  PM.add(createGCInfoDeleter());
169
170  return false; // success!
171}
172
173/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
174/// get machine code emitted.  This uses a MachineCodeEmitter object to handle
175/// actually outputting the machine code and resolving things like the address
176/// of functions.  This method should returns true if machine code emission is
177/// not supported.
178///
179bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
180                                                   MachineCodeEmitter &MCE,
181                                                   CodeGenOpt::Level OptLevel) {
182  // Make sure the code model is set.
183  setCodeModelForJIT();
184
185  // Add common CodeGen passes.
186  if (addCommonCodeGenPasses(PM, OptLevel))
187    return true;
188
189  addCodeEmitter(PM, OptLevel, MCE);
190  PM.add(createGCInfoDeleter());
191
192  return false; // success!
193}
194
195/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
196/// get machine code emitted.  This uses a MachineCodeEmitter object to handle
197/// actually outputting the machine code and resolving things like the address
198/// of functions.  This method should returns true if machine code emission is
199/// not supported.
200///
201bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
202                                                   JITCodeEmitter &JCE,
203                                                   CodeGenOpt::Level OptLevel) {
204  // Make sure the code model is set.
205  setCodeModelForJIT();
206
207  // Add common CodeGen passes.
208  if (addCommonCodeGenPasses(PM, OptLevel))
209    return true;
210
211  addCodeEmitter(PM, OptLevel, JCE);
212  PM.add(createGCInfoDeleter());
213
214  return false; // success!
215}
216
217static void printAndVerify(PassManagerBase &PM,
218                           const char *Banner,
219                           bool allowDoubleDefs = false) {
220  if (PrintMachineCode)
221    PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
222
223  if (VerifyMachineCode)
224    PM.add(createMachineVerifierPass(allowDoubleDefs));
225}
226
227/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
228/// emitting to assembly files or machine code output.
229///
230bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
231                                               CodeGenOpt::Level OptLevel) {
232  // Standard LLVM-Level Passes.
233
234  // Optionally, tun split-GEPs and no-load GVN.
235  if (EnableSplitGEPGVN) {
236    PM.add(createGEPSplitterPass());
237    PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
238  }
239
240  // Run loop strength reduction before anything else.
241  if (OptLevel != CodeGenOpt::None && !DisableLSR) {
242    PM.add(createLoopStrengthReducePass(getTargetLowering()));
243    if (PrintLSR)
244      PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
245  }
246
247  // Turn exception handling constructs into something the code generators can
248  // handle.
249  switch (getMCAsmInfo()->getExceptionHandlingType())
250  {
251  case ExceptionHandling::SjLj:
252    // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
253    // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
254    // catch info can get misplaced when a selector ends up more than one block
255    // removed from the parent invoke(s). This could happen when a landing
256    // pad is shared by multiple invokes and is also a target of a normal
257    // edge from elsewhere.
258    PM.add(createSjLjEHPass(getTargetLowering()));
259    PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
260    break;
261  case ExceptionHandling::Dwarf:
262    PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
263    break;
264  case ExceptionHandling::None:
265    PM.add(createLowerInvokePass(getTargetLowering()));
266    break;
267  }
268
269  PM.add(createGCLoweringPass());
270
271  // Make sure that no unreachable blocks are instruction selected.
272  PM.add(createUnreachableBlockEliminationPass());
273
274  if (OptLevel != CodeGenOpt::None && !DisableCGP)
275    PM.add(createCodeGenPreparePass(getTargetLowering()));
276
277  PM.add(createStackProtectorPass(getTargetLowering()));
278
279  if (PrintISelInput)
280    PM.add(createPrintFunctionPass("\n\n"
281                                   "*** Final LLVM Code input to ISel ***\n",
282                                   &dbgs()));
283
284  // Standard Lower-Level Passes.
285
286  // Set up a MachineFunction for the rest of CodeGen to work on.
287  PM.add(new MachineFunctionAnalysis(*this, OptLevel));
288
289  // Enable FastISel with -fast, but allow that to be overridden.
290  if (EnableFastISelOption == cl::BOU_TRUE ||
291      (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
292    EnableFastISel = true;
293
294  // Ask the target for an isel.
295  if (addInstSelector(PM, OptLevel))
296    return true;
297
298  // Print the instruction selected machine code...
299  printAndVerify(PM, "After Instruction Selection",
300                 /* allowDoubleDefs= */ true);
301
302  if (OptLevel != CodeGenOpt::None) {
303    PM.add(createOptimizeExtsPass());
304    if (!DisableMachineLICM)
305      PM.add(createMachineLICMPass());
306    if (!DisableMachineSink)
307      PM.add(createMachineSinkingPass());
308    printAndVerify(PM, "After MachineLICM and MachineSinking",
309                   /* allowDoubleDefs= */ true);
310  }
311
312  // Pre-ra tail duplication.
313  if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
314    PM.add(createTailDuplicatePass(true));
315    printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
316                   /* allowDoubleDefs= */ true);
317  }
318
319  // Run pre-ra passes.
320  if (addPreRegAlloc(PM, OptLevel))
321    printAndVerify(PM, "After PreRegAlloc passes",
322                   /* allowDoubleDefs= */ true);
323
324  // Perform register allocation.
325  PM.add(createRegisterAllocator());
326  printAndVerify(PM, "After Register Allocation");
327
328  // Perform stack slot coloring.
329  if (OptLevel != CodeGenOpt::None && !DisableSSC) {
330    // FIXME: Re-enable coloring with register when it's capable of adding
331    // kill markers.
332    PM.add(createStackSlotColoringPass(false));
333    printAndVerify(PM, "After StackSlotColoring");
334  }
335
336  // Run post-ra passes.
337  if (addPostRegAlloc(PM, OptLevel))
338    printAndVerify(PM, "After PostRegAlloc passes");
339
340  PM.add(createLowerSubregsPass());
341  printAndVerify(PM, "After LowerSubregs");
342
343  // Insert prolog/epilog code.  Eliminate abstract frame index references...
344  PM.add(createPrologEpilogCodeInserter());
345  printAndVerify(PM, "After PrologEpilogCodeInserter");
346
347  // Run pre-sched2 passes.
348  if (addPreSched2(PM, OptLevel))
349    printAndVerify(PM, "After PreSched2 passes");
350
351  // Second pass scheduler.
352  if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
353    PM.add(createPostRAScheduler(OptLevel));
354    printAndVerify(PM, "After PostRAScheduler");
355  }
356
357  // Branch folding must be run after regalloc and prolog/epilog insertion.
358  if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
359    PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
360    printAndVerify(PM, "After BranchFolding");
361  }
362
363  // Tail duplication.
364  if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
365    PM.add(createTailDuplicatePass(false));
366    printAndVerify(PM, "After TailDuplicate");
367  }
368
369  PM.add(createGCMachineCodeAnalysisPass());
370
371  if (PrintGCInfo)
372    PM.add(createGCInfoPrinter(dbgs()));
373
374  if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
375    PM.add(createCodePlacementOptPass());
376    printAndVerify(PM, "After CodePlacementOpt");
377  }
378
379  if (addPreEmitPass(PM, OptLevel))
380    printAndVerify(PM, "After PreEmit passes");
381
382  return false;
383}
384