LLVM 19.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"
16#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/Module.h"
27#include <cstring>
28#include <optional>
29
30using namespace llvm;
31
32namespace llvm {
33
34/// Options for LLVMCreateTargetMachine().
36 std::string CPU;
37 std::string Features;
38 std::string ABI;
40 std::optional<Reloc::Model> RM;
41 std::optional<CodeModel::Model> CM;
42 bool JIT;
43};
44
45} // namespace llvm
46
49
51 return reinterpret_cast<TargetMachine *>(P);
52}
54 return reinterpret_cast<Target*>(P);
55}
57 return reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine *>(P));
58}
59static LLVMTargetRef wrap(const Target * P) {
60 return reinterpret_cast<LLVMTargetRef>(const_cast<Target*>(P));
61}
62
64 if (TargetRegistry::targets().begin() == TargetRegistry::targets().end()) {
65 return nullptr;
66 }
67
68 const Target *target = &*TargetRegistry::targets().begin();
69 return wrap(target);
70}
72 return wrap(unwrap(T)->getNext());
73}
74
76 StringRef NameRef = Name;
78 [&](const Target &T) { return T.getName() == NameRef; });
79 return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
80}
81
83 char **ErrorMessage) {
84 std::string Error;
85
87
88 if (!*T) {
89 if (ErrorMessage)
90 *ErrorMessage = strdup(Error.c_str());
91
92 return 1;
93 }
94
95 return 0;
96}
97
99 return unwrap(T)->getName();
100}
101
103 return unwrap(T)->getShortDescription();
104}
105
107 return unwrap(T)->hasJIT();
108}
109
111 return unwrap(T)->hasTargetMachine();
112}
113
115 return unwrap(T)->hasMCAsmBackend();
116}
117
119 return wrap(new LLVMTargetMachineOptions());
120}
121
123 delete unwrap(Options);
124}
125
127 const char *CPU) {
128 unwrap(Options)->CPU = CPU;
129}
130
132 const char *Features) {
133 unwrap(Options)->Features = Features;
134}
135
137 const char *ABI) {
138 unwrap(Options)->ABI = ABI;
139}
140
144
145 switch (Level) {
147 OL = CodeGenOptLevel::None;
148 break;
150 OL = CodeGenOptLevel::Less;
151 break;
153 OL = CodeGenOptLevel::Aggressive;
154 break;
156 OL = CodeGenOptLevel::Default;
157 break;
158 }
159
160 unwrap(Options)->OL = OL;
161}
162
164 LLVMRelocMode Reloc) {
165 std::optional<Reloc::Model> RM;
166
167 switch (Reloc) {
168 case LLVMRelocStatic:
169 RM = Reloc::Static;
170 break;
171 case LLVMRelocPIC:
172 RM = Reloc::PIC_;
173 break;
176 break;
177 case LLVMRelocROPI:
178 RM = Reloc::ROPI;
179 break;
180 case LLVMRelocRWPI:
181 RM = Reloc::RWPI;
182 break;
184 RM = Reloc::ROPI_RWPI;
185 break;
186 case LLVMRelocDefault:
187 break;
188 }
189
190 unwrap(Options)->RM = RM;
191}
192
194 LLVMCodeModel CodeModel) {
195 auto CM = unwrap(CodeModel, unwrap(Options)->JIT);
196 unwrap(Options)->CM = CM;
197}
198
202 auto *Opt = unwrap(Options);
203 TargetOptions TO;
204 TO.MCOptions.ABIName = Opt->ABI;
205 return wrap(unwrap(T)->createTargetMachine(Triple, Opt->CPU, Opt->Features,
206 TO, Opt->RM, Opt->CM, Opt->OL,
207 Opt->JIT));
208}
209
211LLVMCreateTargetMachine(LLVMTargetRef T, const char *Triple, const char *CPU,
212 const char *Features, LLVMCodeGenOptLevel Level,
213 LLVMRelocMode Reloc, LLVMCodeModel CodeModel) {
215
221
223
225 return Machine;
226}
227
229
231 const Target* target = &(unwrap(T)->getTarget());
232 return wrap(target);
233}
234
236 std::string StringRep = unwrap(T)->getTargetTriple().str();
237 return strdup(StringRep.c_str());
238}
239
241 std::string StringRep = std::string(unwrap(T)->getTargetCPU());
242 return strdup(StringRep.c_str());
243}
244
246 std::string StringRep = std::string(unwrap(T)->getTargetFeatureString());
247 return strdup(StringRep.c_str());
248}
249
251 LLVMBool VerboseAsm) {
252 unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
253}
254
256 unwrap(T)->setFastISel(Enable);
257}
258
260 unwrap(T)->setGlobalISel(Enable);
261}
262
265 GlobalISelAbortMode AM = GlobalISelAbortMode::Enable;
266 switch (Mode) {
268 AM = GlobalISelAbortMode::Disable;
269 break;
271 AM = GlobalISelAbortMode::Enable;
272 break;
274 AM = GlobalISelAbortMode::DisableWithDiag;
275 break;
276 }
277
278 unwrap(T)->setGlobalISelAbort(AM);
279}
280
283 unwrap(T)->setMachineOutliner(Enable);
284}
285
287 return wrap(new DataLayout(unwrap(T)->createDataLayout()));
288}
289
292 LLVMCodeGenFileType codegen,
293 char **ErrorMessage) {
295 Module* Mod = unwrap(M);
296
298
299 std::string error;
300
301 Mod->setDataLayout(TM->createDataLayout());
302
304 switch (codegen) {
305 case LLVMAssemblyFile:
306 ft = CodeGenFileType::AssemblyFile;
307 break;
308 default:
309 ft = CodeGenFileType::ObjectFile;
310 break;
311 }
312 if (TM->addPassesToEmitFile(pass, OS, nullptr, ft)) {
313 error = "TargetMachine can't emit a file of this type";
314 *ErrorMessage = strdup(error.c_str());
315 return true;
316 }
317
318 pass.run(*Mod);
319
320 OS.flush();
321 return false;
322}
323
325 const char *Filename,
326 LLVMCodeGenFileType codegen,
327 char **ErrorMessage) {
328 std::error_code EC;
329 raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);
330 if (EC) {
331 *ErrorMessage = strdup(EC.message().c_str());
332 return true;
333 }
334 bool Result = LLVMTargetMachineEmit(T, M, dest, codegen, ErrorMessage);
335 dest.flush();
336 return Result;
337}
338
340 LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
341 LLVMMemoryBufferRef *OutMemBuf) {
342 SmallString<0> CodeString;
343 raw_svector_ostream OStream(CodeString);
344 bool Result = LLVMTargetMachineEmit(T, M, OStream, codegen, ErrorMessage);
345
346 StringRef Data = OStream.str();
347 *OutMemBuf =
348 LLVMCreateMemoryBufferWithMemoryRangeCopy(Data.data(), Data.size(), "");
349 return Result;
350}
351
353 return strdup(sys::getDefaultTargetTriple().c_str());
354}
355
356char *LLVMNormalizeTargetTriple(const char* triple) {
357 return strdup(Triple::normalize(StringRef(triple)).c_str());
358}
359
361 return strdup(sys::getHostCPUName().data());
362}
363
365 SubtargetFeatures Features;
366 StringMap<bool> HostFeatures;
367
368 if (sys::getHostCPUFeatures(HostFeatures))
369 for (const auto &[Feature, IsEnabled] : HostFeatures)
370 Features.AddFeature(Feature, IsEnabled);
371
372 return strdup(Features.getString().c_str());
373}
374
376 unwrap(PM)->add(
377 createTargetTransformInfoWrapperPass(unwrap(T)->getTargetIRAnalysis()));
378}
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:371
@ Enable
Definition: DwarfDebug.cpp:87
std::string Name
static LVOptions Options
Definition: LVOptions.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
modulo schedule Modulo Schedule test pass
static std::unique_ptr< TargetMachine > createTargetMachine(Function *F, CodeGenOptLevel OptLevel)
Create the TargetMachine object to query the backend for optimization preferences.
#define P(N)
Module * Mod
const char LLVMTargetMachineRef TM
raw_pwrite_stream & OS
#define error(X)
static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M, raw_pwrite_stream &OS, LLVMCodeGenFileType codegen, char **ErrorMessage)
static LLVMTargetMachineRef wrap(const TargetMachine *P)
static Target * unwrap(LLVMTargetRef P)
This pass exposes codegen information to IR-level passes.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
void setDataLayout(StringRef Desc)
Set the data layout.
Definition: Module.cpp:401
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Manages the enabling and disabling of subtarget specific features.
std::string getString() const
Returns features as a string.
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:76
MCTargetOptions MCOptions
Machine level options.
Target - Wrapper for Target specific information.
bool hasTargetMachine() const
hasTargetMachine - Check if this target supports code generation.
const char * getName() const
getName - Get the target name.
bool hasMCAsmBackend() const
hasMCAsmBackend - Check if this target supports .o generation.
const char * getShortDescription() const
getShortDescription - Get a short description of the target.
bool hasJIT() const
hasJIT - Check if this targets supports the just-in-time compilation.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
std::string normalize() const
Return the normalized form of this triple's string.
Definition: Triple.h:354
PassManager manages ModulePassManagers.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:470
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:444
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:690
StringRef str() const
Return a StringRef for the vector contents.
Definition: raw_ostream.h:715
LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(const char *InputData, size_t InputDataLength, const char *BufferName)
Definition: Core.cpp:4217
int LLVMBool
Definition: Types.h:28
struct LLVMOpaquePassManager * LLVMPassManagerRef
Definition: Types.h:127
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition: Types.h:48
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:61
LLVMCodeGenFileType
Definition: TargetMachine.h:65
void LLVMTargetMachineOptionsSetCPU(LLVMTargetMachineOptionsRef Options, const char *CPU)
void LLVMTargetMachineOptionsSetFeatures(LLVMTargetMachineOptionsRef Options, const char *Features)
Set the list of features for the target machine.
void LLVMSetTargetMachineMachineOutliner(LLVMTargetMachineRef T, LLVMBool Enable)
Enable the MachineOutliner pass.
char * LLVMGetHostCPUFeatures(void)
Get the host CPU's features as a string.
void LLVMTargetMachineOptionsSetRelocMode(LLVMTargetMachineOptionsRef Options, LLVMRelocMode Reloc)
LLVMTargetRef LLVMGetFirstTarget()
Returns the first llvm::Target in the registered targets list.
struct LLVMTarget * LLVMTargetRef
Definition: TargetMachine.h:36
char * LLVMGetHostCPUName(void)
Get the host CPU as a string.
struct LLVMOpaqueTargetMachine * LLVMTargetMachineRef
Definition: TargetMachine.h:35
LLVMCodeModel
Definition: TargetMachine.h:55
void LLVMTargetMachineOptionsSetCodeGenOptLevel(LLVMTargetMachineOptionsRef Options, LLVMCodeGenOptLevel Level)
char * LLVMGetTargetMachineCPU(LLVMTargetMachineRef T)
Returns the cpu used creating this target machine.
void LLVMDisposeTargetMachineOptions(LLVMTargetMachineOptionsRef Options)
Dispose of an LLVMTargetMachineOptionsRef instance.
const char * LLVMGetTargetName(LLVMTargetRef T)
Returns the name of a target.
struct LLVMOpaqueTargetMachineOptions * LLVMTargetMachineOptionsRef
Definition: TargetMachine.h:34
void LLVMSetTargetMachineGlobalISel(LLVMTargetMachineRef T, LLVMBool Enable)
Enable global instruction selection.
void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM)
Adds the target-specific analysis passes to the pass manager.
LLVMTargetRef LLVMGetTargetFromName(const char *Name)
Finds the target corresponding to the given name and stores it in T.
void LLVMSetTargetMachineFastISel(LLVMTargetMachineRef T, LLVMBool Enable)
Enable fast-path instruction selection.
const char * LLVMGetTargetDescription(LLVMTargetRef T)
Returns the description of a target.
char * LLVMGetDefaultTargetTriple(void)
Get a triple for the host machine as a string.
void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T, LLVMBool VerboseAsm)
Set the target machine's ASM verbosity.
LLVMTargetMachineOptionsRef LLVMCreateTargetMachineOptions(void)
Create a new set of options for an llvm::TargetMachine.
LLVMBool LLVMGetTargetFromTriple(const char *TripleStr, LLVMTargetRef *T, char **ErrorMessage)
Finds the target corresponding to the given triple and stores it in T.
char * LLVMNormalizeTargetTriple(const char *triple)
Normalize a target triple.
LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T)
Returns if the target as an ASM backend (required for emitting output)
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.
char * LLVMGetTargetMachineTriple(LLVMTargetMachineRef T)
Returns the triple used creating this target machine.
LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, const char *Triple, const char *CPU, const char *Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel)
Creates a new llvm::TargetMachine.
void LLVMTargetMachineOptionsSetABI(LLVMTargetMachineOptionsRef Options, const char *ABI)
LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T)
Returns the next llvm::Target given a previous one (or null if there's none)
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.
LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T)
Create a DataLayout based on the targetMachine.
LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T)
Returns if the target has a TargetMachine associated.
LLVMRelocMode
Definition: TargetMachine.h:45
LLVMCodeGenOptLevel
Definition: TargetMachine.h:38
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition: Target.h:37
LLVMTargetMachineRef LLVMCreateTargetMachineWithOptions(LLVMTargetRef T, const char *Triple, LLVMTargetMachineOptionsRef Options)
Create a new llvm::TargetMachine.
LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T)
Returns the Target used in a TargetMachine.
LLVMGlobalISelAbortMode
Definition: TargetMachine.h:70
void LLVMTargetMachineOptionsSetCodeModel(LLVMTargetMachineOptionsRef Options, LLVMCodeModel CodeModel)
void LLVMSetTargetMachineGlobalISelAbort(LLVMTargetMachineRef T, LLVMGlobalISelAbortMode Mode)
Set abort behaviour when global instruction selection fails to lower/select an instruction.
void LLVMDisposeTargetMachine(LLVMTargetMachineRef T)
Dispose the LLVMTargetMachineRef instance generated by LLVMCreateTargetMachine.
LLVMBool LLVMTargetHasJIT(LLVMTargetRef T)
Returns if the target has a JIT.
char * LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T)
Returns the feature string used creating this target machine.
@ LLVMAssemblyFile
Definition: TargetMachine.h:66
@ LLVMRelocPIC
Definition: TargetMachine.h:48
@ LLVMRelocDynamicNoPic
Definition: TargetMachine.h:49
@ LLVMRelocStatic
Definition: TargetMachine.h:47
@ LLVMRelocRWPI
Definition: TargetMachine.h:51
@ LLVMRelocROPI
Definition: TargetMachine.h:50
@ LLVMRelocROPI_RWPI
Definition: TargetMachine.h:52
@ LLVMRelocDefault
Definition: TargetMachine.h:46
@ LLVMCodeGenLevelAggressive
Definition: TargetMachine.h:42
@ LLVMCodeGenLevelDefault
Definition: TargetMachine.h:41
@ LLVMCodeGenLevelNone
Definition: TargetMachine.h:39
@ LLVMCodeGenLevelLess
Definition: TargetMachine.h:40
@ LLVMGlobalISelAbortDisableWithDiag
Definition: TargetMachine.h:73
@ LLVMGlobalISelAbortDisable
Definition: TargetMachine.h:72
@ LLVMGlobalISelAbortEnable
Definition: TargetMachine.h:71
@ DynamicNoPIC
Definition: CodeGen.h:25
@ ROPI_RWPI
Definition: CodeGen.h:25
StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition: Host.cpp:1667
bool getHostCPUFeatures(StringMap< bool, MallocAllocator > &Features)
getHostCPUFeatures - Get the LLVM names for the host CPU features.
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:83
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
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:1758
GlobalISelAbortMode
Enable abort calls when global instruction selection fails to lower/select an instruction.
Options for LLVMCreateTargetMachine().
std::optional< Reloc::Model > RM
std::optional< CodeModel::Model > CM
static const Target * lookupTarget(StringRef Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
static iterator_range< iterator > targets()