TargetMachine.h 20 KB

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