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
30namespace llvm {
31
32class AAManager;
33using ModulePassManager = PassManager<Module>;
34
35class Function;
36class GlobalValue;
37class MachineFunctionPassManager;
38class MachineFunctionAnalysisManager;
39class MachineModuleInfoWrapperPass;
40class Mangler;
41class MCAsmInfo;
42class MCContext;
43class MCInstrInfo;
44class MCRegisterInfo;
45class MCStreamer;
46class MCSubtargetInfo;
47class MCSymbol;
48class raw_pwrite_stream;
49class PassBuilder;
50struct PerFunctionMIParsingState;
51class SMDiagnostic;
52class SMRange;
53class Target;
54class TargetIntrinsicInfo;
55class TargetIRAnalysis;
56class TargetTransformInfo;
57class TargetLoweringObjectFile;
58class TargetPassConfig;
59class TargetSubtargetInfo;
60
61// The old pass manager infrastructure is hidden in a legacy namespace now.
62namespace legacy {
63class PassManagerBase;
64}
65using legacy::PassManagerBase;
66
67struct MachineFunctionInfo;
68namespace yaml {
69struct 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///
78class TargetMachine {
79protected: // 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 uint64_t LargeDataThreshold = 0;
104 CodeGenOptLevel OptLevel = CodeGenOptLevel::Default;
105
106 /// Contains target specific asm information.
107 std::unique_ptr<const MCAsmInfo> AsmInfo;
108 std::unique_ptr<const MCRegisterInfo> MRI;
109 std::unique_ptr<const MCInstrInfo> MII;
110 std::unique_ptr<const MCSubtargetInfo> STI;
111
112 unsigned RequireStructuredCFG : 1;
113 unsigned O0WantsFastISel : 1;
114
115 // PGO related tunables.
116 std::optional<PGOOptions> PGOOption;
117
118public:
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(AS: DL.getProgramAddressSpace());
201 }
202
203 unsigned getAllocaPointerSize() const {
204 return DL.getPointerSize(AS: 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 /// Returns the maximum code size possible under the code model.
236 uint64_t getMaxCodeSize() const;
237
238 /// Set the code model.
239 void setCodeModel(CodeModel::Model CM) { CMModel = CM; }
240
241 void setLargeDataThreshold(uint64_t LDT) { LargeDataThreshold = LDT; }
242 bool isLargeGlobalValue(const GlobalValue *GV) const;
243
244 bool isPositionIndependent() const;
245
246 bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const;
247
248 /// Returns true if this target uses emulated TLS.
249 bool useEmulatedTLS() const;
250
251 /// Returns true if this target uses TLS Descriptors.
252 bool useTLSDESC() const;
253
254 /// Returns the TLS model which should be used for the given global variable.
255 TLSModel::Model getTLSModel(const GlobalValue *GV) const;
256
257 /// Returns the optimization level: None, Less, Default, or Aggressive.
258 CodeGenOptLevel getOptLevel() const;
259
260 /// Overrides the optimization level.
261 void setOptLevel(CodeGenOptLevel Level);
262
263 void setFastISel(bool Enable) { Options.EnableFastISel = Enable; }
264 bool getO0WantsFastISel() { return O0WantsFastISel; }
265 void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; }
266 void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; }
267 void setGlobalISelAbort(GlobalISelAbortMode Mode) {
268 Options.GlobalISelAbort = Mode;
269 }
270 void setMachineOutliner(bool Enable) {
271 Options.EnableMachineOutliner = Enable;
272 }
273 void setSupportsDefaultOutlining(bool Enable) {
274 Options.SupportsDefaultOutlining = Enable;
275 }
276 void setSupportsDebugEntryValues(bool Enable) {
277 Options.SupportsDebugEntryValues = Enable;
278 }
279
280 void setCFIFixup(bool Enable) { Options.EnableCFIFixup = Enable; }
281
282 bool getAIXExtendedAltivecABI() const {
283 return Options.EnableAIXExtendedAltivecABI;
284 }
285
286 bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
287
288 /// Return true if unique basic block section names must be generated.
289 bool getUniqueBasicBlockSectionNames() const {
290 return Options.UniqueBasicBlockSectionNames;
291 }
292
293 /// Return true if data objects should be emitted into their own section,
294 /// corresponds to -fdata-sections.
295 bool getDataSections() const {
296 return Options.DataSections;
297 }
298
299 /// Return true if functions should be emitted into their own section,
300 /// corresponding to -ffunction-sections.
301 bool getFunctionSections() const {
302 return Options.FunctionSections;
303 }
304
305 /// Return true if visibility attribute should not be emitted in XCOFF,
306 /// corresponding to -mignore-xcoff-visibility.
307 bool getIgnoreXCOFFVisibility() const {
308 return Options.IgnoreXCOFFVisibility;
309 }
310
311 /// Return true if XCOFF traceback table should be emitted,
312 /// corresponding to -xcoff-traceback-table.
313 bool getXCOFFTracebackTable() const { return Options.XCOFFTracebackTable; }
314
315 /// If basic blocks should be emitted into their own section,
316 /// corresponding to -fbasic-block-sections.
317 llvm::BasicBlockSection getBBSectionsType() const {
318 return Options.BBSections;
319 }
320
321 /// Get the list of functions and basic block ids that need unique sections.
322 const MemoryBuffer *getBBSectionsFuncListBuf() const {
323 return Options.BBSectionsFuncListBuf.get();
324 }
325
326 /// Returns true if a cast between SrcAS and DestAS is a noop.
327 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
328 return false;
329 }
330
331 void setPGOOption(std::optional<PGOOptions> PGOOpt) { PGOOption = PGOOpt; }
332 const std::optional<PGOOptions> &getPGOOption() const { return PGOOption; }
333
334 /// If the specified generic pointer could be assumed as a pointer to a
335 /// specific address space, return that address space.
336 ///
337 /// Under offloading programming, the offloading target may be passed with
338 /// values only prepared on the host side and could assume certain
339 /// properties.
340 virtual unsigned getAssumedAddrSpace(const Value *V) const { return -1; }
341
342 /// If the specified predicate checks whether a generic pointer falls within
343 /// a specified address space, return that generic pointer and the address
344 /// space being queried.
345 ///
346 /// Such predicates could be specified in @llvm.assume intrinsics for the
347 /// optimizer to assume that the given generic pointer always falls within
348 /// the address space based on that predicate.
349 virtual std::pair<const Value *, unsigned>
350 getPredicatedAddrSpace(const Value *V) const {
351 return std::make_pair(x: nullptr, y: -1);
352 }
353
354 /// Get a \c TargetIRAnalysis appropriate for the target.
355 ///
356 /// This is used to construct the new pass manager's target IR analysis pass,
357 /// set up appropriately for this target machine. Even the old pass manager
358 /// uses this to answer queries about the IR.
359 TargetIRAnalysis getTargetIRAnalysis() const;
360
361 /// Return a TargetTransformInfo for a given function.
362 ///
363 /// The returned TargetTransformInfo is specialized to the subtarget
364 /// corresponding to \p F.
365 virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const;
366
367 /// Allow the target to modify the pass pipeline.
368 // TODO: Populate all pass names by using <Target>PassRegistry.def.
369 virtual void registerPassBuilderCallbacks(PassBuilder &,
370 bool PopulateClassToPassNames) {}
371
372 /// Allow the target to register alias analyses with the AAManager for use
373 /// with the new pass manager. Only affects the "default" AAManager.
374 virtual void registerDefaultAliasAnalyses(AAManager &) {}
375
376 /// Add passes to the specified pass manager to get the specified file
377 /// emitted. Typically this will involve several steps of code generation.
378 /// This method should return true if emission of this file type is not
379 /// supported, or false on success.
380 /// \p MMIWP is an optional parameter that, if set to non-nullptr,
381 /// will be used to set the MachineModuloInfo for this PM.
382 virtual bool
383 addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
384 raw_pwrite_stream *, CodeGenFileType,
385 bool /*DisableVerify*/ = true,
386 MachineModuleInfoWrapperPass *MMIWP = nullptr) {
387 return true;
388 }
389
390 /// Add passes to the specified pass manager to get machine code emitted with
391 /// the MCJIT. This method returns true if machine code is not supported. It
392 /// fills the MCContext Ctx pointer which can be used to build custom
393 /// MCStreamer.
394 ///
395 virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
396 raw_pwrite_stream &,
397 bool /*DisableVerify*/ = true) {
398 return true;
399 }
400
401 /// True if subtarget inserts the final scheduling pass on its own.
402 ///
403 /// Branch relaxation, which must happen after block placement, can
404 /// on some targets (e.g. SystemZ) expose additional post-RA
405 /// scheduling opportunities.
406 virtual bool targetSchedulesPostRAScheduling() const { return false; };
407
408 void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
409 Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
410 MCSymbol *getSymbol(const GlobalValue *GV) const;
411
412 /// The integer bit size to use for SjLj based exception handling.
413 static constexpr unsigned DefaultSjLjDataSize = 32;
414 virtual unsigned getSjLjDataSize() const { return DefaultSjLjDataSize; }
415
416 static std::pair<int, int> parseBinutilsVersion(StringRef Version);
417
418 /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
419 /// (e.g. stack) the target returns the corresponding address space.
420 virtual unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
421 return 0;
422 }
423};
424
425/// This class describes a target machine that is implemented with the LLVM
426/// target-independent code generator.
427///
428class LLVMTargetMachine : public TargetMachine {
429protected: // Can only create subclasses.
430 LLVMTargetMachine(const Target &T, StringRef DataLayoutString,
431 const Triple &TT, StringRef CPU, StringRef FS,
432 const TargetOptions &Options, Reloc::Model RM,
433 CodeModel::Model CM, CodeGenOptLevel OL);
434
435 void initAsmInfo();
436
437public:
438 /// Get a TargetTransformInfo implementation for the target.
439 ///
440 /// The TTI returned uses the common code generator to answer queries about
441 /// the IR.
442 TargetTransformInfo getTargetTransformInfo(const Function &F) const override;
443
444 /// Create a pass configuration object to be used by addPassToEmitX methods
445 /// for generating a pipeline of CodeGen passes.
446 virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
447
448 /// Add passes to the specified pass manager to get the specified file
449 /// emitted. Typically this will involve several steps of code generation.
450 /// \p MMIWP is an optional parameter that, if set to non-nullptr,
451 /// will be used to set the MachineModuloInfo for this PM.
452 bool
453 addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
454 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
455 bool DisableVerify = true,
456 MachineModuleInfoWrapperPass *MMIWP = nullptr) override;
457
458 virtual Error buildCodeGenPipeline(ModulePassManager &,
459 MachineFunctionPassManager &,
460 MachineFunctionAnalysisManager &,
461 raw_pwrite_stream &, raw_pwrite_stream *,
462 CodeGenFileType, CGPassBuilderOption,
463 PassInstrumentationCallbacks *) {
464 return make_error<StringError>(Args: "buildCodeGenPipeline is not overridden",
465 Args: inconvertibleErrorCode());
466 }
467
468 /// Add passes to the specified pass manager to get machine code emitted with
469 /// the MCJIT. This method returns true if machine code is not supported. It
470 /// fills the MCContext Ctx pointer which can be used to build custom
471 /// MCStreamer.
472 bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
473 raw_pwrite_stream &Out,
474 bool DisableVerify = true) override;
475
476 /// Returns true if the target is expected to pass all machine verifier
477 /// checks. This is a stopgap measure to fix targets one by one. We will
478 /// remove this at some point and always enable the verifier when
479 /// EXPENSIVE_CHECKS is enabled.
480 virtual bool isMachineVerifierClean() const { return true; }
481
482 /// Adds an AsmPrinter pass to the pipeline that prints assembly or
483 /// machine code from the MI representation.
484 bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out,
485 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
486 MCContext &Context);
487
488 Expected<std::unique_ptr<MCStreamer>>
489 createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
490 CodeGenFileType FileType, MCContext &Ctx);
491
492 /// True if the target uses physical regs (as nearly all targets do). False
493 /// for stack machines such as WebAssembly and other virtual-register
494 /// machines. If true, all vregs must be allocated before PEI. If false, then
495 /// callee-save register spilling and scavenging are not needed or used. If
496 /// false, implicitly defined registers will still be assumed to be physical
497 /// registers, except that variadic defs will be allocated vregs.
498 virtual bool usesPhysRegsForValues() const { return true; }
499
500 /// True if the target wants to use interprocedural register allocation by
501 /// default. The -enable-ipra flag can be used to override this.
502 virtual bool useIPRA() const {
503 return false;
504 }
505
506 /// The default variant to use in unqualified `asm` instructions.
507 /// If this returns 0, `asm "$(foo$|bar$)"` will evaluate to `asm "foo"`.
508 virtual int unqualifiedInlineAsmVariant() const { return 0; }
509
510 // MachineRegisterInfo callback function
511 virtual void registerMachineRegisterInfoCallback(MachineFunction &MF) const {}
512};
513
514/// Helper method for getting the code model, returning Default if
515/// CM does not have a value. The tiny and kernel models will produce
516/// an error, so targets that support them or require more complex codemodel
517/// selection logic should implement and call their own getEffectiveCodeModel.
518inline CodeModel::Model
519getEffectiveCodeModel(std::optional<CodeModel::Model> CM,
520 CodeModel::Model Default) {
521 if (CM) {
522 // By default, targets do not support the tiny and kernel models.
523 if (*CM == CodeModel::Tiny)
524 report_fatal_error(reason: "Target does not support the tiny CodeModel", gen_crash_diag: false);
525 if (*CM == CodeModel::Kernel)
526 report_fatal_error(reason: "Target does not support the kernel CodeModel", gen_crash_diag: false);
527 return *CM;
528 }
529 return Default;
530}
531
532} // end namespace llvm
533
534#endif // LLVM_TARGET_TARGETMACHINE_H
535

source code of llvm/include/llvm/Target/TargetMachine.h