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"
15#include "llvm/Analysis/TargetTransformInfo.h"
16#include "llvm/IR/DataLayout.h"
17#include "llvm/IR/LegacyPassManager.h"
18#include "llvm/IR/Module.h"
19#include "llvm/MC/TargetRegistry.h"
20#include "llvm/Support/CBindingWrapping.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/raw_ostream.h"
24#include "llvm/Target/CodeGenCWrappers.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/TargetParser/Host.h"
27#include "llvm/TargetParser/SubtargetFeature.h"
28#include <optional>
29
30using namespace llvm;
31
32namespace llvm {
33
34/// Options for LLVMCreateTargetMachine().
35struct LLVMTargetMachineOptions {
36 std::string CPU;
37 std::string Features;
38 std::string ABI;
39 CodeGenOptLevel OL = CodeGenOptLevel::Default;
40 std::optional<Reloc::Model> RM;
41 std::optional<CodeModel::Model> CM;
42 bool JIT;
43};
44
45} // namespace llvm
46
47DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMTargetMachineOptions,
48 LLVMTargetMachineOptionsRef)
49
50static TargetMachine *unwrap(LLVMTargetMachineRef P) {
51 return reinterpret_cast<TargetMachine *>(P);
52}
53static Target *unwrap(LLVMTargetRef P) {
54 return reinterpret_cast<Target*>(P);
55}
56static LLVMTargetMachineRef wrap(const TargetMachine *P) {
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
63LLVMTargetRef LLVMGetFirstTarget() {
64 if (TargetRegistry::targets().begin() == TargetRegistry::targets().end()) {
65 return nullptr;
66 }
67
68 const Target *target = &*TargetRegistry::targets().begin();
69 return wrap(P: target);
70}
71LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T) {
72 return wrap(P: unwrap(P: T)->getNext());
73}
74
75LLVMTargetRef LLVMGetTargetFromName(const char *Name) {
76 StringRef NameRef = Name;
77 auto I = find_if(Range: TargetRegistry::targets(),
78 P: [&](const Target &T) { return T.getName() == NameRef; });
79 return I != TargetRegistry::targets().end() ? wrap(P: &*I) : nullptr;
80}
81
82LLVMBool LLVMGetTargetFromTriple(const char* TripleStr, LLVMTargetRef *T,
83 char **ErrorMessage) {
84 std::string Error;
85
86 Triple TT(TripleStr);
87 *T = wrap(P: TargetRegistry::lookupTarget(TheTriple: TT, Error));
88
89 if (!*T) {
90 if (ErrorMessage)
91 *ErrorMessage = strdup(s: Error.c_str());
92
93 return 1;
94 }
95
96 return 0;
97}
98
99const char * LLVMGetTargetName(LLVMTargetRef T) {
100 return unwrap(P: T)->getName();
101}
102
103const char * LLVMGetTargetDescription(LLVMTargetRef T) {
104 return unwrap(P: T)->getShortDescription();
105}
106
107LLVMBool LLVMTargetHasJIT(LLVMTargetRef T) {
108 return unwrap(P: T)->hasJIT();
109}
110
111LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T) {
112 return unwrap(P: T)->hasTargetMachine();
113}
114
115LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T) {
116 return unwrap(P: T)->hasMCAsmBackend();
117}
118
119LLVMTargetMachineOptionsRef LLVMCreateTargetMachineOptions(void) {
120 return wrap(P: new LLVMTargetMachineOptions());
121}
122
123void LLVMDisposeTargetMachineOptions(LLVMTargetMachineOptionsRef Options) {
124 delete unwrap(P: Options);
125}
126
127void LLVMTargetMachineOptionsSetCPU(LLVMTargetMachineOptionsRef Options,
128 const char *CPU) {
129 unwrap(P: Options)->CPU = CPU;
130}
131
132void LLVMTargetMachineOptionsSetFeatures(LLVMTargetMachineOptionsRef Options,
133 const char *Features) {
134 unwrap(P: Options)->Features = Features;
135}
136
137void LLVMTargetMachineOptionsSetABI(LLVMTargetMachineOptionsRef Options,
138 const char *ABI) {
139 unwrap(P: Options)->ABI = ABI;
140}
141
142void LLVMTargetMachineOptionsSetCodeGenOptLevel(
143 LLVMTargetMachineOptionsRef Options, LLVMCodeGenOptLevel Level) {
144 CodeGenOptLevel OL;
145
146 switch (Level) {
147 case LLVMCodeGenLevelNone:
148 OL = CodeGenOptLevel::None;
149 break;
150 case LLVMCodeGenLevelLess:
151 OL = CodeGenOptLevel::Less;
152 break;
153 case LLVMCodeGenLevelAggressive:
154 OL = CodeGenOptLevel::Aggressive;
155 break;
156 case LLVMCodeGenLevelDefault:
157 OL = CodeGenOptLevel::Default;
158 break;
159 }
160
161 unwrap(P: Options)->OL = OL;
162}
163
164void LLVMTargetMachineOptionsSetRelocMode(LLVMTargetMachineOptionsRef Options,
165 LLVMRelocMode Reloc) {
166 std::optional<Reloc::Model> RM;
167
168 switch (Reloc) {
169 case LLVMRelocStatic:
170 RM = Reloc::Static;
171 break;
172 case LLVMRelocPIC:
173 RM = Reloc::PIC_;
174 break;
175 case LLVMRelocDynamicNoPic:
176 RM = Reloc::DynamicNoPIC;
177 break;
178 case LLVMRelocROPI:
179 RM = Reloc::ROPI;
180 break;
181 case LLVMRelocRWPI:
182 RM = Reloc::RWPI;
183 break;
184 case LLVMRelocROPI_RWPI:
185 RM = Reloc::ROPI_RWPI;
186 break;
187 case LLVMRelocDefault:
188 break;
189 }
190
191 unwrap(P: Options)->RM = RM;
192}
193
194void LLVMTargetMachineOptionsSetCodeModel(LLVMTargetMachineOptionsRef Options,
195 LLVMCodeModel CodeModel) {
196 auto CM = unwrap(Model: CodeModel, JIT&: unwrap(P: Options)->JIT);
197 unwrap(P: Options)->CM = CM;
198}
199
200LLVMTargetMachineRef
201LLVMCreateTargetMachineWithOptions(LLVMTargetRef T, const char *TripleStr,
202 LLVMTargetMachineOptionsRef Options) {
203 auto *Opt = unwrap(P: Options);
204 TargetOptions TO;
205 TO.MCOptions.ABIName = Opt->ABI;
206 TO.MCOptions.LibraryOptions = &cl::getCAPILibraryOptions();
207 return wrap(P: unwrap(P: T)->createTargetMachine(TT: Triple(TripleStr), CPU: Opt->CPU,
208 Features: Opt->Features, Options: TO, RM: Opt->RM,
209 CM: Opt->CM, OL: Opt->OL, JIT: Opt->JIT));
210}
211
212LLVMTargetMachineRef
213LLVMCreateTargetMachine(LLVMTargetRef T, const char *Triple, const char *CPU,
214 const char *Features, LLVMCodeGenOptLevel Level,
215 LLVMRelocMode Reloc, LLVMCodeModel CodeModel) {
216 auto *Options = LLVMCreateTargetMachineOptions();
217
218 LLVMTargetMachineOptionsSetCPU(Options, CPU);
219 LLVMTargetMachineOptionsSetFeatures(Options, Features);
220 LLVMTargetMachineOptionsSetCodeGenOptLevel(Options, Level);
221 LLVMTargetMachineOptionsSetRelocMode(Options, Reloc);
222 LLVMTargetMachineOptionsSetCodeModel(Options, CodeModel);
223
224 auto *Machine = LLVMCreateTargetMachineWithOptions(T, TripleStr: Triple, Options);
225
226 LLVMDisposeTargetMachineOptions(Options);
227 return Machine;
228}
229
230void LLVMDisposeTargetMachine(LLVMTargetMachineRef T) { delete unwrap(P: T); }
231
232LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T) {
233 const Target* target = &(unwrap(P: T)->getTarget());
234 return wrap(P: target);
235}
236
237char* LLVMGetTargetMachineTriple(LLVMTargetMachineRef T) {
238 std::string StringRep = unwrap(P: T)->getTargetTriple().str();
239 return strdup(s: StringRep.c_str());
240}
241
242char* LLVMGetTargetMachineCPU(LLVMTargetMachineRef T) {
243 std::string StringRep = std::string(unwrap(P: T)->getTargetCPU());
244 return strdup(s: StringRep.c_str());
245}
246
247char* LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T) {
248 std::string StringRep = std::string(unwrap(P: T)->getTargetFeatureString());
249 return strdup(s: StringRep.c_str());
250}
251
252void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T,
253 LLVMBool VerboseAsm) {
254 unwrap(P: T)->Options.MCOptions.AsmVerbose = VerboseAsm;
255}
256
257void LLVMSetTargetMachineFastISel(LLVMTargetMachineRef T, LLVMBool Enable) {
258 unwrap(P: T)->setFastISel(Enable);
259}
260
261void LLVMSetTargetMachineGlobalISel(LLVMTargetMachineRef T, LLVMBool Enable) {
262 unwrap(P: T)->setGlobalISel(Enable);
263}
264
265void LLVMSetTargetMachineGlobalISelAbort(LLVMTargetMachineRef T,
266 LLVMGlobalISelAbortMode Mode) {
267 GlobalISelAbortMode AM = GlobalISelAbortMode::Enable;
268 switch (Mode) {
269 case LLVMGlobalISelAbortDisable:
270 AM = GlobalISelAbortMode::Disable;
271 break;
272 case LLVMGlobalISelAbortEnable:
273 AM = GlobalISelAbortMode::Enable;
274 break;
275 case LLVMGlobalISelAbortDisableWithDiag:
276 AM = GlobalISelAbortMode::DisableWithDiag;
277 break;
278 }
279
280 unwrap(P: T)->setGlobalISelAbort(AM);
281}
282
283void LLVMSetTargetMachineMachineOutliner(LLVMTargetMachineRef T,
284 LLVMBool Enable) {
285 unwrap(P: T)->setMachineOutliner(Enable);
286}
287
288LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T) {
289 TargetMachine *TM = unwrap(P: T);
290 return wrap(P: new DataLayout(TM->getTargetTriple().computeDataLayout(
291 ABIName: TM->Options.MCOptions.getABIName())));
292}
293
294static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M,
295 raw_pwrite_stream &OS,
296 LLVMCodeGenFileType codegen,
297 char **ErrorMessage) {
298 TargetMachine* TM = unwrap(P: T);
299 Module* Mod = unwrap(P: M);
300
301 legacy::PassManager pass;
302
303 std::string error;
304
305 Mod->setDataLayout(TM->getTargetTriple().computeDataLayout(
306 ABIName: TM->Options.MCOptions.getABIName()));
307
308 CodeGenFileType ft;
309 switch (codegen) {
310 case LLVMAssemblyFile:
311 ft = CodeGenFileType::AssemblyFile;
312 break;
313 default:
314 ft = CodeGenFileType::ObjectFile;
315 break;
316 }
317 if (TM->addPassesToEmitFile(pass, OS, nullptr, ft)) {
318 error = "TargetMachine can't emit a file of this type";
319 *ErrorMessage = strdup(s: error.c_str());
320 return true;
321 }
322
323 pass.run(M&: *Mod);
324
325 OS.flush();
326 return false;
327}
328
329LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
330 const char *Filename,
331 LLVMCodeGenFileType codegen,
332 char **ErrorMessage) {
333 std::error_code EC;
334 raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);
335 if (EC) {
336 *ErrorMessage = strdup(s: EC.message().c_str());
337 return true;
338 }
339 bool Result = LLVMTargetMachineEmit(T, M, OS&: dest, codegen, ErrorMessage);
340 dest.flush();
341 return Result;
342}
343
344LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T,
345 LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
346 LLVMMemoryBufferRef *OutMemBuf) {
347 SmallString<0> CodeString;
348 raw_svector_ostream OStream(CodeString);
349 bool Result = LLVMTargetMachineEmit(T, M, OS&: OStream, codegen, ErrorMessage);
350
351 StringRef Data = OStream.str();
352 *OutMemBuf =
353 LLVMCreateMemoryBufferWithMemoryRangeCopy(InputData: Data.data(), InputDataLength: Data.size(), BufferName: "");
354 return Result;
355}
356
357char *LLVMGetDefaultTargetTriple(void) {
358 return strdup(s: sys::getDefaultTargetTriple().c_str());
359}
360
361char *LLVMNormalizeTargetTriple(const char* triple) {
362 return strdup(s: Triple::normalize(Str: StringRef(triple)).c_str());
363}
364
365char *LLVMGetHostCPUName(void) {
366 return strdup(s: sys::getHostCPUName().data());
367}
368
369char *LLVMGetHostCPUFeatures(void) {
370 SubtargetFeatures Features;
371 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
372 Features.AddFeature(String: Feature, Enable: IsEnabled);
373
374 return strdup(s: Features.getString().c_str());
375}
376
377void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM) {
378 unwrap(P: PM)->add(
379 P: createTargetTransformInfoWrapperPass(TIRA: unwrap(P: T)->getTargetIRAnalysis()));
380}
381