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