• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- llvm/Target/TargetMachine.h - Target Information --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the TargetMachine and LLVMTargetMachine classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_TARGET_TARGETMACHINE_H
14 #define LLVM_TARGET_TARGETMACHINE_H
15 
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/CodeGen.h"
21 #include "llvm/Target/TargetOptions.h"
22 #include <string>
23 
24 namespace llvm {
25 
26 class Function;
27 class GlobalValue;
28 class MachineModuleInfoWrapperPass;
29 class Mangler;
30 class MCAsmInfo;
31 class MCContext;
32 class MCInstrInfo;
33 class MCRegisterInfo;
34 class MCSubtargetInfo;
35 class MCSymbol;
36 class raw_pwrite_stream;
37 class PassBuilder;
38 class PassManagerBuilder;
39 struct PerFunctionMIParsingState;
40 class SMDiagnostic;
41 class SMRange;
42 class Target;
43 class TargetIntrinsicInfo;
44 class TargetIRAnalysis;
45 class TargetTransformInfo;
46 class TargetLoweringObjectFile;
47 class TargetPassConfig;
48 class TargetSubtargetInfo;
49 
50 // The old pass manager infrastructure is hidden in a legacy namespace now.
51 namespace legacy {
52 class PassManagerBase;
53 }
54 using legacy::PassManagerBase;
55 
56 namespace yaml {
57 struct MachineFunctionInfo;
58 }
59 
60 //===----------------------------------------------------------------------===//
61 ///
62 /// Primary interface to the complete machine description for the target
63 /// machine.  All target-specific information should be accessible through this
64 /// interface.
65 ///
66 class TargetMachine {
67 protected: // Can only create subclasses.
68   TargetMachine(const Target &T, StringRef DataLayoutString,
69                 const Triple &TargetTriple, StringRef CPU, StringRef FS,
70                 const TargetOptions &Options);
71 
72   /// The Target that this machine was created for.
73   const Target &TheTarget;
74 
75   /// DataLayout for the target: keep ABI type size and alignment.
76   ///
77   /// The DataLayout is created based on the string representation provided
78   /// during construction. It is kept here only to avoid reparsing the string
79   /// but should not really be used during compilation, because it has an
80   /// internal cache that is context specific.
81   const DataLayout DL;
82 
83   /// Triple string, CPU name, and target feature strings the TargetMachine
84   /// instance is created with.
85   Triple TargetTriple;
86   std::string TargetCPU;
87   std::string TargetFS;
88 
89   Reloc::Model RM = Reloc::Static;
90   CodeModel::Model CMModel = CodeModel::Small;
91   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
92 
93   /// Contains target specific asm information.
94   std::unique_ptr<const MCAsmInfo> AsmInfo;
95   std::unique_ptr<const MCRegisterInfo> MRI;
96   std::unique_ptr<const MCInstrInfo> MII;
97   std::unique_ptr<const MCSubtargetInfo> STI;
98 
99   unsigned RequireStructuredCFG : 1;
100   unsigned O0WantsFastISel : 1;
101 
102 public:
103   const TargetOptions DefaultOptions;
104   mutable TargetOptions Options;
105 
106   TargetMachine(const TargetMachine &) = delete;
107   void operator=(const TargetMachine &) = delete;
108   virtual ~TargetMachine();
109 
getTarget()110   const Target &getTarget() const { return TheTarget; }
111 
getTargetTriple()112   const Triple &getTargetTriple() const { return TargetTriple; }
getTargetCPU()113   StringRef getTargetCPU() const { return TargetCPU; }
getTargetFeatureString()114   StringRef getTargetFeatureString() const { return TargetFS; }
setTargetFeatureString(StringRef FS)115   void setTargetFeatureString(StringRef FS) { TargetFS = std::string(FS); }
116 
117   /// Virtual method implemented by subclasses that returns a reference to that
118   /// target's TargetSubtargetInfo-derived member variable.
getSubtargetImpl(const Function &)119   virtual const TargetSubtargetInfo *getSubtargetImpl(const Function &) const {
120     return nullptr;
121   }
getObjFileLowering()122   virtual TargetLoweringObjectFile *getObjFileLowering() const {
123     return nullptr;
124   }
125 
126   /// Allocate and return a default initialized instance of the YAML
127   /// representation for the MachineFunctionInfo.
createDefaultFuncInfoYAML()128   virtual yaml::MachineFunctionInfo *createDefaultFuncInfoYAML() const {
129     return nullptr;
130   }
131 
132   /// Allocate and initialize an instance of the YAML representation of the
133   /// MachineFunctionInfo.
134   virtual yaml::MachineFunctionInfo *
convertFuncInfoToYAML(const MachineFunction & MF)135   convertFuncInfoToYAML(const MachineFunction &MF) const {
136     return nullptr;
137   }
138 
139   /// Parse out the target's MachineFunctionInfo from the YAML reprsentation.
parseMachineFunctionInfo(const yaml::MachineFunctionInfo &,PerFunctionMIParsingState & PFS,SMDiagnostic & Error,SMRange & SourceRange)140   virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &,
141                                         PerFunctionMIParsingState &PFS,
142                                         SMDiagnostic &Error,
143                                         SMRange &SourceRange) const {
144     return false;
145   }
146 
147   /// This method returns a pointer to the specified type of
148   /// TargetSubtargetInfo.  In debug builds, it verifies that the object being
149   /// returned is of the correct type.
getSubtarget(const Function & F)150   template <typename STC> const STC &getSubtarget(const Function &F) const {
151     return *static_cast<const STC*>(getSubtargetImpl(F));
152   }
153 
154   /// Create a DataLayout.
createDataLayout()155   const DataLayout createDataLayout() const { return DL; }
156 
157   /// Test if a DataLayout if compatible with the CodeGen for this target.
158   ///
159   /// The LLVM Module owns a DataLayout that is used for the target independent
160   /// optimizations and code generation. This hook provides a target specific
161   /// check on the validity of this DataLayout.
isCompatibleDataLayout(const DataLayout & Candidate)162   bool isCompatibleDataLayout(const DataLayout &Candidate) const {
163     return DL == Candidate;
164   }
165 
166   /// Get the pointer size for this target.
167   ///
168   /// This is the only time the DataLayout in the TargetMachine is used.
getPointerSize(unsigned AS)169   unsigned getPointerSize(unsigned AS) const {
170     return DL.getPointerSize(AS);
171   }
172 
getPointerSizeInBits(unsigned AS)173   unsigned getPointerSizeInBits(unsigned AS) const {
174     return DL.getPointerSizeInBits(AS);
175   }
176 
getProgramPointerSize()177   unsigned getProgramPointerSize() const {
178     return DL.getPointerSize(DL.getProgramAddressSpace());
179   }
180 
getAllocaPointerSize()181   unsigned getAllocaPointerSize() const {
182     return DL.getPointerSize(DL.getAllocaAddrSpace());
183   }
184 
185   /// Reset the target options based on the function's attributes.
186   // FIXME: Remove TargetOptions that affect per-function code generation
187   // from TargetMachine.
188   void resetTargetOptions(const Function &F) const;
189 
190   /// Return target specific asm information.
getMCAsmInfo()191   const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); }
192 
getMCRegisterInfo()193   const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); }
getMCInstrInfo()194   const MCInstrInfo *getMCInstrInfo() const { return MII.get(); }
getMCSubtargetInfo()195   const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); }
196 
197   /// If intrinsic information is available, return it.  If not, return null.
getIntrinsicInfo()198   virtual const TargetIntrinsicInfo *getIntrinsicInfo() const {
199     return nullptr;
200   }
201 
requiresStructuredCFG()202   bool requiresStructuredCFG() const { return RequireStructuredCFG; }
setRequiresStructuredCFG(bool Value)203   void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; }
204 
205   /// Returns the code generation relocation model. The choices are static, PIC,
206   /// and dynamic-no-pic, and target default.
207   Reloc::Model getRelocationModel() const;
208 
209   /// Returns the code model. The choices are small, kernel, medium, large, and
210   /// target default.
211   CodeModel::Model getCodeModel() const;
212 
213   bool isPositionIndependent() const;
214 
215   bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const;
216 
217   /// Returns true if this target uses emulated TLS.
218   bool useEmulatedTLS() const;
219 
220   /// Returns the TLS model which should be used for the given global variable.
221   TLSModel::Model getTLSModel(const GlobalValue *GV) const;
222 
223   /// Returns the optimization level: None, Less, Default, or Aggressive.
224   CodeGenOpt::Level getOptLevel() const;
225 
226   /// Overrides the optimization level.
227   void setOptLevel(CodeGenOpt::Level Level);
228 
setFastISel(bool Enable)229   void setFastISel(bool Enable) { Options.EnableFastISel = Enable; }
getO0WantsFastISel()230   bool getO0WantsFastISel() { return O0WantsFastISel; }
setO0WantsFastISel(bool Enable)231   void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; }
setGlobalISel(bool Enable)232   void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; }
setGlobalISelAbort(GlobalISelAbortMode Mode)233   void setGlobalISelAbort(GlobalISelAbortMode Mode) {
234     Options.GlobalISelAbort = Mode;
235   }
setMachineOutliner(bool Enable)236   void setMachineOutliner(bool Enable) {
237     Options.EnableMachineOutliner = Enable;
238   }
setSupportsDefaultOutlining(bool Enable)239   void setSupportsDefaultOutlining(bool Enable) {
240     Options.SupportsDefaultOutlining = Enable;
241   }
setSupportsDebugEntryValues(bool Enable)242   void setSupportsDebugEntryValues(bool Enable) {
243     Options.SupportsDebugEntryValues = Enable;
244   }
245 
getAIXExtendedAltivecABI()246   bool getAIXExtendedAltivecABI() const {
247     return Options.EnableAIXExtendedAltivecABI;
248   }
249 
getUniqueSectionNames()250   bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
251 
252   /// Return true if unique basic block section names must be generated.
getUniqueBasicBlockSectionNames()253   bool getUniqueBasicBlockSectionNames() const {
254     return Options.UniqueBasicBlockSectionNames;
255   }
256 
257   /// Return true if data objects should be emitted into their own section,
258   /// corresponds to -fdata-sections.
getDataSections()259   bool getDataSections() const {
260     return Options.DataSections;
261   }
262 
263   /// Return true if functions should be emitted into their own section,
264   /// corresponding to -ffunction-sections.
getFunctionSections()265   bool getFunctionSections() const {
266     return Options.FunctionSections;
267   }
268 
269   /// Return true if visibility attribute should not be emitted in xcoff,
270   /// corresponding to -mignore-xcoff-visibility.
getIgnoreXCOFFVisibility()271   bool getIgnoreXCOFFVisibility() const {
272     return Options.IgnoreXCOFFVisibility;
273   }
274 
275   /// If basic blocks should be emitted into their own section,
276   /// corresponding to -fbasic-block-sections.
getBBSectionsType()277   llvm::BasicBlockSection getBBSectionsType() const {
278     return Options.BBSections;
279   }
280 
281   /// Get the list of functions and basic block ids that need unique sections.
getBBSectionsFuncListBuf()282   const MemoryBuffer *getBBSectionsFuncListBuf() const {
283     return Options.BBSectionsFuncListBuf.get();
284   }
285 
286   /// Returns true if a cast between SrcAS and DestAS is a noop.
isNoopAddrSpaceCast(unsigned SrcAS,unsigned DestAS)287   virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
288     return false;
289   }
290 
291   /// If the specified generic pointer could be assumed as a pointer to a
292   /// specific address space, return that address space.
293   ///
294   /// Under offloading programming, the offloading target may be passed with
295   /// values only prepared on the host side and could assume certain
296   /// properties.
getAssumedAddrSpace(const Value * V)297   virtual unsigned getAssumedAddrSpace(const Value *V) const { return -1; }
298 
299   /// Get a \c TargetIRAnalysis appropriate for the target.
300   ///
301   /// This is used to construct the new pass manager's target IR analysis pass,
302   /// set up appropriately for this target machine. Even the old pass manager
303   /// uses this to answer queries about the IR.
304   TargetIRAnalysis getTargetIRAnalysis();
305 
306   /// Return a TargetTransformInfo for a given function.
307   ///
308   /// The returned TargetTransformInfo is specialized to the subtarget
309   /// corresponding to \p F.
310   virtual TargetTransformInfo getTargetTransformInfo(const Function &F);
311 
312   /// Allow the target to modify the pass manager, e.g. by calling
313   /// PassManagerBuilder::addExtension.
adjustPassManager(PassManagerBuilder &)314   virtual void adjustPassManager(PassManagerBuilder &) {}
315 
316   /// Allow the target to modify the pass pipeline with New Pass Manager
317   /// (similar to adjustPassManager for Legacy Pass manager).
registerPassBuilderCallbacks(PassBuilder &,bool DebugPassManager)318   virtual void registerPassBuilderCallbacks(PassBuilder &,
319                                             bool DebugPassManager) {}
320 
321   /// Add passes to the specified pass manager to get the specified file
322   /// emitted.  Typically this will involve several steps of code generation.
323   /// This method should return true if emission of this file type is not
324   /// supported, or false on success.
325   /// \p MMIWP is an optional parameter that, if set to non-nullptr,
326   /// will be used to set the MachineModuloInfo for this PM.
327   virtual bool
328   addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
329                       raw_pwrite_stream *, CodeGenFileType,
330                       bool /*DisableVerify*/ = true,
331                       MachineModuleInfoWrapperPass *MMIWP = nullptr) {
332     return true;
333   }
334 
335   /// Add passes to the specified pass manager to get machine code emitted with
336   /// the MCJIT. This method returns true if machine code is not supported. It
337   /// fills the MCContext Ctx pointer which can be used to build custom
338   /// MCStreamer.
339   ///
340   virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
341                                  raw_pwrite_stream &,
342                                  bool /*DisableVerify*/ = true) {
343     return true;
344   }
345 
346   /// True if subtarget inserts the final scheduling pass on its own.
347   ///
348   /// Branch relaxation, which must happen after block placement, can
349   /// on some targets (e.g. SystemZ) expose additional post-RA
350   /// scheduling opportunities.
targetSchedulesPostRAScheduling()351   virtual bool targetSchedulesPostRAScheduling() const { return false; };
352 
353   void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
354                          Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
355   MCSymbol *getSymbol(const GlobalValue *GV) const;
356 
357   /// The integer bit size to use for SjLj based exception handling.
358   static constexpr unsigned DefaultSjLjDataSize = 32;
getSjLjDataSize()359   virtual unsigned getSjLjDataSize() const { return DefaultSjLjDataSize; }
360 };
361 
362 /// This class describes a target machine that is implemented with the LLVM
363 /// target-independent code generator.
364 ///
365 class LLVMTargetMachine : public TargetMachine {
366 protected: // Can only create subclasses.
367   LLVMTargetMachine(const Target &T, StringRef DataLayoutString,
368                     const Triple &TT, StringRef CPU, StringRef FS,
369                     const TargetOptions &Options, Reloc::Model RM,
370                     CodeModel::Model CM, CodeGenOpt::Level OL);
371 
372   void initAsmInfo();
373 
374 public:
375   /// Get a TargetTransformInfo implementation for the target.
376   ///
377   /// The TTI returned uses the common code generator to answer queries about
378   /// the IR.
379   TargetTransformInfo getTargetTransformInfo(const Function &F) override;
380 
381   /// Create a pass configuration object to be used by addPassToEmitX methods
382   /// for generating a pipeline of CodeGen passes.
383   virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
384 
385   /// Add passes to the specified pass manager to get the specified file
386   /// emitted.  Typically this will involve several steps of code generation.
387   /// \p MMIWP is an optional parameter that, if set to non-nullptr,
388   /// will be used to set the MachineModuloInfo for this PM.
389   bool
390   addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
391                       raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
392                       bool DisableVerify = true,
393                       MachineModuleInfoWrapperPass *MMIWP = nullptr) override;
394 
395   /// Add passes to the specified pass manager to get machine code emitted with
396   /// the MCJIT. This method returns true if machine code is not supported. It
397   /// fills the MCContext Ctx pointer which can be used to build custom
398   /// MCStreamer.
399   bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
400                          raw_pwrite_stream &Out,
401                          bool DisableVerify = true) override;
402 
403   /// Returns true if the target is expected to pass all machine verifier
404   /// checks. This is a stopgap measure to fix targets one by one. We will
405   /// remove this at some point and always enable the verifier when
406   /// EXPENSIVE_CHECKS is enabled.
isMachineVerifierClean()407   virtual bool isMachineVerifierClean() const { return true; }
408 
409   /// Adds an AsmPrinter pass to the pipeline that prints assembly or
410   /// machine code from the MI representation.
411   bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out,
412                      raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
413                      MCContext &Context);
414 
415   /// True if the target uses physical regs (as nearly all targets do). False
416   /// for stack machines such as WebAssembly and other virtual-register
417   /// machines. If true, all vregs must be allocated before PEI. If false, then
418   /// callee-save register spilling and scavenging are not needed or used. If
419   /// false, implicitly defined registers will still be assumed to be physical
420   /// registers, except that variadic defs will be allocated vregs.
usesPhysRegsForValues()421   virtual bool usesPhysRegsForValues() const { return true; }
422 
423   /// True if the target wants to use interprocedural register allocation by
424   /// default. The -enable-ipra flag can be used to override this.
useIPRA()425   virtual bool useIPRA() const {
426     return false;
427   }
428 };
429 
430 /// Helper method for getting the code model, returning Default if
431 /// CM does not have a value. The tiny and kernel models will produce
432 /// an error, so targets that support them or require more complex codemodel
433 /// selection logic should implement and call their own getEffectiveCodeModel.
getEffectiveCodeModel(Optional<CodeModel::Model> CM,CodeModel::Model Default)434 inline CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM,
435                                               CodeModel::Model Default) {
436   if (CM) {
437     // By default, targets do not support the tiny and kernel models.
438     if (*CM == CodeModel::Tiny)
439       report_fatal_error("Target does not support the tiny CodeModel", false);
440     if (*CM == CodeModel::Kernel)
441       report_fatal_error("Target does not support the kernel CodeModel", false);
442     return *CM;
443   }
444   return Default;
445 }
446 
447 } // end namespace llvm
448 
449 #endif // LLVM_TARGET_TARGETMACHINE_H
450