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 MachineModuleInfoWrapperPass;
38 class Mangler;
39 class MCAsmInfo;
40 class MCContext;
41 class MCInstrInfo;
42 class MCRegisterInfo;
43 class MCStreamer;
44 class MCSubtargetInfo;
45 class MCSymbol;
46 class raw_pwrite_stream;
47 class PassBuilder;
48 struct PerFunctionMIParsingState;
49 class SMDiagnostic;
50 class SMRange;
51 class Target;
52 class TargetIntrinsicInfo;
53 class TargetIRAnalysis;
54 class TargetTransformInfo;
55 class TargetLoweringObjectFile;
56 class TargetPassConfig;
57 class TargetSubtargetInfo;
58
59 // The old pass manager infrastructure is hidden in a legacy namespace now.
60 namespace legacy {
61 class PassManagerBase;
62 }
63 using legacy::PassManagerBase;
64
65 struct MachineFunctionInfo;
66 namespace yaml {
67 struct MachineFunctionInfo;
68 }
69
70 //===----------------------------------------------------------------------===//
71 ///
72 /// Primary interface to the complete machine description for the target
73 /// machine. All target-specific information should be accessible through this
74 /// interface.
75 ///
76 class TargetMachine {
77 protected: // Can only create subclasses.
78 TargetMachine(const Target &T, StringRef DataLayoutString,
79 const Triple &TargetTriple, StringRef CPU, StringRef FS,
80 const TargetOptions &Options);
81
82 /// The Target that this machine was created for.
83 const Target &TheTarget;
84
85 /// DataLayout for the target: keep ABI type size and alignment.
86 ///
87 /// The DataLayout is created based on the string representation provided
88 /// during construction. It is kept here only to avoid reparsing the string
89 /// but should not really be used during compilation, because it has an
90 /// internal cache that is context specific.
91 const DataLayout DL;
92
93 /// Triple string, CPU name, and target feature strings the TargetMachine
94 /// instance is created with.
95 Triple TargetTriple;
96 std::string TargetCPU;
97 std::string TargetFS;
98
99 Reloc::Model RM = Reloc::Static;
100 CodeModel::Model CMModel = CodeModel::Small;
101 uint64_t LargeDataThreshold = 0;
102 CodeGenOptLevel OptLevel = CodeGenOptLevel::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 // PGO related tunables.
114 std::optional<PGOOptions> PGOOption;
115
116 public:
117 mutable TargetOptions Options;
118
119 TargetMachine(const TargetMachine &) = delete;
120 void operator=(const TargetMachine &) = delete;
121 virtual ~TargetMachine();
122
getTarget()123 const Target &getTarget() const { return TheTarget; }
124
getTargetTriple()125 const Triple &getTargetTriple() const { return TargetTriple; }
getTargetCPU()126 StringRef getTargetCPU() const { return TargetCPU; }
getTargetFeatureString()127 StringRef getTargetFeatureString() const { return TargetFS; }
setTargetFeatureString(StringRef FS)128 void setTargetFeatureString(StringRef FS) { TargetFS = std::string(FS); }
129
130 /// Virtual method implemented by subclasses that returns a reference to that
131 /// target's TargetSubtargetInfo-derived member variable.
getSubtargetImpl(const Function &)132 virtual const TargetSubtargetInfo *getSubtargetImpl(const Function &) const {
133 return nullptr;
134 }
getObjFileLowering()135 virtual TargetLoweringObjectFile *getObjFileLowering() const {
136 return nullptr;
137 }
138
139 /// Create the target's instance of MachineFunctionInfo
140 virtual MachineFunctionInfo *
createMachineFunctionInfo(BumpPtrAllocator & Allocator,const Function & F,const TargetSubtargetInfo * STI)141 createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F,
142 const TargetSubtargetInfo *STI) const {
143 return nullptr;
144 }
145
146 /// Allocate and return a default initialized instance of the YAML
147 /// representation for the MachineFunctionInfo.
createDefaultFuncInfoYAML()148 virtual yaml::MachineFunctionInfo *createDefaultFuncInfoYAML() const {
149 return nullptr;
150 }
151
152 /// Allocate and initialize an instance of the YAML representation of the
153 /// MachineFunctionInfo.
154 virtual yaml::MachineFunctionInfo *
convertFuncInfoToYAML(const MachineFunction & MF)155 convertFuncInfoToYAML(const MachineFunction &MF) const {
156 return nullptr;
157 }
158
159 /// Parse out the target's MachineFunctionInfo from the YAML reprsentation.
parseMachineFunctionInfo(const yaml::MachineFunctionInfo &,PerFunctionMIParsingState & PFS,SMDiagnostic & Error,SMRange & SourceRange)160 virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &,
161 PerFunctionMIParsingState &PFS,
162 SMDiagnostic &Error,
163 SMRange &SourceRange) const {
164 return false;
165 }
166
167 /// This method returns a pointer to the specified type of
168 /// TargetSubtargetInfo. In debug builds, it verifies that the object being
169 /// returned is of the correct type.
getSubtarget(const Function & F)170 template <typename STC> const STC &getSubtarget(const Function &F) const {
171 return *static_cast<const STC*>(getSubtargetImpl(F));
172 }
173
174 /// Create a DataLayout.
createDataLayout()175 const DataLayout createDataLayout() const { return DL; }
176
177 /// Test if a DataLayout if compatible with the CodeGen for this target.
178 ///
179 /// The LLVM Module owns a DataLayout that is used for the target independent
180 /// optimizations and code generation. This hook provides a target specific
181 /// check on the validity of this DataLayout.
isCompatibleDataLayout(const DataLayout & Candidate)182 bool isCompatibleDataLayout(const DataLayout &Candidate) const {
183 return DL == Candidate;
184 }
185
186 /// Get the pointer size for this target.
187 ///
188 /// This is the only time the DataLayout in the TargetMachine is used.
getPointerSize(unsigned AS)189 unsigned getPointerSize(unsigned AS) const {
190 return DL.getPointerSize(AS);
191 }
192
getPointerSizeInBits(unsigned AS)193 unsigned getPointerSizeInBits(unsigned AS) const {
194 return DL.getPointerSizeInBits(AS);
195 }
196
getProgramPointerSize()197 unsigned getProgramPointerSize() const {
198 return DL.getPointerSize(DL.getProgramAddressSpace());
199 }
200
getAllocaPointerSize()201 unsigned getAllocaPointerSize() const {
202 return DL.getPointerSize(DL.getAllocaAddrSpace());
203 }
204
205 /// Reset the target options based on the function's attributes.
206 // FIXME: Remove TargetOptions that affect per-function code generation
207 // from TargetMachine.
208 void resetTargetOptions(const Function &F) const;
209
210 /// Return target specific asm information.
getMCAsmInfo()211 const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); }
212
getMCRegisterInfo()213 const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); }
getMCInstrInfo()214 const MCInstrInfo *getMCInstrInfo() const { return MII.get(); }
getMCSubtargetInfo()215 const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); }
216
217 /// If intrinsic information is available, return it. If not, return null.
getIntrinsicInfo()218 virtual const TargetIntrinsicInfo *getIntrinsicInfo() const {
219 return nullptr;
220 }
221
requiresStructuredCFG()222 bool requiresStructuredCFG() const { return RequireStructuredCFG; }
setRequiresStructuredCFG(bool Value)223 void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; }
224
225 /// Returns the code generation relocation model. The choices are static, PIC,
226 /// and dynamic-no-pic, and target default.
227 Reloc::Model getRelocationModel() const;
228
229 /// Returns the code model. The choices are small, kernel, medium, large, and
230 /// target default.
getCodeModel()231 CodeModel::Model getCodeModel() const { return CMModel; }
232
233 /// Returns the maximum code size possible under the code model.
234 uint64_t getMaxCodeSize() const;
235
236 /// Set the code model.
setCodeModel(CodeModel::Model CM)237 void setCodeModel(CodeModel::Model CM) { CMModel = CM; }
238
setLargeDataThreshold(uint64_t LDT)239 void setLargeDataThreshold(uint64_t LDT) { LargeDataThreshold = LDT; }
240 bool isLargeGlobalValue(const GlobalValue *GV) const;
241
242 bool isPositionIndependent() const;
243
244 bool shouldAssumeDSOLocal(const GlobalValue *GV) const;
245
246 /// Returns true if this target uses emulated TLS.
247 bool useEmulatedTLS() const;
248
249 /// Returns true if this target uses TLS Descriptors.
250 bool useTLSDESC() const;
251
252 /// Returns the TLS model which should be used for the given global variable.
253 TLSModel::Model getTLSModel(const GlobalValue *GV) const;
254
255 /// Returns the optimization level: None, Less, Default, or Aggressive.
256 CodeGenOptLevel getOptLevel() const;
257
258 /// Overrides the optimization level.
259 void setOptLevel(CodeGenOptLevel Level);
260
setFastISel(bool Enable)261 void setFastISel(bool Enable) { Options.EnableFastISel = Enable; }
getO0WantsFastISel()262 bool getO0WantsFastISel() { return O0WantsFastISel; }
setO0WantsFastISel(bool Enable)263 void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; }
setGlobalISel(bool Enable)264 void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; }
setGlobalISelAbort(GlobalISelAbortMode Mode)265 void setGlobalISelAbort(GlobalISelAbortMode Mode) {
266 Options.GlobalISelAbort = Mode;
267 }
setMachineOutliner(bool Enable)268 void setMachineOutliner(bool Enable) {
269 Options.EnableMachineOutliner = Enable;
270 }
setSupportsDefaultOutlining(bool Enable)271 void setSupportsDefaultOutlining(bool Enable) {
272 Options.SupportsDefaultOutlining = Enable;
273 }
setSupportsDebugEntryValues(bool Enable)274 void setSupportsDebugEntryValues(bool Enable) {
275 Options.SupportsDebugEntryValues = Enable;
276 }
277
setCFIFixup(bool Enable)278 void setCFIFixup(bool Enable) { Options.EnableCFIFixup = Enable; }
279
getAIXExtendedAltivecABI()280 bool getAIXExtendedAltivecABI() const {
281 return Options.EnableAIXExtendedAltivecABI;
282 }
283
getUniqueSectionNames()284 bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
285
286 /// Return true if unique basic block section names must be generated.
getUniqueBasicBlockSectionNames()287 bool getUniqueBasicBlockSectionNames() const {
288 return Options.UniqueBasicBlockSectionNames;
289 }
290
291 /// Return true if data objects should be emitted into their own section,
292 /// corresponds to -fdata-sections.
getDataSections()293 bool getDataSections() const {
294 return Options.DataSections;
295 }
296
297 /// Return true if functions should be emitted into their own section,
298 /// corresponding to -ffunction-sections.
getFunctionSections()299 bool getFunctionSections() const {
300 return Options.FunctionSections;
301 }
302
303 /// Return true if visibility attribute should not be emitted in XCOFF,
304 /// corresponding to -mignore-xcoff-visibility.
getIgnoreXCOFFVisibility()305 bool getIgnoreXCOFFVisibility() const {
306 return Options.IgnoreXCOFFVisibility;
307 }
308
309 /// Return true if XCOFF traceback table should be emitted,
310 /// corresponding to -xcoff-traceback-table.
getXCOFFTracebackTable()311 bool getXCOFFTracebackTable() const { return Options.XCOFFTracebackTable; }
312
313 /// If basic blocks should be emitted into their own section,
314 /// corresponding to -fbasic-block-sections.
getBBSectionsType()315 llvm::BasicBlockSection getBBSectionsType() const {
316 return Options.BBSections;
317 }
318
319 /// Get the list of functions and basic block ids that need unique sections.
getBBSectionsFuncListBuf()320 const MemoryBuffer *getBBSectionsFuncListBuf() const {
321 return Options.BBSectionsFuncListBuf.get();
322 }
323
324 /// Returns true if a cast between SrcAS and DestAS is a noop.
isNoopAddrSpaceCast(unsigned SrcAS,unsigned DestAS)325 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
326 return false;
327 }
328
setPGOOption(std::optional<PGOOptions> PGOOpt)329 void setPGOOption(std::optional<PGOOptions> PGOOpt) { PGOOption = PGOOpt; }
getPGOOption()330 const std::optional<PGOOptions> &getPGOOption() const { return PGOOption; }
331
332 /// If the specified generic pointer could be assumed as a pointer to a
333 /// specific address space, return that address space.
334 ///
335 /// Under offloading programming, the offloading target may be passed with
336 /// values only prepared on the host side and could assume certain
337 /// properties.
getAssumedAddrSpace(const Value * V)338 virtual unsigned getAssumedAddrSpace(const Value *V) const { return -1; }
339
340 /// If the specified predicate checks whether a generic pointer falls within
341 /// a specified address space, return that generic pointer and the address
342 /// space being queried.
343 ///
344 /// Such predicates could be specified in @llvm.assume intrinsics for the
345 /// optimizer to assume that the given generic pointer always falls within
346 /// the address space based on that predicate.
347 virtual std::pair<const Value *, unsigned>
getPredicatedAddrSpace(const Value * V)348 getPredicatedAddrSpace(const Value *V) const {
349 return std::make_pair(nullptr, -1);
350 }
351
352 /// Get a \c TargetIRAnalysis appropriate for the target.
353 ///
354 /// This is used to construct the new pass manager's target IR analysis pass,
355 /// set up appropriately for this target machine. Even the old pass manager
356 /// uses this to answer queries about the IR.
357 TargetIRAnalysis getTargetIRAnalysis() const;
358
359 /// Return a TargetTransformInfo for a given function.
360 ///
361 /// The returned TargetTransformInfo is specialized to the subtarget
362 /// corresponding to \p F.
363 virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const;
364
365 /// Allow the target to modify the pass pipeline.
366 // TODO: Populate all pass names by using <Target>PassRegistry.def.
registerPassBuilderCallbacks(PassBuilder &,bool PopulateClassToPassNames)367 virtual void registerPassBuilderCallbacks(PassBuilder &,
368 bool PopulateClassToPassNames) {}
369
370 /// Allow the target to register alias analyses with the AAManager for use
371 /// with the new pass manager. Only affects the "default" AAManager.
registerDefaultAliasAnalyses(AAManager &)372 virtual void registerDefaultAliasAnalyses(AAManager &) {}
373
374 /// Add passes to the specified pass manager to get the specified file
375 /// emitted. Typically this will involve several steps of code generation.
376 /// This method should return true if emission of this file type is not
377 /// supported, or false on success.
378 /// \p MMIWP is an optional parameter that, if set to non-nullptr,
379 /// will be used to set the MachineModuloInfo for this PM.
380 virtual bool
381 addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
382 raw_pwrite_stream *, CodeGenFileType,
383 bool /*DisableVerify*/ = true,
384 MachineModuleInfoWrapperPass *MMIWP = nullptr) {
385 return true;
386 }
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 ///
393 virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
394 raw_pwrite_stream &,
395 bool /*DisableVerify*/ = true) {
396 return true;
397 }
398
399 /// True if subtarget inserts the final scheduling pass on its own.
400 ///
401 /// Branch relaxation, which must happen after block placement, can
402 /// on some targets (e.g. SystemZ) expose additional post-RA
403 /// scheduling opportunities.
targetSchedulesPostRAScheduling()404 virtual bool targetSchedulesPostRAScheduling() const { return false; };
405
406 void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
407 Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
408 MCSymbol *getSymbol(const GlobalValue *GV) const;
409
410 /// The integer bit size to use for SjLj based exception handling.
411 static constexpr unsigned DefaultSjLjDataSize = 32;
getSjLjDataSize()412 virtual unsigned getSjLjDataSize() const { return DefaultSjLjDataSize; }
413
414 static std::pair<int, int> parseBinutilsVersion(StringRef Version);
415
416 /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
417 /// (e.g. stack) the target returns the corresponding address space.
getAddressSpaceForPseudoSourceKind(unsigned Kind)418 virtual unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
419 return 0;
420 }
421 };
422
423 /// This class describes a target machine that is implemented with the LLVM
424 /// target-independent code generator.
425 ///
426 class LLVMTargetMachine : public TargetMachine {
427 protected: // Can only create subclasses.
428 LLVMTargetMachine(const Target &T, StringRef DataLayoutString,
429 const Triple &TT, StringRef CPU, StringRef FS,
430 const TargetOptions &Options, Reloc::Model RM,
431 CodeModel::Model CM, CodeGenOptLevel OL);
432
433 void initAsmInfo();
434
435 public:
436 /// Get a TargetTransformInfo implementation for the target.
437 ///
438 /// The TTI returned uses the common code generator to answer queries about
439 /// the IR.
440 TargetTransformInfo getTargetTransformInfo(const Function &F) const override;
441
442 /// Create a pass configuration object to be used by addPassToEmitX methods
443 /// for generating a pipeline of CodeGen passes.
444 virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
445
446 /// Add passes to the specified pass manager to get the specified file
447 /// emitted. Typically this will involve several steps of code generation.
448 /// \p MMIWP is an optional parameter that, if set to non-nullptr,
449 /// will be used to set the MachineModuloInfo for this PM.
450 bool
451 addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
452 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
453 bool DisableVerify = true,
454 MachineModuleInfoWrapperPass *MMIWP = nullptr) override;
455
buildCodeGenPipeline(ModulePassManager &,raw_pwrite_stream &,raw_pwrite_stream *,CodeGenFileType,CGPassBuilderOption,PassInstrumentationCallbacks *)456 virtual Error buildCodeGenPipeline(ModulePassManager &, raw_pwrite_stream &,
457 raw_pwrite_stream *, CodeGenFileType,
458 CGPassBuilderOption,
459 PassInstrumentationCallbacks *) {
460 return make_error<StringError>("buildCodeGenPipeline is not overridden",
461 inconvertibleErrorCode());
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.
isMachineVerifierClean()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.
usesPhysRegsForValues()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.
useIPRA()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"`.
unqualifiedInlineAsmVariant()504 virtual int unqualifiedInlineAsmVariant() const { return 0; }
505
506 // MachineRegisterInfo callback function
registerMachineRegisterInfoCallback(MachineFunction & MF)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
getEffectiveCodeModel(std::optional<CodeModel::Model> CM,CodeModel::Model Default)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