TargetMachine.h 19 KB

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