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