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