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