LLVM  17.0.0git
TargetMachineC.cpp
Go to the documentation of this file.
1 //===-- TargetMachine.cpp -------------------------------------------------===//
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 implements the LLVM-C part of TargetMachine.h
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm-c/Core.h"
14 #include "llvm-c/TargetMachine.h"
16 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/Module.h"
20 #include "llvm/MC/TargetRegistry.h"
22 #include "llvm/Support/Host.h"
26 #include <cstring>
27 #include <optional>
28 
29 using namespace llvm;
30 
32  return reinterpret_cast<TargetMachine *>(P);
33 }
35  return reinterpret_cast<Target*>(P);
36 }
38  return reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine *>(P));
39 }
40 static LLVMTargetRef wrap(const Target * P) {
41  return reinterpret_cast<LLVMTargetRef>(const_cast<Target*>(P));
42 }
43 
46  return nullptr;
47  }
48 
49  const Target *target = &*TargetRegistry::targets().begin();
50  return wrap(target);
51 }
53  return wrap(unwrap(T)->getNext());
54 }
55 
57  StringRef NameRef = Name;
59  [&](const Target &T) { return T.getName() == NameRef; });
60  return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
61 }
62 
64  char **ErrorMessage) {
65  std::string Error;
66 
67  *T = wrap(TargetRegistry::lookupTarget(TripleStr, Error));
68 
69  if (!*T) {
70  if (ErrorMessage)
71  *ErrorMessage = strdup(Error.c_str());
72 
73  return 1;
74  }
75 
76  return 0;
77 }
78 
80  return unwrap(T)->getName();
81 }
82 
84  return unwrap(T)->getShortDescription();
85 }
86 
88  return unwrap(T)->hasJIT();
89 }
90 
92  return unwrap(T)->hasTargetMachine();
93 }
94 
96  return unwrap(T)->hasMCAsmBackend();
97 }
98 
100  const char *Triple, const char *CPU, const char *Features,
101  LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc,
103  std::optional<Reloc::Model> RM;
104  switch (Reloc){
105  case LLVMRelocStatic:
106  RM = Reloc::Static;
107  break;
108  case LLVMRelocPIC:
109  RM = Reloc::PIC_;
110  break;
113  break;
114  case LLVMRelocROPI:
115  RM = Reloc::ROPI;
116  break;
117  case LLVMRelocRWPI:
118  RM = Reloc::RWPI;
119  break;
120  case LLVMRelocROPI_RWPI:
122  break;
123  default:
124  break;
125  }
126 
127  bool JIT;
128  std::optional<CodeModel::Model> CM = unwrap(CodeModel, JIT);
129 
131  switch (Level) {
133  OL = CodeGenOpt::None;
134  break;
136  OL = CodeGenOpt::Less;
137  break;
140  break;
141  default:
142  OL = CodeGenOpt::Default;
143  break;
144  }
145 
147  return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt, RM, CM,
148  OL, JIT));
149 }
150 
152 
154  const Target* target = &(unwrap(T)->getTarget());
155  return wrap(target);
156 }
157 
159  std::string StringRep = unwrap(T)->getTargetTriple().str();
160  return strdup(StringRep.c_str());
161 }
162 
164  std::string StringRep = std::string(unwrap(T)->getTargetCPU());
165  return strdup(StringRep.c_str());
166 }
167 
169  std::string StringRep = std::string(unwrap(T)->getTargetFeatureString());
170  return strdup(StringRep.c_str());
171 }
172 
174  LLVMBool VerboseAsm) {
175  unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
176 }
177 
179  return wrap(new DataLayout(unwrap(T)->createDataLayout()));
180 }
181 
183  raw_pwrite_stream &OS,
185  char **ErrorMessage) {
186  TargetMachine* TM = unwrap(T);
187  Module* Mod = unwrap(M);
188 
190 
191  std::string error;
192 
193  Mod->setDataLayout(TM->createDataLayout());
194 
195  CodeGenFileType ft;
196  switch (codegen) {
197  case LLVMAssemblyFile:
198  ft = CGFT_AssemblyFile;
199  break;
200  default:
201  ft = CGFT_ObjectFile;
202  break;
203  }
204  if (TM->addPassesToEmitFile(pass, OS, nullptr, ft)) {
205  error = "TargetMachine can't emit a file of this type";
206  *ErrorMessage = strdup(error.c_str());
207  return true;
208  }
209 
210  pass.run(*Mod);
211 
212  OS.flush();
213  return false;
214 }
215 
217  const char *Filename,
219  char **ErrorMessage) {
220  std::error_code EC;
221  raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);
222  if (EC) {
223  *ErrorMessage = strdup(EC.message().c_str());
224  return true;
225  }
226  bool Result = LLVMTargetMachineEmit(T, M, dest, codegen, ErrorMessage);
227  dest.flush();
228  return Result;
229 }
230 
232  LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
233  LLVMMemoryBufferRef *OutMemBuf) {
234  SmallString<0> CodeString;
235  raw_svector_ostream OStream(CodeString);
236  bool Result = LLVMTargetMachineEmit(T, M, OStream, codegen, ErrorMessage);
237 
238  StringRef Data = OStream.str();
239  *OutMemBuf =
241  return Result;
242 }
243 
245  return strdup(sys::getDefaultTargetTriple().c_str());
246 }
247 
248 char *LLVMNormalizeTargetTriple(const char* triple) {
249  return strdup(Triple::normalize(StringRef(triple)).c_str());
250 }
251 
252 char *LLVMGetHostCPUName(void) {
253  return strdup(sys::getHostCPUName().data());
254 }
255 
257  SubtargetFeatures Features;
258  StringMap<bool> HostFeatures;
259 
260  if (sys::getHostCPUFeatures(HostFeatures))
261  for (const auto &[Feature, IsEnabled] : HostFeatures)
262  Features.AddFeature(Feature, IsEnabled);
263 
264  return strdup(Features.getString().c_str());
265 }
266 
268  unwrap(PM)->add(
269  createTargetTransformInfoWrapperPass(unwrap(T)->getTargetIRAnalysis()));
270 }
LLVMCreateTargetMachine
LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, const char *Triple, const char *CPU, const char *Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel)
Creates a new llvm::TargetMachine.
Definition: TargetMachineC.cpp:99
LLVMTargetMachineEmit
static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M, raw_pwrite_stream &OS, LLVMCodeGenFileType codegen, char **ErrorMessage)
Definition: TargetMachineC.cpp:182
llvm::CodeGenOpt::Less
@ Less
-O1
Definition: CodeGen.h:59
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:114
FileSystem.h
llvm::sys::fs::OF_None
@ OF_None
Definition: FileSystem.h:757
createTargetMachine
static std::unique_ptr< TargetMachine > createTargetMachine(Function *F, CodeGenOpt::Level OptLevel)
Create the TargetMachine object to query the backend for optimization preferences.
Definition: OMPIRBuilder.cpp:3193
llvm::CGFT_ObjectFile
@ CGFT_ObjectFile
Definition: CodeGen.h:86
llvm::TargetOptions
Definition: TargetOptions.h:124
LLVMGetTargetName
const char * LLVMGetTargetName(LLVMTargetRef T)
Returns the name of a target.
Definition: TargetMachineC.cpp:79
T
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
LLVMSetTargetMachineAsmVerbosity
void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T, LLVMBool VerboseAsm)
Set the target machine's ASM verbosity.
Definition: TargetMachineC.cpp:173
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:149
llvm::SubtargetFeatures::AddFeature
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Definition: SubtargetFeature.cpp:37
LLVMCodeGenFileType
LLVMCodeGenFileType
Definition: TargetMachine.h:64
LLVMRelocStatic
@ LLVMRelocStatic
Definition: TargetMachine.h:46
LLVMCodeGenOptLevel
LLVMCodeGenOptLevel
Definition: TargetMachine.h:37
LLVMGetTargetDescription
const char * LLVMGetTargetDescription(LLVMTargetRef T)
Returns the description of a target.
Definition: TargetMachineC.cpp:83
codegen
Since we know that Vector is byte aligned and we know the element offset of we should change the load into a lve *x instead of doing a load store lve *x sequence Implement passing vectors by value into calls and receiving them as arguments GCC apparently tries to codegen
Definition: README_ALTIVEC.txt:46
LLVMGetTargetMachineTarget
LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T)
Returns the Target used in a TargetMachine.
Definition: TargetMachineC.cpp:153
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
LLVMTargetMachineEmitToMemoryBuffer
LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M, LLVMCodeGenFileType codegen, char **ErrorMessage, LLVMMemoryBufferRef *OutMemBuf)
Compile the LLVM IR stored in M and store the result in OutMemBuf.
Definition: TargetMachineC.cpp:231
llvm::sys::getHostCPUFeatures
bool getHostCPUFeatures(StringMap< bool, MallocAllocator > &Features)
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Module.h
llvm::sys::path::end
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
llvm::sys::path::begin
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:226
llvm::Reloc::ROPI_RWPI
@ ROPI_RWPI
Definition: CodeGen.h:25
error
#define error(X)
Definition: SymbolRecordMapping.cpp:14
llvm::TargetRegistry::lookupTarget
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Definition: TargetRegistry.cpp:62
LegacyPassManager.h
LLVMGetTargetFromName
LLVMTargetRef LLVMGetTargetFromName(const char *Name)
Finds the target corresponding to the given name and stores it in T.
Definition: TargetMachineC.cpp:56
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
LLVMRelocROPI
@ LLVMRelocROPI
Definition: TargetMachine.h:49
LLVMGetFirstTarget
LLVMTargetRef LLVMGetFirstTarget()
Returns the first llvm::Target in the registered targets list.
Definition: TargetMachineC.cpp:44
LLVMTargetDataRef
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition: DataLayout.h:42
LLVMTargetMachineEmitToFile
LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M, const char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage)
Emits an asm or object file for the given module to the filename.
Definition: TargetMachineC.cpp:216
LLVMAssemblyFile
@ LLVMAssemblyFile
Definition: TargetMachine.h:65
LLVMCodeGenLevelLess
@ LLVMCodeGenLevelLess
Definition: TargetMachine.h:39
LLVMTargetHasTargetMachine
LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T)
Returns if the target has a TargetMachine associated.
Definition: TargetMachineC.cpp:91
LLVMTargetRef
struct LLVMTarget * LLVMTargetRef
Definition: TargetMachine.h:35
SubtargetFeature.h
llvm::MSP430Attrs::CodeModel
CodeModel
Definition: MSP430Attributes.h:37
TargetMachine.h
llvm::TargetRegistry::targets
static iterator_range< iterator > targets()
Definition: TargetRegistry.cpp:20
LLVMCreateTargetDataLayout
LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T)
Create a DataLayout based on the targetMachine.
Definition: TargetMachineC.cpp:178
LLVMRelocMode
LLVMRelocMode
Definition: TargetMachine.h:44
llvm::CodeGenOpt::Aggressive
@ Aggressive
-O3
Definition: CodeGen.h:61
llvm::SubtargetFeatures
Manages the enabling and disabling of subtarget specific features.
Definition: SubtargetFeature.h:181
LLVMRelocPIC
@ LLVMRelocPIC
Definition: TargetMachine.h:47
opt
arm prera ldst opt
Definition: ARMLoadStoreOptimizer.cpp:2191
pass
modulo schedule Modulo Schedule test pass
Definition: ModuloSchedule.cpp:2144
Host.h
llvm::unwrap
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:285
llvm::raw_ostream::flush
void flush()
Definition: raw_ostream.h:185
LLVMTargetHasJIT
LLVMBool LLVMTargetHasJIT(LLVMTargetRef T)
Returns if the target has a JIT.
Definition: TargetMachineC.cpp:87
llvm::StringMap< bool >
llvm::SmallString< 0 >
LLVMCodeModel
LLVMCodeModel
Definition: TargetMachine.h:54
llvm::createTargetTransformInfoWrapperPass
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
Definition: TargetTransformInfo.cpp:1237
CodeGenCWrappers.h
llvm::SubtargetFeatures::getString
std::string getString() const
Returns features as a string.
Definition: SubtargetFeature.cpp:55
llvm::raw_pwrite_stream
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:428
llvm::EngineKind::JIT
@ JIT
Definition: ExecutionEngine.h:524
llvm::Triple::normalize
std::string normalize() const
Return the normalized form of this triple's string.
Definition: Triple.h:348
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::Module::setDataLayout
void setDataLayout(StringRef Desc)
Set the data layout.
Definition: Module.cpp:392
LLVMGetTargetMachineCPU
char * LLVMGetTargetMachineCPU(LLVMTargetMachineRef T)
Returns the cpu used creating this target machine.
Definition: TargetMachineC.cpp:163
llvm::TargetMachine
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:78
LLVMCodeGenLevelNone
@ LLVMCodeGenLevelNone
Definition: TargetMachine.h:38
llvm::Reloc::ROPI
@ ROPI
Definition: CodeGen.h:25
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
llvm::CodeGenOpt::None
@ None
-O0
Definition: CodeGen.h:58
llvm::Reloc::DynamicNoPIC
@ DynamicNoPIC
Definition: CodeGen.h:25
LLVMPassManagerRef
struct LLVMOpaquePassManager * LLVMPassManagerRef
Definition: Types.h:127
llvm::wrap
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:280
LLVMGetHostCPUFeatures
char * LLVMGetHostCPUFeatures(void)
Get the host CPU's features as a string.
Definition: TargetMachineC.cpp:256
llvm::Reloc::RWPI
@ RWPI
Definition: CodeGen.h:25
llvm::AArch64::RM
@ RM
Definition: AArch64ISelLowering.h:499
llvm::sys::getDefaultTargetTriple
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
LLVMDisposeTargetMachine
void LLVMDisposeTargetMachine(LLVMTargetMachineRef T)
Dispose the LLVMTargetMachineRef instance generated by LLVMCreateTargetMachine.
Definition: TargetMachineC.cpp:151
LLVMRelocDynamicNoPic
@ LLVMRelocDynamicNoPic
Definition: TargetMachine.h:48
llvm::Reloc::PIC_
@ PIC_
Definition: CodeGen.h:25
DataLayout.h
llvm::CodeGenFileType
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:84
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
llvm::raw_svector_ostream::str
StringRef str() const
Return a StringRef for the vector contents.
Definition: raw_ostream.h:697
llvm::Reloc::Static
@ Static
Definition: CodeGen.h:25
LLVMCodeGenLevelAggressive
@ LLVMCodeGenLevelAggressive
Definition: TargetMachine.h:41
LLVMGetTargetMachineTriple
char * LLVMGetTargetMachineTriple(LLVMTargetMachineRef T)
Returns the triple used creating this target machine.
Definition: TargetMachineC.cpp:158
LLVMRelocROPI_RWPI
@ LLVMRelocROPI_RWPI
Definition: TargetMachine.h:51
llvm::raw_fd_ostream
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:454
LLVMCreateMemoryBufferWithMemoryRangeCopy
LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(const char *InputData, size_t InputDataLength, const char *BufferName)
Definition: Core.cpp:4034
llvm::find_if
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1762
LLVMNormalizeTargetTriple
char * LLVMNormalizeTargetTriple(const char *triple)
Normalize a target triple.
Definition: TargetMachineC.cpp:248
LLVMBool
int LLVMBool
Definition: Types.h:28
TargetMachine.h
LLVMGetDefaultTargetTriple
char * LLVMGetDefaultTargetTriple(void)
Get a triple for the host machine as a string.
Definition: TargetMachineC.cpp:244
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
llvm::legacy::PassManager
PassManager manages ModulePassManagers.
Definition: LegacyPassManager.h:52
llvm::c_str
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
Definition: WindowsSupport.h:196
LLVMGetTargetFromTriple
LLVMBool LLVMGetTargetFromTriple(const char *TripleStr, LLVMTargetRef *T, char **ErrorMessage)
Finds the target corresponding to the given triple and stores it in T.
Definition: TargetMachineC.cpp:63
LLVMGetTargetMachineFeatureString
char * LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T)
Returns the feature string used creating this target machine.
Definition: TargetMachineC.cpp:168
Core.h
LLVMTargetHasAsmBackend
LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T)
Returns if the target as an ASM backend (required for emitting output)
Definition: TargetMachineC.cpp:95
LLVMGetHostCPUName
char * LLVMGetHostCPUName(void)
Get the host CPU as a string.
Definition: TargetMachineC.cpp:252
LLVMRelocRWPI
@ LLVMRelocRWPI
Definition: TargetMachine.h:50
LLVMGetNextTarget
LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T)
Returns the next llvm::Target given a previous one (or null if there's none)
Definition: TargetMachineC.cpp:52
llvm::sys::getHostCPUName
StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition: Host.cpp:1573
TargetTransformInfo.h
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
LLVMMemoryBufferRef
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition: Types.h:48
TM
const char LLVMTargetMachineRef TM
Definition: PassBuilderBindings.cpp:47
llvm::CodeGenOpt::Level
Level
Code generation optimization level.
Definition: CodeGen.h:57
LLVMAddAnalysisPasses
void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM)
Adds the target-specific analysis passes to the pass manager.
Definition: TargetMachineC.cpp:267
Mod
Module * Mod
Definition: PassBuilderBindings.cpp:54
llvm::CGFT_AssemblyFile
@ CGFT_AssemblyFile
Definition: CodeGen.h:85
raw_ostream.h
TargetRegistry.h
LLVMTargetMachineRef
struct LLVMOpaqueTargetMachine * LLVMTargetMachineRef
Definition: TargetMachine.h:34
llvm::CodeGenOpt::Default
@ Default
-O2, -Os
Definition: CodeGen.h:60
LLVMModuleRef
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:61