LLVM  4.0.0
LLVMTargetMachine.cpp
Go to the documentation of this file.
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 
15 #include "llvm/Analysis/Passes.h"
19 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/Transforms/Scalar.h"
36 using namespace llvm;
37 
38 // Enable or disable FastISel. Both options are needed, because
39 // FastISel is enabled by default with -fast, and we wish to be
40 // able to enable or disable fast-isel independently from -O0.
42 EnableFastISelOption("fast-isel", cl::Hidden,
43  cl::desc("Enable the \"fast\" instruction selector"));
44 
45 static cl::opt<bool>
46  EnableGlobalISel("global-isel", cl::Hidden, cl::init(false),
47  cl::desc("Enable the \"global\" instruction selector"));
48 
52  // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
53  // to some backends having subtarget feature dependent module level
54  // code generation. This is similar to the hack in the AsmPrinter for
55  // module level assembly etc.
58 
59  MCAsmInfo *TmpAsmInfo =
61  // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
62  // and if the old one gets included then MCAsmInfo will be NULL and
63  // we'll crash later.
64  // Provide the user with a useful error message about what's wrong.
65  assert(TmpAsmInfo && "MCAsmInfo not initialized. "
66  "Make sure you include the correct TargetSelect.h"
67  "and that InitializeAllTargetMCs() is being invoked!");
68 
70  TmpAsmInfo->setUseIntegratedAssembler(false);
71 
73 
76 
78 
81 
82  AsmInfo = TmpAsmInfo;
83 }
84 
86  StringRef DataLayoutString,
87  const Triple &TT, StringRef CPU,
88  StringRef FS, TargetOptions Options,
91  : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
92  T.adjustCodeGenOpts(TT, RM, CM);
93  this->RM = RM;
94  this->CMModel = CM;
95  this->OptLevel = OL;
96 }
97 
99  return TargetIRAnalysis([this](const Function &F) {
100  return TargetTransformInfo(BasicTTIImpl(this, F));
101  });
102 }
103 
104 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
105 static MCContext *
107  bool DisableVerify, AnalysisID StartBefore,
108  AnalysisID StartAfter, AnalysisID StopBefore,
109  AnalysisID StopAfter,
110  MachineFunctionInitializer *MFInitializer = nullptr) {
111 
112  // When in emulated TLS mode, add the LowerEmuTLS pass.
113  if (TM->Options.EmulatedTLS)
114  PM.add(createLowerEmuTLSPass(TM));
115 
117 
118  // Add internal analysis passes from the target machine.
120 
121  // Targets may override createPassConfig to provide a target-specific
122  // subclass.
123  TargetPassConfig *PassConfig = TM->createPassConfig(PM);
124  PassConfig->setStartStopPasses(StartBefore, StartAfter, StopBefore,
125  StopAfter);
126 
127  // Set PassConfig options provided by TargetMachine.
128  PassConfig->setDisableVerify(DisableVerify);
129 
130  PM.add(PassConfig);
131 
132  PassConfig->addIRPasses();
133 
134  PassConfig->addCodeGenPrepare();
135 
136  PassConfig->addPassesToHandleExceptions();
137 
138  PassConfig->addISelPrepare();
139 
140  MachineModuleInfo *MMI = new MachineModuleInfo(TM);
141  MMI->setMachineFunctionInitializer(MFInitializer);
142  PM.add(MMI);
143 
144  // Enable FastISel with -fast, but allow that to be overridden.
147  (TM->getOptLevel() == CodeGenOpt::None &&
148  TM->getO0WantsFastISel()))
149  TM->setFastISel(true);
150 
151  // Ask the target for an isel.
153  if (PassConfig->addIRTranslator())
154  return nullptr;
155 
156  PassConfig->addPreLegalizeMachineIR();
157 
158  if (PassConfig->addLegalizeMachineIR())
159  return nullptr;
160 
161  // Before running the register bank selector, ask the target if it
162  // wants to run some passes.
163  PassConfig->addPreRegBankSelect();
164 
165  if (PassConfig->addRegBankSelect())
166  return nullptr;
167 
168  PassConfig->addPreGlobalInstructionSelect();
169 
170  if (PassConfig->addGlobalInstructionSelect())
171  return nullptr;
172 
173  // Pass to reset the MachineFunction if the ISel failed.
176 
177  // Provide a fallback path when we do not want to abort on
178  // not-yet-supported input.
179  if (LLVM_UNLIKELY(!PassConfig->isGlobalISelAbortEnabled()) &&
180  PassConfig->addInstSelector())
181  return nullptr;
182 
183  } else if (PassConfig->addInstSelector())
184  return nullptr;
185 
186  PassConfig->addMachinePasses();
187 
188  PassConfig->setInitialized();
189 
190  return &MMI->getContext();
191 }
192 
194  PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
195  bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
196  AnalysisID StopBefore, AnalysisID StopAfter,
197  MachineFunctionInitializer *MFInitializer) {
198  // Add common CodeGen passes.
199  MCContext *Context =
200  addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
201  StopBefore, StopAfter, MFInitializer);
202  if (!Context)
203  return true;
204 
205  if (StopBefore || StopAfter) {
206  PM.add(createPrintMIRPass(Out));
207  return false;
208  }
209 
211  Context->setAllowTemporaryLabels(false);
212 
214  const MCAsmInfo &MAI = *getMCAsmInfo();
216  const MCInstrInfo &MII = *getMCInstrInfo();
217 
218  std::unique_ptr<MCStreamer> AsmStreamer;
219 
220  switch (FileType) {
221  case CGFT_AssemblyFile: {
223  getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
224 
225  // Create a code emitter if asked to show the encoding.
226  MCCodeEmitter *MCE = nullptr;
228  MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
229 
230  MCAsmBackend *MAB =
233  auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
235  *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
236  Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
238  AsmStreamer.reset(S);
239  break;
240  }
241  case CGFT_ObjectFile: {
242  // Create the code emitter for the target if it exists. If not, .o file
243  // emission fails.
244  MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
245  MCAsmBackend *MAB =
248  if (!MCE || !MAB)
249  return true;
250 
251  // Don't waste memory on names of temp labels.
252  Context->setUseNamesOnTempLabels(false);
253 
254  Triple T(getTargetTriple().str());
255  AsmStreamer.reset(getTarget().createMCObjectStreamer(
256  T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
258  /*DWARFMustBeAtTheEnd*/ true));
259  break;
260  }
261  case CGFT_Null:
262  // The Null output is intended for use for performance analysis and testing,
263  // not real users.
264  AsmStreamer.reset(getTarget().createNullStreamer(*Context));
265  break;
266  }
267 
268  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
270  getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
271  if (!Printer)
272  return true;
273 
274  PM.add(Printer);
276 
277  return false;
278 }
279 
280 /// addPassesToEmitMC - Add passes to the specified pass manager to get
281 /// machine code emitted with the MCJIT. This method returns true if machine
282 /// code is not supported. It fills the MCContext Ctx pointer which can be
283 /// used to build custom MCStreamer.
284 ///
285 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
286  raw_pwrite_stream &Out,
287  bool DisableVerify) {
288  // Add common CodeGen passes.
289  Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
290  nullptr, nullptr);
291  if (!Ctx)
292  return true;
293 
295  Ctx->setAllowTemporaryLabels(false);
296 
297  // Create the code emitter for the target if it exists. If not, .o file
298  // emission fails.
300  MCCodeEmitter *MCE =
302  MCAsmBackend *MAB =
305  if (!MCE || !MAB)
306  return true;
307 
308  const Triple &T = getTargetTriple();
310  std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
311  T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
313  /*DWARFMustBeAtTheEnd*/ true));
314 
315  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
317  getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
318  if (!Printer)
319  return true;
320 
321  PM.add(Printer);
323 
324  return false; // success!
325 }
bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType, bool DisableVerify=true, AnalysisID StartBefore=nullptr, AnalysisID StartAfter=nullptr, AnalysisID StopBefore=nullptr, AnalysisID StopAfter=nullptr, MachineFunctionInitializer *MFInitializer=nullptr) override
Add passes to the specified pass manager to get the specified file emitted.
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:491
StringRef getTargetCPU() const
LLVMContext & Context
MCTargetOptions MCOptions
Machine level options.
void setCompressDebugSections(DebugCompressionType CompressDebugSections)
Definition: MCAsmInfo.h:593
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void setUseIntegratedAssembler(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:577
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:182
void setDisableVerify(bool Disable)
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
virtual void reset()
State management.
Definition: MCStreamer.cpp:56
MCStreamer * createNullStreamer(MCContext &Ctx)
Create a dummy machine code streamer, which does nothing.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
void setO0WantsFastISel(bool Enable)
Analysis pass providing the TargetTransformInfo.
print alias Alias Set Printer
CodeGenOpt::Level OptLevel
virtual TargetPassConfig * createPassConfig(PassManagerBase &PM)
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
const MCRegisterInfo * getMCRegisterInfo() const
const Triple & getTargetTriple() const
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
unsigned DisableIntegratedAS
Disable the integrated assembler.
MachineFunctionPass * createResetMachineFunctionPass(bool EmitFallbackDiag)
This pass resets a MachineFunction when it has the FailedISel property as if it was just created...
MCAsmBackend * createMCAsmBackend(const MCRegisterInfo &MRI, StringRef TheTriple, StringRef CPU, const MCTargetOptions &Options) const
createMCAsmBackend - Create a target specific assembly parser.
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
virtual bool addLegalizeMachineIR()
This method should install a legalize pass, which converts the instruction sequence into one that can...
void setUseNamesOnTempLabels(bool Value)
Definition: MCContext.h:252
virtual bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
ExceptionHandling ExceptionModel
What exception model to use.
AsmPrinter * createAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > &&Streamer) const
createAsmPrinter - Create a target specific assembly printer pass.
Target-Independent Code Generator Pass Configuration Options.
const MCAsmInfo * AsmInfo
Contains target specific asm information.
Context object for machine code objects.
Definition: MCContext.h:51
const MCInstrInfo * getMCInstrInfo() const
virtual void addMachinePasses()
Add the complete, standard set of LLVM CodeGen passes.
void setStartStopPasses(AnalysisID StartBefore, AnalysisID StartAfter, AnalysisID StopBefore, AnalysisID StopAfter)
Set the StartAfter, StartBefore and StopAfter passes to allow running only a portion of the normal co...
#define F(x, y, z)
Definition: MD5.cpp:51
const MCSubtargetInfo * STI
virtual bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path...
#define T
bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, raw_pwrite_stream &OS, bool DisableVerify=true) override
Add passes to the specified pass manager to get machine code emitted with the MCJIT.
virtual void addPreLegalizeMachineIR()
This method may be implemented by targets that want to run passes immediately before legalization...
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
bool PreserveAsmComments
Preserve Comments in Assembly.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:57
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple) const
createMCAsmInfo - Create a MCAsmInfo implementation for the specified target triple.
Streaming machine code generation interface.
Definition: MCStreamer.h:161
virtual void setPreserveAsmComments(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:585
void setAllowTemporaryLabels(bool Value)
Definition: MCContext.h:251
Concrete BasicTTIImpl that can be used if no further customization is needed.
CodeModel::Model CMModel
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:23
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:24
FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.
virtual bool addInstSelector()
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
MCCodeEmitter * createMCCodeEmitter(const MCInstrInfo &II, const MCRegisterInfo &MRI, MCContext &Ctx) const
createMCCodeEmitter - Create a target specific code emitter.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
virtual void addISelPrepare()
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection...
virtual void addCodeGenPrepare()
Add pass to prepare the LLVM IR for code generation.
void setRelaxELFRelocations(bool V)
Definition: MCAsmInfo.h:600
const Target & TheTarget
The Target that this machine was created for.
cl::opt< TargetMachine::CodeGenFileType > FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile), cl::desc("Choose a file type (not all types are supported by all targets):"), cl::values(clEnumValN(TargetMachine::CGFT_AssemblyFile,"asm","Emit an assembly ('.s') file"), clEnumValN(TargetMachine::CGFT_ObjectFile,"obj","Emit a native object ('.o') file"), clEnumValN(TargetMachine::CGFT_Null,"null","Emit nothing, for performance testing")))
void adjustCodeGenOpts(const Triple &TT, Reloc::Model RM, CodeModel::Model &CM) const
const MCInstrInfo * MII
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
void addPassesToHandleExceptions()
Add passes to lower exception handling for the code generator.
unsigned CompressDebugSections
Compress DWARF debug sections.
static cl::opt< cl::boolOrDefault > EnableFastISelOption("fast-isel", cl::Hidden, cl::desc("Enable the \"fast\" instruction selector"))
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
virtual void addPreRegBankSelect()
This method may be implemented by targets that want to run passes immediately before the register ban...
void setMachineFunctionInitializer(MachineFunctionInitializer *MFInit)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
StringRef getTargetFeatureString() const
const MCContext & getContext() const
void setFastISel(bool Enable)
LLVMTargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TargetTriple, StringRef CPU, StringRef FS, TargetOptions Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL)
virtual bool addGlobalInstructionSelect()
This method should install a (global) instruction selector pass, which converts possibly generic inst...
static MCContext * addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM, bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter, AnalysisID StopBefore, AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer=nullptr)
addPassesToX helper drives creation and initialization of TargetPassConfig.
Target - Wrapper for Target specific information.
unsigned EmulatedTLS
EmulatedTLS - This flag enables emulated TLS model, using emutls function in the runtime library...
virtual bool addRegBankSelect()
This method should install a register bank selector pass, which assigns register banks to virtual reg...
unsigned RelaxELFRelocations
const MCRegisterInfo * MRI
MCStreamer * createAsmStreamer(MCContext &Ctx, std::unique_ptr< formatted_raw_ostream > OS, bool IsVerboseAsm, bool UseDwarfDirectory, MCInstPrinter *InstPrint, MCCodeEmitter *CE, MCAsmBackend *TAB, bool ShowInst) const
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:41
virtual void addPreGlobalInstructionSelect()
This method may be implemented by targets that want to run passes immediately before the (global) ins...
MCSubtargetInfo - Generic base class for all target subtargets.
const MCSubtargetInfo * getMCSubtargetInfo() const
ModulePass * createLowerEmuTLSPass(const TargetMachine *TM)
LowerEmuTLS - This pass generates __emutls_[vt].xyz variables for all TLS variables for the emulated ...
const void * AnalysisID
Definition: Pass.h:46
This file defines passes to print out IR in various granularities.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:333
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:36
ModulePass * createPreISelIntrinsicLoweringPass()
This pass lowers the .load.relative intrinsic to instructions.
const Target & getTarget() const
Primary interface to the complete machine description for the target machine.
void setExceptionsType(ExceptionHandling EH)
Definition: MCAsmInfo.h:541
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
This interface provides a way to initialize machine functions after they are created by the machine f...
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit...
TargetIRAnalysis getTargetIRAnalysis() override
Get a TargetIRAnalysis implementation for the target.
virtual bool addIRTranslator()
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
MachineFunctionPass * createPrintMIRPass(raw_ostream &OS)
MIRPrinting pass - this pass prints out the LLVM IR into the given stream using the MIR serialization...
static cl::opt< bool > EnableGlobalISel("global-isel", cl::Hidden, cl::init(false), cl::desc("Enable the \"global\" instruction selector"))
This class contains meta information specific to a module.