llvm.org GIT mirror llvm / a063107
TargetMachine: Merge TargetMachine and LLVMTargetMachine Merge LLVMTargetMachine into TargetMachine. - There is no in-tree target anymore that just implements TargetMachine but not LLVMTargetMachine. - It should still be possible to stub out all the various functions in case a target does not want to use lib/CodeGen - This simplifies the code and avoids methods ending up in the wrong interface. Differential Revision: https://reviews.llvm.org/D38489 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@315633 91177308-0d34-0410-b5e6-96231b3b80d8 Matthias Braun 2 years ago
54 changed file(s) with 767 addition(s) and 879 deletion(s). Raw diff Collapse all Expand all
2020
2121 namespace llvm {
2222
23 class LLVMTargetMachine;
2423 struct MachineSchedContext;
2524 class PassConfigImpl;
2625 class ScheduleDAGInstrs;
26 class TargetMachine;
2727
2828 // The old pass manager infrastructure is hidden in a legacy namespace now.
2929 namespace legacy {
120120 void setStartStopPasses();
121121
122122 protected:
123 LLVMTargetMachine *TM;
123 TargetMachine *TM;
124124 PassConfigImpl *Impl = nullptr; // Internal data structures
125125 bool Initialized = false; // Flagged after all passes are configured.
126126
140140 bool addCoreISelPasses();
141141
142142 public:
143 TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm);
143 TargetPassConfig(TargetMachine &TM, PassManagerBase &pm);
144144 // Dummy constructor.
145145 TargetPassConfig();
146146
377377 virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
378378
379379 /// addOptimizedRegAlloc - Add passes related to register allocation.
380 /// LLVMTargetMachine provides standard regalloc passes for most targets.
381380 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
382381
383382 /// addPreRewrite - Add passes to the optimized register allocation pipeline
352352 /// The integrated assembler should be enabled by default (by the
353353 /// constructors) when failing to parse a valid piece of assembly (inline
354354 /// or otherwise) is considered a bug. It may then be overridden after
355 /// construction (see LLVMTargetMachine::initAsmInfo()).
355 /// construction (see TargetMachine::initAsmInfo()).
356356 bool UseIntegratedAssembler;
357357
358358 /// Preserve Comments in assembly
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file defines the TargetMachine and LLVMTargetMachine classes.
9 /// \file Defines the TargetMachine interface.
1010 //
1111 //===----------------------------------------------------------------------===//
1212
4848 using legacy::PassManagerBase;
4949
5050 //===----------------------------------------------------------------------===//
51 ///
51
5252 /// Primary interface to the complete machine description for the target
5353 /// machine. All target-specific information should be accessible through this
5454 /// interface.
55 ///
5655 class TargetMachine {
5756 protected: // Can only create subclasses.
5857 TargetMachine(const Target &T, StringRef DataLayoutString,
5958 const Triple &TargetTriple, StringRef CPU, StringRef FS,
60 const TargetOptions &Options);
59 const TargetOptions &Options, Reloc::Model RM,
60 CodeModel::Model CM, CodeGenOpt::Level OL);
6161
6262 /// The Target that this machine was created for.
6363 const Target &TheTarget;
8989
9090 unsigned RequireStructuredCFG : 1;
9191 unsigned O0WantsFastISel : 1;
92
93 void initAsmInfo();
9294
9395 public:
9496 const TargetOptions DefaultOptions;
224226 /// supported, or false on success.
225227 /// \p MMI is an optional parameter that, if set to non-nullptr,
226228 /// will be used to set the MachineModuloInfo for this PM.
227 virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
228 CodeGenFileType,
229 bool /*DisableVerify*/ = true,
230 MachineModuleInfo *MMI = nullptr) {
231 return true;
232 }
229 virtual bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
230 CodeGenFileType FileType,
231 bool DisableVerify = true,
232 MachineModuleInfo *MMI = nullptr);
233233
234234 /// Add passes to the specified pass manager to get machine code emitted with
235235 /// the MCJIT. This method returns true if machine code is not supported. It
236236 /// fills the MCContext Ctx pointer which can be used to build custom
237237 /// MCStreamer.
238 ///
239 virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
240 raw_pwrite_stream &,
241 bool /*DisableVerify*/ = true) {
242 return true;
243 }
238 virtual bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
239 raw_pwrite_stream &OS,
240 bool DisableVerify = true);
244241
245242 /// True if subtarget inserts the final scheduling pass on its own.
246243 ///
264261 virtual bool useIPRA() const {
265262 return false;
266263 }
267 };
268
269 /// This class describes a target machine that is implemented with the LLVM
270 /// target-independent code generator.
271 ///
272 class LLVMTargetMachine : public TargetMachine {
273 protected: // Can only create subclasses.
274 LLVMTargetMachine(const Target &T, StringRef DataLayoutString,
275 const Triple &TargetTriple, StringRef CPU, StringRef FS,
276 const TargetOptions &Options, Reloc::Model RM,
277 CodeModel::Model CM, CodeGenOpt::Level OL);
278
279 void initAsmInfo();
280
281 public:
282 /// \brief Get a TargetIRAnalysis implementation for the target.
283 ///
284 /// This analysis will produce a TTI result which uses the common code
285 /// generator to answer queries about the IR.
286 TargetIRAnalysis getTargetIRAnalysis() override;
287264
288265 /// Create a pass configuration object to be used by addPassToEmitX methods
289266 /// for generating a pipeline of CodeGen passes.
290267 virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
291
292 /// Add passes to the specified pass manager to get the specified file
293 /// emitted. Typically this will involve several steps of code generation.
294 /// \p MMI is an optional parameter that, if set to non-nullptr,
295 /// will be used to set the MachineModuloInfofor this PM.
296 bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
297 CodeGenFileType FileType, bool DisableVerify = true,
298 MachineModuleInfo *MMI = nullptr) override;
299
300 /// Add passes to the specified pass manager to get machine code emitted with
301 /// the MCJIT. This method returns true if machine code is not supported. It
302 /// fills the MCContext Ctx pointer which can be used to build custom
303 /// MCStreamer.
304 bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
305 raw_pwrite_stream &OS,
306 bool DisableVerify = true) override;
307268
308269 /// Returns true if the target is expected to pass all machine verifier
309270 /// checks. This is a stopgap measure to fix targets one by one. We will
5252 LiveRegUnits.cpp
5353 LiveStackAnalysis.cpp
5454 LiveVariables.cpp
55 LLVMTargetMachine.cpp
5655 LocalStackSlotAllocation.cpp
5756 LowLevelType.cpp
5857 LowerEmuTLS.cpp
141140 TargetInstrInfo.cpp
142141 TargetLoweringBase.cpp
143142 TargetLoweringObjectFileImpl.cpp
143 TargetMachine.cpp
144 TargetMachineC.cpp
144145 TargetOptionsImpl.cpp
145146 TargetPassConfig.cpp
146147 TargetRegisterInfo.cpp
+0
-259
lib/CodeGen/LLVMTargetMachine.cpp less more
None //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the LLVMTargetMachine class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Analysis/Passes.h"
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/CodeGen/BasicTTIImpl.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/TargetPassConfig.h"
19 #include "llvm/IR/IRPrintingPasses.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/Scalar.h"
37 using namespace llvm;
38
39 void LLVMTargetMachine::initAsmInfo() {
40 MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
41 MII = TheTarget.createMCInstrInfo();
42 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
43 // to some backends having subtarget feature dependent module level
44 // code generation. This is similar to the hack in the AsmPrinter for
45 // module level assembly etc.
46 STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
47 getTargetFeatureString());
48
49 MCAsmInfo *TmpAsmInfo =
50 TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
51 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
52 // and if the old one gets included then MCAsmInfo will be NULL and
53 // we'll crash later.
54 // Provide the user with a useful error message about what's wrong.
55 assert(TmpAsmInfo && "MCAsmInfo not initialized. "
56 "Make sure you include the correct TargetSelect.h"
57 "and that InitializeAllTargetMCs() is being invoked!");
58
59 if (Options.DisableIntegratedAS)
60 TmpAsmInfo->setUseIntegratedAssembler(false);
61
62 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
63
64 TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections);
65
66 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
67
68 if (Options.ExceptionModel != ExceptionHandling::None)
69 TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
70
71 AsmInfo = TmpAsmInfo;
72 }
73
74 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
75 StringRef DataLayoutString,
76 const Triple &TT, StringRef CPU,
77 StringRef FS, const TargetOptions &Options,
78 Reloc::Model RM, CodeModel::Model CM,
79 CodeGenOpt::Level OL)
80 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
81 this->RM = RM;
82 this->CMModel = CM;
83 this->OptLevel = OL;
84 }
85
86 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
87 return TargetIRAnalysis([this](const Function &F) {
88 return TargetTransformInfo(BasicTTIImpl(this, F));
89 });
90 }
91
92 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
93 static MCContext *
94 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
95 bool DisableVerify, bool &WillCompleteCodeGenPipeline,
96 raw_pwrite_stream &Out, MachineModuleInfo *MMI) {
97 // Targets may override createPassConfig to provide a target-specific
98 // subclass.
99 TargetPassConfig *PassConfig = TM->createPassConfig(PM);
100 // Set PassConfig options provided by TargetMachine.
101 PassConfig->setDisableVerify(DisableVerify);
102 WillCompleteCodeGenPipeline = PassConfig->willCompleteCodeGenPipeline();
103 PM.add(PassConfig);
104 if (!MMI)
105 MMI = new MachineModuleInfo(TM);
106 PM.add(MMI);
107
108 if (PassConfig->addISelPasses())
109 return nullptr;
110 PassConfig->addMachinePasses();
111 PassConfig->setInitialized();
112 if (!WillCompleteCodeGenPipeline)
113 PM.add(createPrintMIRPass(Out));
114
115 return &MMI->getContext();
116 }
117
118 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM,
119 raw_pwrite_stream &Out, CodeGenFileType FileType,
120 MCContext &Context) {
121 if (Options.MCOptions.MCSaveTempLabels)
122 Context.setAllowTemporaryLabels(false);
123
124 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
125 const MCAsmInfo &MAI = *getMCAsmInfo();
126 const MCRegisterInfo &MRI = *getMCRegisterInfo();
127 const MCInstrInfo &MII = *getMCInstrInfo();
128
129 std::unique_ptr AsmStreamer;
130
131 switch (FileType) {
132 case CGFT_AssemblyFile: {
133 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
134 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
135
136 // Create a code emitter if asked to show the encoding.
137 MCCodeEmitter *MCE = nullptr;
138 if (Options.MCOptions.ShowMCEncoding)
139 MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
140
141 MCAsmBackend *MAB =
142 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
143 Options.MCOptions);
144 auto FOut = llvm::make_unique(Out);
145 MCStreamer *S = getTarget().createAsmStreamer(
146 Context, std::move(FOut), Options.MCOptions.AsmVerbose,
147 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
148 Options.MCOptions.ShowMCInst);
149 AsmStreamer.reset(S);
150 break;
151 }
152 case CGFT_ObjectFile: {
153 // Create the code emitter for the target if it exists. If not, .o file
154 // emission fails.
155 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
156 MCAsmBackend *MAB =
157 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
158 Options.MCOptions);
159 if (!MCE || !MAB)
160 return true;
161
162 // Don't waste memory on names of temp labels.
163 Context.setUseNamesOnTempLabels(false);
164
165 Triple T(getTargetTriple().str());
166 AsmStreamer.reset(getTarget().createMCObjectStreamer(
167 T, Context, std::unique_ptr(MAB), Out,
168 std::unique_ptr(MCE), STI, Options.MCOptions.MCRelaxAll,
169 Options.MCOptions.MCIncrementalLinkerCompatible,
170 /*DWARFMustBeAtTheEnd*/ true));
171 break;
172 }
173 case CGFT_Null:
174 // The Null output is intended for use for performance analysis and testing,
175 // not real users.
176 AsmStreamer.reset(getTarget().createNullStreamer(Context));
177 break;
178 }
179
180 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
181 FunctionPass *Printer =
182 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
183 if (!Printer)
184 return true;
185
186 PM.add(Printer);
187 return false;
188 }
189
190 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
191 raw_pwrite_stream &Out,
192 CodeGenFileType FileType,
193 bool DisableVerify,
194 MachineModuleInfo *MMI) {
195 // Add common CodeGen passes.
196 bool WillCompleteCodeGenPipeline = true;
197 MCContext *Context = addPassesToGenerateCode(
198 this, PM, DisableVerify, WillCompleteCodeGenPipeline, Out, MMI);
199 if (!Context)
200 return true;
201
202 if (WillCompleteCodeGenPipeline && addAsmPrinter(PM, Out, FileType, *Context))
203 return true;
204
205 PM.add(createFreeMachineFunctionPass());
206 return false;
207 }
208
209 /// addPassesToEmitMC - Add passes to the specified pass manager to get
210 /// machine code emitted with the MCJIT. This method returns true if machine
211 /// code is not supported. It fills the MCContext Ctx pointer which can be
212 /// used to build custom MCStreamer.
213 ///
214 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
215 raw_pwrite_stream &Out,
216 bool DisableVerify) {
217 // Add common CodeGen passes.
218 bool WillCompleteCodeGenPipeline = true;
219 Ctx = addPassesToGenerateCode(this, PM, DisableVerify,
220 WillCompleteCodeGenPipeline, Out,
221 /*MachineModuleInfo*/ nullptr);
222 if (!Ctx)
223 return true;
224 assert(WillCompleteCodeGenPipeline && "CodeGen pipeline has been altered");
225
226 if (Options.MCOptions.MCSaveTempLabels)
227 Ctx->setAllowTemporaryLabels(false);
228
229 // Create the code emitter for the target if it exists. If not, .o file
230 // emission fails.
231 const MCRegisterInfo &MRI = *getMCRegisterInfo();
232 MCCodeEmitter *MCE =
233 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
234 MCAsmBackend *MAB =
235 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
236 Options.MCOptions);
237 if (!MCE || !MAB)
238 return true;
239
240 const Triple &T = getTargetTriple();
241 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
242 std::unique_ptr AsmStreamer(getTarget().createMCObjectStreamer(
243 T, *Ctx, std::unique_ptr(MAB), Out,
244 std::unique_ptr(MCE), STI, Options.MCOptions.MCRelaxAll,
245 Options.MCOptions.MCIncrementalLinkerCompatible,
246 /*DWARFMustBeAtTheEnd*/ true));
247
248 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
249 FunctionPass *Printer =
250 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
251 if (!Printer)
252 return true;
253
254 PM.add(Printer);
255 PM.add(createFreeMachineFunctionPass());
256
257 return false; // success!
258 }
1616 // Register live intervals: Registers must be defined only once, and must be
1717 // defined before use.
1818 //
19 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
20 // command-line option -verify-machineinstrs, or by defining the environment
21 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
22 // the verifier errors.
19 // The machine code verifier is enabled with the command-line option
20 // -verify-machineinstrs.
2321 //===----------------------------------------------------------------------===//
2422
2523 #include "llvm/ADT/BitVector.h"
0 //===-- TargetMachine.cpp - Implement the TargetMachine class -------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file Implements the TargetMachine class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Target/TargetMachine.h"
14
15 #include "llvm/Analysis/Passes.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/BasicTTIImpl.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/TargetPassConfig.h"
21 #include "llvm/IR/IRPrintingPasses.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/MC/MCAsmBackend.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Transforms/Scalar.h"
39 using namespace llvm;
40
41 TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
42 const Triple &TT, StringRef CPU, StringRef FS,
43 const TargetOptions &Options, Reloc::Model RM,
44 CodeModel::Model CM, CodeGenOpt::Level OL)
45 : TheTarget(T), DL(DataLayoutString), TargetTriple(TT), TargetCPU(CPU),
46 TargetFS(FS), RM(RM), CMModel(CM), OptLevel(OL), AsmInfo(nullptr),
47 MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
48 DefaultOptions(Options), Options(Options) {
49 }
50
51 TargetMachine::~TargetMachine() {
52 delete AsmInfo;
53 delete MRI;
54 delete MII;
55 delete STI;
56 }
57
58 bool TargetMachine::isPositionIndependent() const {
59 return getRelocationModel() == Reloc::PIC_;
60 }
61
62 // FIXME: This function needs to go away for a number of reasons:
63 // a) global state on the TargetMachine is terrible in general,
64 // b) these target options should be passed only on the function
65 // and not on the TargetMachine (via TargetOptions) at all.
66 void TargetMachine::resetTargetOptions(const Function &F) const {
67 #define RESET_OPTION(X, Y) \
68 do { \
69 if (F.hasFnAttribute(Y)) \
70 Options.X = (F.getFnAttribute(Y).getValueAsString() == "true"); \
71 else \
72 Options.X = DefaultOptions.X; \
73 } while (0)
74
75 RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
76 RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
77 RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
78 RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
79 RESET_OPTION(NoTrappingFPMath, "no-trapping-math");
80
81 StringRef Denormal =
82 F.getFnAttribute("denormal-fp-math").getValueAsString();
83 if (Denormal == "ieee")
84 Options.FPDenormalMode = FPDenormal::IEEE;
85 else if (Denormal == "preserve-sign")
86 Options.FPDenormalMode = FPDenormal::PreserveSign;
87 else if (Denormal == "positive-zero")
88 Options.FPDenormalMode = FPDenormal::PositiveZero;
89 else
90 Options.FPDenormalMode = DefaultOptions.FPDenormalMode;
91 }
92
93 Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
94
95 CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; }
96
97 /// Get the IR-specified TLS model for Var.
98 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
99 switch (GV->getThreadLocalMode()) {
100 case GlobalVariable::NotThreadLocal:
101 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
102 break;
103 case GlobalVariable::GeneralDynamicTLSModel:
104 return TLSModel::GeneralDynamic;
105 case GlobalVariable::LocalDynamicTLSModel:
106 return TLSModel::LocalDynamic;
107 case GlobalVariable::InitialExecTLSModel:
108 return TLSModel::InitialExec;
109 case GlobalVariable::LocalExecTLSModel:
110 return TLSModel::LocalExec;
111 }
112 llvm_unreachable("invalid TLS model");
113 }
114
115 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
116 const GlobalValue *GV) const {
117 Reloc::Model RM = getRelocationModel();
118 const Triple &TT = getTargetTriple();
119
120 // DLLImport explicitly marks the GV as external.
121 if (GV && GV->hasDLLImportStorageClass())
122 return false;
123
124 // Every other GV is local on COFF.
125 // Make an exception for windows OS in the triple: Some firmwares builds use
126 // *-win32-macho triples. This (accidentally?) produced windows relocations
127 // without GOT tables in older clang versions; Keep this behaviour.
128 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
129 return true;
130
131 if (GV && (GV->hasLocalLinkage() || !GV->hasDefaultVisibility()))
132 return true;
133
134 if (TT.isOSBinFormatMachO()) {
135 if (RM == Reloc::Static)
136 return true;
137 return GV && GV->isStrongDefinitionForLinker();
138 }
139
140 assert(TT.isOSBinFormatELF());
141 assert(RM != Reloc::DynamicNoPIC);
142
143 bool IsExecutable =
144 RM == Reloc::Static || M.getPIELevel() != PIELevel::Default;
145 if (IsExecutable) {
146 // If the symbol is defined, it cannot be preempted.
147 if (GV && !GV->isDeclarationForLinker())
148 return true;
149
150 bool IsTLS = GV && GV->isThreadLocal();
151 bool IsAccessViaCopyRelocs = Options.MCOptions.MCPIECopyRelocations && GV &&
152 isa(GV) &&
153 !GV->hasExternalWeakLinkage();
154 Triple::ArchType Arch = TT.getArch();
155 bool IsPPC =
156 Arch == Triple::ppc || Arch == Triple::ppc64 || Arch == Triple::ppc64le;
157 // Check if we can use copy relocations. PowerPC has no copy relocations.
158 if (!IsTLS && !IsPPC && (RM == Reloc::Static || IsAccessViaCopyRelocs))
159 return true;
160 }
161
162 // ELF supports preemption of other symbols.
163 return false;
164 }
165
166 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
167 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
168 Reloc::Model RM = getRelocationModel();
169 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
170 bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
171
172 TLSModel::Model Model;
173 if (IsSharedLibrary) {
174 if (IsLocal)
175 Model = TLSModel::LocalDynamic;
176 else
177 Model = TLSModel::GeneralDynamic;
178 } else {
179 if (IsLocal)
180 Model = TLSModel::LocalExec;
181 else
182 Model = TLSModel::InitialExec;
183 }
184
185 // If the user specified a more specific model, use that.
186 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
187 if (SelectedModel > Model)
188 return SelectedModel;
189
190 return Model;
191 }
192
193 CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
194
195 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
196
197 void TargetMachine::getNameWithPrefix(SmallVectorImpl &Name,
198 const GlobalValue *GV, Mangler &Mang,
199 bool MayAlwaysUsePrivate) const {
200 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
201 // Simple case: If GV is not private, it is not important to find out if
202 // private labels are legal in this case or not.
203 Mang.getNameWithPrefix(Name, GV, false);
204 return;
205 }
206 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
207 TLOF->getNameWithPrefix(Name, GV, *this);
208 }
209
210 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
211 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
212 SmallString<128> NameStr;
213 getNameWithPrefix(NameStr, GV, TLOF->getMangler());
214 return TLOF->getContext().getOrCreateSymbol(NameStr);
215 }
216
217 void TargetMachine::initAsmInfo() {
218 MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
219 MII = TheTarget.createMCInstrInfo();
220 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
221 // to some backends having subtarget feature dependent module level
222 // code generation. This is similar to the hack in the AsmPrinter for
223 // module level assembly etc.
224 STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
225 getTargetFeatureString());
226
227 MCAsmInfo *TmpAsmInfo =
228 TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
229 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
230 // and if the old one gets included then MCAsmInfo will be NULL and
231 // we'll crash later.
232 // Provide the user with a useful error message about what's wrong.
233 assert(TmpAsmInfo && "MCAsmInfo not initialized. "
234 "Make sure you include the correct TargetSelect.h"
235 "and that InitializeAllTargetMCs() is being invoked!");
236
237 if (Options.DisableIntegratedAS)
238 TmpAsmInfo->setUseIntegratedAssembler(false);
239
240 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
241
242 TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections);
243
244 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
245
246 if (Options.ExceptionModel != ExceptionHandling::None)
247 TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
248
249 AsmInfo = TmpAsmInfo;
250 }
251
252 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
253 return TargetIRAnalysis([this](const Function &F) {
254 return TargetTransformInfo(BasicTTIImpl(this, F));
255 });
256 }
257
258 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
259 static MCContext *
260 addPassesToGenerateCode(TargetMachine *TM, PassManagerBase &PM,
261 bool DisableVerify, bool &WillCompleteCodeGenPipeline,
262 raw_pwrite_stream &Out, MachineModuleInfo *MMI) {
263 // Targets may override createPassConfig to provide a target-specific
264 // subclass.
265 TargetPassConfig *PassConfig = TM->createPassConfig(PM);
266 // Set PassConfig options provided by TargetMachine.
267 PassConfig->setDisableVerify(DisableVerify);
268 WillCompleteCodeGenPipeline = PassConfig->willCompleteCodeGenPipeline();
269 PM.add(PassConfig);
270 if (!MMI)
271 MMI = new MachineModuleInfo(TM);
272 PM.add(MMI);
273
274 if (PassConfig->addISelPasses())
275 return nullptr;
276 PassConfig->addMachinePasses();
277 PassConfig->setInitialized();
278 if (!WillCompleteCodeGenPipeline)
279 PM.add(createPrintMIRPass(Out));
280
281 return &MMI->getContext();
282 }
283
284 bool TargetMachine::addAsmPrinter(PassManagerBase &PM,
285 raw_pwrite_stream &Out, CodeGenFileType FileType,
286 MCContext &Context) {
287 if (Options.MCOptions.MCSaveTempLabels)
288 Context.setAllowTemporaryLabels(false);
289
290 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
291 const MCAsmInfo &MAI = *getMCAsmInfo();
292 const MCRegisterInfo &MRI = *getMCRegisterInfo();
293 const MCInstrInfo &MII = *getMCInstrInfo();
294
295 std::unique_ptr AsmStreamer;
296
297 switch (FileType) {
298 case CGFT_AssemblyFile: {
299 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
300 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
301
302 // Create a code emitter if asked to show the encoding.
303 MCCodeEmitter *MCE = nullptr;
304 if (Options.MCOptions.ShowMCEncoding)
305 MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
306
307 MCAsmBackend *MAB =
308 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
309 Options.MCOptions);
310 auto FOut = llvm::make_unique(Out);
311 MCStreamer *S = getTarget().createAsmStreamer(
312 Context, std::move(FOut), Options.MCOptions.AsmVerbose,
313 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
314 Options.MCOptions.ShowMCInst);
315 AsmStreamer.reset(S);
316 break;
317 }
318 case CGFT_ObjectFile: {
319 // Create the code emitter for the target if it exists. If not, .o file
320 // emission fails.
321 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
322 MCAsmBackend *MAB =
323 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
324 Options.MCOptions);
325 if (!MCE || !MAB)
326 return true;
327
328 // Don't waste memory on names of temp labels.
329 Context.setUseNamesOnTempLabels(false);
330
331 Triple T(getTargetTriple().str());
332 AsmStreamer.reset(getTarget().createMCObjectStreamer(
333 T, Context, std::unique_ptr(MAB), Out,
334 std::unique_ptr(MCE), STI, Options.MCOptions.MCRelaxAll,
335 Options.MCOptions.MCIncrementalLinkerCompatible,
336 /*DWARFMustBeAtTheEnd*/ true));
337 break;
338 }
339 case CGFT_Null:
340 // The Null output is intended for use for performance analysis and testing,
341 // not real users.
342 AsmStreamer.reset(getTarget().createNullStreamer(Context));
343 break;
344 }
345
346 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
347 FunctionPass *Printer =
348 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
349 if (!Printer)
350 return true;
351
352 PM.add(Printer);
353 return false;
354 }
355
356 bool TargetMachine::addPassesToEmitFile(PassManagerBase &PM,
357 raw_pwrite_stream &Out,
358 CodeGenFileType FileType,
359 bool DisableVerify,
360 MachineModuleInfo *MMI) {
361 // Add common CodeGen passes.
362 bool WillCompleteCodeGenPipeline = true;
363 MCContext *Context = addPassesToGenerateCode(
364 this, PM, DisableVerify, WillCompleteCodeGenPipeline, Out, MMI);
365 if (!Context)
366 return true;
367
368 if (WillCompleteCodeGenPipeline && addAsmPrinter(PM, Out, FileType, *Context))
369 return true;
370
371 PM.add(createFreeMachineFunctionPass());
372 return false;
373 }
374
375 bool TargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
376 raw_pwrite_stream &Out,
377 bool DisableVerify) {
378 // Add common CodeGen passes.
379 bool WillCompleteCodeGenPipeline = true;
380 Ctx = addPassesToGenerateCode(this, PM, DisableVerify,
381 WillCompleteCodeGenPipeline, Out,
382 /*MachineModuleInfo*/ nullptr);
383 if (!Ctx)
384 return true;
385 assert(WillCompleteCodeGenPipeline && "CodeGen pipeline has been altered");
386
387 if (Options.MCOptions.MCSaveTempLabels)
388 Ctx->setAllowTemporaryLabels(false);
389
390 // Create the code emitter for the target if it exists. If not, .o file
391 // emission fails.
392 const MCRegisterInfo &MRI = *getMCRegisterInfo();
393 MCCodeEmitter *MCE =
394 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
395 MCAsmBackend *MAB =
396 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
397 Options.MCOptions);
398 if (!MCE || !MAB)
399 return true;
400
401 const Triple &T = getTargetTriple();
402 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
403 std::unique_ptr AsmStreamer(getTarget().createMCObjectStreamer(
404 T, *Ctx, std::unique_ptr(MAB), Out,
405 std::unique_ptr(MCE), STI, Options.MCOptions.MCRelaxAll,
406 Options.MCOptions.MCIncrementalLinkerCompatible,
407 /*DWARFMustBeAtTheEnd*/ true));
408
409 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
410 FunctionPass *Printer =
411 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
412 if (!Printer)
413 return true;
414
415 PM.add(Printer);
416 PM.add(createFreeMachineFunctionPass());
417
418 return false; // success!
419 }
0 //===-- TargetMachine.cpp -------------------------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
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/Target.h"
15 #include "llvm-c/TargetMachine.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/LegacyPassManager.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/CodeGenCWrappers.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/FormattedStream.h"
23 #include "llvm/Support/Host.h"
24 #include "llvm/Support/TargetRegistry.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include
29 #include
30 #include
31
32 using namespace llvm;
33
34 static TargetMachine *unwrap(LLVMTargetMachineRef P) {
35 return reinterpret_cast(P);
36 }
37 static Target *unwrap(LLVMTargetRef P) {
38 return reinterpret_cast(P);
39 }
40 static LLVMTargetMachineRef wrap(const TargetMachine *P) {
41 return reinterpret_cast(const_cast(P));
42 }
43 static LLVMTargetRef wrap(const Target * P) {
44 return reinterpret_cast(const_cast(P));
45 }
46
47 LLVMTargetRef LLVMGetFirstTarget() {
48 if (TargetRegistry::targets().begin() == TargetRegistry::targets().end()) {
49 return nullptr;
50 }
51
52 const Target *target = &*TargetRegistry::targets().begin();
53 return wrap(target);
54 }
55 LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T) {
56 return wrap(unwrap(T)->getNext());
57 }
58
59 LLVMTargetRef LLVMGetTargetFromName(const char *Name) {
60 StringRef NameRef = Name;
61 auto I = find_if(TargetRegistry::targets(),
62 [&](const Target &T) { return T.getName() == NameRef; });
63 return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
64 }
65
66 LLVMBool LLVMGetTargetFromTriple(const char* TripleStr, LLVMTargetRef *T,
67 char **ErrorMessage) {
68 std::string Error;
69
70 *T = wrap(TargetRegistry::lookupTarget(TripleStr, Error));
71
72 if (!*T) {
73 if (ErrorMessage)
74 *ErrorMessage = strdup(Error.c_str());
75
76 return 1;
77 }
78
79 return 0;
80 }
81
82 const char * LLVMGetTargetName(LLVMTargetRef T) {
83 return unwrap(T)->getName();
84 }
85
86 const char * LLVMGetTargetDescription(LLVMTargetRef T) {
87 return unwrap(T)->getShortDescription();
88 }
89
90 LLVMBool LLVMTargetHasJIT(LLVMTargetRef T) {
91 return unwrap(T)->hasJIT();
92 }
93
94 LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T) {
95 return unwrap(T)->hasTargetMachine();
96 }
97
98 LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T) {
99 return unwrap(T)->hasMCAsmBackend();
100 }
101
102 LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T,
103 const char *Triple, const char *CPU, const char *Features,
104 LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc,
105 LLVMCodeModel CodeModel) {
106 Optional RM;
107 switch (Reloc){
108 case LLVMRelocStatic:
109 RM = Reloc::Static;
110 break;
111 case LLVMRelocPIC:
112 RM = Reloc::PIC_;
113 break;
114 case LLVMRelocDynamicNoPic:
115 RM = Reloc::DynamicNoPIC;
116 break;
117 default:
118 break;
119 }
120
121 bool JIT;
122 Optional CM = unwrap(CodeModel, JIT);
123
124 CodeGenOpt::Level OL;
125 switch (Level) {
126 case LLVMCodeGenLevelNone:
127 OL = CodeGenOpt::None;
128 break;
129 case LLVMCodeGenLevelLess:
130 OL = CodeGenOpt::Less;
131 break;
132 case LLVMCodeGenLevelAggressive:
133 OL = CodeGenOpt::Aggressive;
134 break;
135 default:
136 OL = CodeGenOpt::Default;
137 break;
138 }
139
140 TargetOptions opt;
141 return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt, RM, CM,
142 OL, JIT));
143 }
144
145 void LLVMDisposeTargetMachine(LLVMTargetMachineRef T) { delete unwrap(T); }
146
147 LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T) {
148 const Target* target = &(unwrap(T)->getTarget());
149 return wrap(target);
150 }
151
152 char* LLVMGetTargetMachineTriple(LLVMTargetMachineRef T) {
153 std::string StringRep = unwrap(T)->getTargetTriple().str();
154 return strdup(StringRep.c_str());
155 }
156
157 char* LLVMGetTargetMachineCPU(LLVMTargetMachineRef T) {
158 std::string StringRep = unwrap(T)->getTargetCPU();
159 return strdup(StringRep.c_str());
160 }
161
162 char* LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T) {
163 std::string StringRep = unwrap(T)->getTargetFeatureString();
164 return strdup(StringRep.c_str());
165 }
166
167 void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T,
168 LLVMBool VerboseAsm) {
169 unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
170 }
171
172 LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T) {
173 return wrap(new DataLayout(unwrap(T)->createDataLayout()));
174 }
175
176 static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M,
177 raw_pwrite_stream &OS,
178 LLVMCodeGenFileType codegen,
179 char **ErrorMessage) {
180 TargetMachine* TM = unwrap(T);
181 Module* Mod = unwrap(M);
182
183 legacy::PassManager pass;
184
185 std::string error;
186
187 Mod->setDataLayout(TM->createDataLayout());
188
189 TargetMachine::CodeGenFileType ft;
190 switch (codegen) {
191 case LLVMAssemblyFile:
192 ft = TargetMachine::CGFT_AssemblyFile;
193 break;
194 default:
195 ft = TargetMachine::CGFT_ObjectFile;
196 break;
197 }
198 if (TM->addPassesToEmitFile(pass, OS, ft)) {
199 error = "TargetMachine can't emit a file of this type";
200 *ErrorMessage = strdup(error.c_str());
201 return true;
202 }
203
204 pass.run(*Mod);
205
206 OS.flush();
207 return false;
208 }
209
210 LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
211 char* Filename, LLVMCodeGenFileType codegen, char** ErrorMessage) {
212 std::error_code EC;
213 raw_fd_ostream dest(Filename, EC, sys::fs::F_None);
214 if (EC) {
215 *ErrorMessage = strdup(EC.message().c_str());
216 return true;
217 }
218 bool Result = LLVMTargetMachineEmit(T, M, dest, codegen, ErrorMessage);
219 dest.flush();
220 return Result;
221 }
222
223 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T,
224 LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
225 LLVMMemoryBufferRef *OutMemBuf) {
226 SmallString<0> CodeString;
227 raw_svector_ostream OStream(CodeString);
228 bool Result = LLVMTargetMachineEmit(T, M, OStream, codegen, ErrorMessage);
229
230 StringRef Data = OStream.str();
231 *OutMemBuf =
232 LLVMCreateMemoryBufferWithMemoryRangeCopy(Data.data(), Data.size(), "");
233 return Result;
234 }
235
236 char *LLVMGetDefaultTargetTriple(void) {
237 return strdup(sys::getDefaultTargetTriple().c_str());
238 }
239
240 void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM) {
241 unwrap(PM)->add(
242 createTargetTransformInfoWrapperPass(unwrap(T)->getTargetIRAnalysis()));
243 }
354354
355355 // Out of line constructor provides default values for pass options and
356356 // registers all common codegen passes.
357 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm)
357 TargetPassConfig::TargetPassConfig(TargetMachine &TM, PassManagerBase &pm)
358358 : ImmutablePass(ID), PM(&pm), TM(&TM) {
359359 Impl = new PassConfigImpl();
360360
407407 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
408408 ///
409409 /// Targets may override this to extend TargetPassConfig.
410 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
410 TargetPassConfig *TargetMachine::createPassConfig(PassManagerBase &PM) {
411411 return new TargetPassConfig(*this, PM);
412412 }
413413
236236 Optional CM,
237237 CodeGenOpt::Level OL, bool JIT,
238238 bool LittleEndian)
239 : LLVMTargetMachine(T,
240 computeDataLayout(TT, Options.MCOptions, LittleEndian),
241 TT, CPU, FS, Options, getEffectiveRelocModel(TT, RM),
242 getEffectiveCodeModel(TT, CM, JIT), OL),
239 : TargetMachine(T, computeDataLayout(TT, Options.MCOptions, LittleEndian),
240 TT, CPU, FS, Options, getEffectiveRelocModel(TT, RM),
241 getEffectiveCodeModel(TT, CM, JIT), OL),
243242 TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
244243 initAsmInfo();
245244 }
2222
2323 class AArch64RegisterBankInfo;
2424
25 class AArch64TargetMachine : public LLVMTargetMachine {
25 class AArch64TargetMachine : public TargetMachine {
2626 protected:
2727 std::unique_ptr TLOF;
2828 mutable StringMap> SubtargetMap;
289289 Optional RM,
290290 Optional CM,
291291 CodeGenOpt::Level OptLevel)
292 : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
293 FS, Options, getEffectiveRelocModel(RM),
294 getEffectiveCodeModel(CM), OptLevel),
292 : TargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
293 FS, Options, getEffectiveRelocModel(RM),
294 getEffectiveCodeModel(CM), OptLevel),
295295 TLOF(createTLOF(getTargetTriple())) {
296296 AS = AMDGPU::getAMDGPUAS(TT);
297297 initAsmInfo();
470470
471471 class AMDGPUPassConfig : public TargetPassConfig {
472472 public:
473 AMDGPUPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
473 AMDGPUPassConfig(TargetMachine &TM, PassManagerBase &PM)
474474 : TargetPassConfig(TM, PM) {
475475 // Exceptions and StackMaps are not supported, so these passes will never do
476476 // anything.
501501
502502 class R600PassConfig final : public AMDGPUPassConfig {
503503 public:
504 R600PassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
504 R600PassConfig(TargetMachine &TM, PassManagerBase &PM)
505505 : AMDGPUPassConfig(TM, PM) {}
506506
507507 ScheduleDAGInstrs *createMachineScheduler(
518518
519519 class GCNPassConfig final : public AMDGPUPassConfig {
520520 public:
521 GCNPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
521 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
522522 : AMDGPUPassConfig(TM, PM) {
523523 // It is necessary to know the register usage of the entire call graph. We
524524 // allow calls without EnableAMDGPUFunctionCalls if they are marked
3030 // AMDGPU Target Machine (R600+)
3131 //===----------------------------------------------------------------------===//
3232
33 class AMDGPUTargetMachine : public LLVMTargetMachine {
33 class AMDGPUTargetMachine : public TargetMachine {
3434 protected:
3535 std::unique_ptr TLOF;
3636 AMDGPUIntrinsicInfo IntrinsicInfo;
3838 Optional RM,
3939 Optional CM,
4040 CodeGenOpt::Level OL, bool JIT)
41 : LLVMTargetMachine(T,
42 "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-"
43 "f32:32:32-i64:32-f64:32-a:0:32-n32",
44 TT, CPU, FS, Options, getRelocModel(RM),
45 getEffectiveCodeModel(CM), OL),
41 : TargetMachine(T, "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-"
42 "f32:32:32-i64:32-f64:32-a:0:32-n32",
43 TT, CPU, FS, Options, getRelocModel(RM),
44 getEffectiveCodeModel(CM), OL),
4645 TLOF(make_unique()),
4746 Subtarget(TT, CPU, FS, *this) {
4847 initAsmInfo();
2020
2121 class TargetPassConfig;
2222
23 class ARCTargetMachine : public LLVMTargetMachine {
23 class ARCTargetMachine : public TargetMachine {
2424 std::unique_ptr TLOF;
2525 ARCSubtarget Subtarget;
2626
204204 Optional RM,
205205 Optional CM,
206206 CodeGenOpt::Level OL, bool isLittle)
207 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
208 CPU, FS, Options, getEffectiveRelocModel(TT, RM),
209 getEffectiveCodeModel(CM), OL),
207 : TargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
208 CPU, FS, Options, getEffectiveRelocModel(TT, RM),
209 getEffectiveCodeModel(CM), OL),
210210 TargetABI(computeTargetABI(TT, CPU, Options)),
211211 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) {
212212
2424
2525 namespace llvm {
2626
27 class ARMBaseTargetMachine : public LLVMTargetMachine {
27 class ARMBaseTargetMachine : public TargetMachine {
2828 public:
2929 enum ARMABI {
3030 ARM_ABI_UNKNOWN,
5151 Optional RM,
5252 Optional CM,
5353 CodeGenOpt::Level OL, bool JIT)
54 : LLVMTargetMachine(T, AVRDataLayout, TT, getCPU(CPU), FS, Options,
55 getEffectiveRelocModel(RM), getEffectiveCodeModel(CM),
56 OL),
54 : TargetMachine(T, AVRDataLayout, TT, getCPU(CPU), FS, Options,
55 getEffectiveRelocModel(RM), getEffectiveCodeModel(CM), OL),
5756 SubTarget(TT, getCPU(CPU), FS, *this) {
5857 this->TLOF = make_unique();
5958 initAsmInfo();
2525 namespace llvm {
2626
2727 /// A generic AVR implementation.
28 class AVRTargetMachine : public LLVMTargetMachine {
28 class AVRTargetMachine : public TargetMachine {
2929 public:
3030 AVRTargetMachine(const Target &T, const Triple &TT, StringRef CPU,
3131 StringRef FS, const TargetOptions &Options,
32 Optional RM,
33 Optional<CodeModel::Model> CM,
32 Optional<Reloc::Model> RM, Optional<CodeModel::Model> CM,
3433 CodeGenOpt::Level OL, bool JIT);
3534
3635 const AVRSubtarget *getSubtargetImpl() const;
5454 Optional RM,
5555 Optional CM,
5656 CodeGenOpt::Level OL, bool JIT)
57 : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
58 getEffectiveRelocModel(RM), getEffectiveCodeModel(CM),
59 OL),
57 : TargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
58 getEffectiveRelocModel(RM), getEffectiveCodeModel(CM), OL),
6059 TLOF(make_unique()),
6160 Subtarget(TT, CPU, FS, *this) {
6261 initAsmInfo();
1717 #include "llvm/Target/TargetMachine.h"
1818
1919 namespace llvm {
20 class BPFTargetMachine : public LLVMTargetMachine {
20 class BPFTargetMachine : public TargetMachine {
2121 std::unique_ptr TLOF;
2222 BPFSubtarget Subtarget;
2323
55 Target.cpp
66 TargetIntrinsicInfo.cpp
77 TargetLoweringObjectFile.cpp
8 TargetMachine.cpp
9 TargetMachineC.cpp
108
119 ADDITIONAL_HEADER_DIRS
1210 ${LLVM_MAIN_INCLUDE_DIR}/llvm/Target
193193 // Specify the vector alignment explicitly. For v512x1, the calculated
194194 // alignment would be 512*alignment(i1), which is 512 bytes, instead of
195195 // the required minimum of 64 bytes.
196 : LLVMTargetMachine(
196 : TargetMachine(
197197 T,
198198 "e-m:e-p:32:32:32-a:0-n16:32-"
199199 "i64:64:64-i32:32:32-i16:16:16-i1:8:8-f32:32:32-f64:64:64-"
2222
2323 class Module;
2424
25 class HexagonTargetMachine : public LLVMTargetMachine {
25 class HexagonTargetMachine : public TargetMachine {
2626 std::unique_ptr TLOF;
2727 mutable StringMap> SubtargetMap;
2828
6464 Optional RM,
6565 Optional CodeModel,
6666 CodeGenOpt::Level OptLevel, bool JIT)
67 : LLVMTargetMachine(T, computeDataLayout(), TT, Cpu, FeatureString, Options,
68 getEffectiveRelocModel(RM),
69 getEffectiveCodeModel(CodeModel), OptLevel),
67 : TargetMachine(T, computeDataLayout(), TT, Cpu, FeatureString, Options,
68 getEffectiveRelocModel(RM),
69 getEffectiveCodeModel(CodeModel), OptLevel),
7070 Subtarget(TT, Cpu, FeatureString, *this, Options, getCodeModel(),
7171 OptLevel),
7272 TLOF(new LanaiTargetObjectFile()) {
2424 namespace llvm {
2525 class formatted_raw_ostream;
2626
27 class LanaiTargetMachine : public LLVMTargetMachine {
27 class LanaiTargetMachine : public TargetMachine {
2828 LanaiSubtarget Subtarget;
2929 std::unique_ptr TLOF;
3030
4848 Optional RM,
4949 Optional CM,
5050 CodeGenOpt::Level OL, bool JIT)
51 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options), TT, CPU, FS,
52 Options, getEffectiveRelocModel(RM),
53 getEffectiveCodeModel(CM), OL),
51 : TargetMachine(T, computeDataLayout(TT, CPU, Options), TT, CPU, FS,
52 Options, getEffectiveRelocModel(RM),
53 getEffectiveCodeModel(CM), OL),
5454 TLOF(make_unique()),
5555 Subtarget(TT, CPU, FS, *this) {
5656 initAsmInfo();
2222
2323 /// MSP430TargetMachine
2424 ///
25 class MSP430TargetMachine : public LLVMTargetMachine {
25 class MSP430TargetMachine : public TargetMachine {
2626 std::unique_ptr TLOF;
2727 MSP430Subtarget Subtarget;
2828
685685 MCAssembler &MCA = getStreamer().getAssembler();
686686
687687 // It's possible that MCObjectFileInfo isn't fully initialized at this point
688 // due to an initialization order problem where LLVMTargetMachine creates the
688 // due to an initialization order problem where TargetMachine creates the
689689 // target streamer before TargetLoweringObjectFile calls
690690 // InitializeMCObjectFileInfo. There doesn't seem to be a single place that
691691 // covers all cases so this statement covers most cases and direct object
108108 Optional CM,
109109 CodeGenOpt::Level OL, bool JIT,
110110 bool isLittle)
111 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
112 CPU, FS, Options, getEffectiveRelocModel(JIT, RM),
113 getEffectiveCodeModel(CM), OL),
111 : TargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
112 CPU, FS, Options, getEffectiveRelocModel(JIT, RM),
113 getEffectiveCodeModel(CM), OL),
114114 isLittle(isLittle), TLOF(llvm::make_unique()),
115115 ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
116116 Subtarget(nullptr), DefaultSubtarget(TT, CPU, FS, isLittle, *this,
2424
2525 namespace llvm {
2626
27 class MipsTargetMachine : public LLVMTargetMachine {
27 class MipsTargetMachine : public TargetMachine {
2828 bool isLittle;
2929 std::unique_ptr TLOF;
3030 // Selected ABI
9999 CodeGenOpt::Level OL, bool is64bit)
100100 // The pic relocation model is used regardless of what the client has
101101 // specified, as it is the only relocation model currently supported.
102 : LLVMTargetMachine(T, computeDataLayout(is64bit), TT, CPU, FS, Options,
103 Reloc::PIC_, getEffectiveCodeModel(CM), OL),
102 : TargetMachine(T, computeDataLayout(is64bit), TT, CPU, FS, Options,
103 Reloc::PIC_, getEffectiveCodeModel(CM), OL),
104104 is64bit(is64bit), TLOF(llvm::make_unique()),
105105 Subtarget(TT, CPU, FS, *this) {
106106 if (TT.getOS() == Triple::NVCL)
2323
2424 /// NVPTXTargetMachine
2525 ///
26 class NVPTXTargetMachine : public LLVMTargetMachine {
26 class NVPTXTargetMachine : public TargetMachine {
2727 bool is64bit;
2828 std::unique_ptr TLOF;
2929 NVPTX::DrvInterface drvInterface;
4141 Optional RM,
4242 Optional CM,
4343 CodeGenOpt::Level OL, bool JIT)
44 : LLVMTargetMachine(T, computeDataLayout(), TT, CPU, FS, Options,
45 getEffectiveRelocModel(RM), *CM, OL) {}
44 : TargetMachine(T, computeDataLayout(), TT, CPU, FS, Options,
45 getEffectiveRelocModel(RM), *CM, OL) {}
4646
4747 Nios2TargetMachine::~Nios2TargetMachine() {}
4848
1717 #include "llvm/Target/TargetMachine.h"
1818
1919 namespace llvm {
20 class Nios2TargetMachine : public LLVMTargetMachine {
20 class Nios2TargetMachine : public TargetMachine {
2121 mutable StringMap> SubtargetMap;
2222
2323 public:
224224
225225 // The FeatureString here is a little subtle. We are modifying the feature
226226 // string with what are (currently) non-function specific overrides as it goes
227 // into the LLVMTargetMachine constructor and then using the stored value in the
227 // into the TargetMachine constructor and then using the stored value in the
228228 // Subtarget constructor below it.
229229 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
230230 StringRef CPU, StringRef FS,
232232 Optional RM,
233233 Optional CM,
234234 CodeGenOpt::Level OL, bool JIT)
235 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
236 computeFSAdditions(FS, OL, TT), Options,
237 getEffectiveRelocModel(TT, RM),
238 getEffectiveCodeModel(TT, CM, JIT), OL),
235 : TargetMachine(T, getDataLayoutString(TT), TT, CPU,
236 computeFSAdditions(FS, OL, TT), Options,
237 getEffectiveRelocModel(TT, RM),
238 getEffectiveCodeModel(TT, CM, JIT), OL),
239239 TLOF(createTLOF(getTargetTriple())),
240240 TargetABI(computeTargetABI(TT, Options)) {
241241 initAsmInfo();
2222
2323 /// Common code between 32-bit and 64-bit PowerPC targets.
2424 ///
25 class PPCTargetMachine final : public LLVMTargetMachine {
25 class PPCTargetMachine final : public TargetMachine {
2626 public:
2727 enum PPCABI { PPC_ABI_UNKNOWN, PPC_ABI_ELFv1, PPC_ABI_ELFv2 };
2828 private:
5454 Optional RM,
5555 Optional CM,
5656 CodeGenOpt::Level OL, bool JIT)
57 : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
58 getEffectiveRelocModel(TT, RM),
59 getEffectiveCodeModel(CM), OL),
57 : TargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
58 getEffectiveRelocModel(TT, RM),
59 getEffectiveCodeModel(CM), OL),
6060 TLOF(make_unique()) {
6161 initAsmInfo();
6262 }
1919 #include "llvm/Target/TargetMachine.h"
2020
2121 namespace llvm {
22 class RISCVTargetMachine : public LLVMTargetMachine {
22 class RISCVTargetMachine : public TargetMachine {
2323 std::unique_ptr TLOF;
2424
2525 public:
8787 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
8888 const TargetOptions &Options, Optional RM,
8989 Optional CM, CodeGenOpt::Level OL, bool JIT, bool is64bit)
90 : LLVMTargetMachine(
90 : TargetMachine(
9191 T, computeDataLayout(TT, is64bit), TT, CPU, FS, Options,
9292 getEffectiveRelocModel(RM),
9393 getEffectiveCodeModel(CM, getEffectiveRelocModel(RM), is64bit, JIT),
1919
2020 namespace llvm {
2121
22 class SparcTargetMachine : public LLVMTargetMachine {
22 class SparcTargetMachine : public TargetMachine {
2323 std::unique_ptr TLOF;
2424 SparcSubtarget Subtarget;
2525 bool is64Bit;
142142 Optional RM,
143143 Optional CM,
144144 CodeGenOpt::Level OL, bool JIT)
145 : LLVMTargetMachine(
145 : TargetMachine(
146146 T, computeDataLayout(TT, CPU, FS), TT, CPU, FS, Options,
147147 getEffectiveRelocModel(RM),
148148 getEffectiveCodeModel(CM, getEffectiveRelocModel(RM), JIT), OL),
2424
2525 namespace llvm {
2626
27 class SystemZTargetMachine : public LLVMTargetMachine {
27 class SystemZTargetMachine : public TargetMachine {
2828 std::unique_ptr TLOF;
2929 SystemZSubtarget Subtarget;
3030
4141 return &Subtarget;
4242 }
4343
44 // Override LLVMTargetMachine
44 // Override TargetMachine
4545 TargetPassConfig *createPassConfig(PassManagerBase &PM) override;
4646 TargetIRAnalysis getTargetIRAnalysis() override;
4747
+0
-222
lib/Target/TargetMachine.cpp less more
None //===-- TargetMachine.cpp - General Target Information ---------------------==//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file describes the general parts of a Target machine.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Target/TargetMachine.h"
14 #include "llvm/Analysis/TargetTransformInfo.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/GlobalAlias.h"
18 #include "llvm/IR/GlobalValue.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/IR/Mangler.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCTargetOptions.h"
27 #include "llvm/MC/SectionKind.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
31 using namespace llvm;
32
33 //---------------------------------------------------------------------------
34 // TargetMachine Class
35 //
36
37 TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
38 const Triple &TT, StringRef CPU, StringRef FS,
39 const TargetOptions &Options)
40 : TheTarget(T), DL(DataLayoutString), TargetTriple(TT), TargetCPU(CPU),
41 TargetFS(FS), AsmInfo(nullptr), MRI(nullptr), MII(nullptr), STI(nullptr),
42 RequireStructuredCFG(false), DefaultOptions(Options), Options(Options) {
43 }
44
45 TargetMachine::~TargetMachine() {
46 delete AsmInfo;
47 delete MRI;
48 delete MII;
49 delete STI;
50 }
51
52 bool TargetMachine::isPositionIndependent() const {
53 return getRelocationModel() == Reloc::PIC_;
54 }
55
56 /// \brief Reset the target options based on the function's attributes.
57 // FIXME: This function needs to go away for a number of reasons:
58 // a) global state on the TargetMachine is terrible in general,
59 // b) these target options should be passed only on the function
60 // and not on the TargetMachine (via TargetOptions) at all.
61 void TargetMachine::resetTargetOptions(const Function &F) const {
62 #define RESET_OPTION(X, Y) \
63 do { \
64 if (F.hasFnAttribute(Y)) \
65 Options.X = (F.getFnAttribute(Y).getValueAsString() == "true"); \
66 else \
67 Options.X = DefaultOptions.X; \
68 } while (0)
69
70 RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
71 RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
72 RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
73 RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
74 RESET_OPTION(NoTrappingFPMath, "no-trapping-math");
75
76 StringRef Denormal =
77 F.getFnAttribute("denormal-fp-math").getValueAsString();
78 if (Denormal == "ieee")
79 Options.FPDenormalMode = FPDenormal::IEEE;
80 else if (Denormal == "preserve-sign")
81 Options.FPDenormalMode = FPDenormal::PreserveSign;
82 else if (Denormal == "positive-zero")
83 Options.FPDenormalMode = FPDenormal::PositiveZero;
84 else
85 Options.FPDenormalMode = DefaultOptions.FPDenormalMode;
86 }
87
88 /// Returns the code generation relocation model. The choices are static, PIC,
89 /// and dynamic-no-pic.
90 Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
91
92 /// Returns the code model. The choices are small, kernel, medium, large, and
93 /// target default.
94 CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; }
95
96 /// Get the IR-specified TLS model for Var.
97 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
98 switch (GV->getThreadLocalMode()) {
99 case GlobalVariable::NotThreadLocal:
100 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
101 break;
102 case GlobalVariable::GeneralDynamicTLSModel:
103 return TLSModel::GeneralDynamic;
104 case GlobalVariable::LocalDynamicTLSModel:
105 return TLSModel::LocalDynamic;
106 case GlobalVariable::InitialExecTLSModel:
107 return TLSModel::InitialExec;
108 case GlobalVariable::LocalExecTLSModel:
109 return TLSModel::LocalExec;
110 }
111 llvm_unreachable("invalid TLS model");
112 }
113
114 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
115 const GlobalValue *GV) const {
116 Reloc::Model RM = getRelocationModel();
117 const Triple &TT = getTargetTriple();
118
119 // DLLImport explicitly marks the GV as external.
120 if (GV && GV->hasDLLImportStorageClass())
121 return false;
122
123 // Every other GV is local on COFF.
124 // Make an exception for windows OS in the triple: Some firmwares builds use
125 // *-win32-macho triples. This (accidentally?) produced windows relocations
126 // without GOT tables in older clang versions; Keep this behaviour.
127 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
128 return true;
129
130 if (GV && (GV->hasLocalLinkage() || !GV->hasDefaultVisibility()))
131 return true;
132
133 if (TT.isOSBinFormatMachO()) {
134 if (RM == Reloc::Static)
135 return true;
136 return GV && GV->isStrongDefinitionForLinker();
137 }
138
139 assert(TT.isOSBinFormatELF());
140 assert(RM != Reloc::DynamicNoPIC);
141
142 bool IsExecutable =
143 RM == Reloc::Static || M.getPIELevel() != PIELevel::Default;
144 if (IsExecutable) {
145 // If the symbol is defined, it cannot be preempted.
146 if (GV && !GV->isDeclarationForLinker())
147 return true;
148
149 bool IsTLS = GV && GV->isThreadLocal();
150 bool IsAccessViaCopyRelocs = Options.MCOptions.MCPIECopyRelocations && GV &&
151 isa(GV) &&
152 !GV->hasExternalWeakLinkage();
153 Triple::ArchType Arch = TT.getArch();
154 bool IsPPC =
155 Arch == Triple::ppc || Arch == Triple::ppc64 || Arch == Triple::ppc64le;
156 // Check if we can use copy relocations. PowerPC has no copy relocations.
157 if (!IsTLS && !IsPPC && (RM == Reloc::Static || IsAccessViaCopyRelocs))
158 return true;
159 }
160
161 // ELF supports preemption of other symbols.
162 return false;
163 }
164
165 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
166 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
167 Reloc::Model RM = getRelocationModel();
168 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
169 bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
170
171 TLSModel::Model Model;
172 if (IsSharedLibrary) {
173 if (IsLocal)
174 Model = TLSModel::LocalDynamic;
175 else
176 Model = TLSModel::GeneralDynamic;
177 } else {
178 if (IsLocal)
179 Model = TLSModel::LocalExec;
180 else
181 Model = TLSModel::InitialExec;
182 }
183
184 // If the user specified a more specific model, use that.
185 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
186 if (SelectedModel > Model)
187 return SelectedModel;
188
189 return Model;
190 }
191
192 /// Returns the optimization level: None, Less, Default, or Aggressive.
193 CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
194
195 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
196
197 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
198 return TargetIRAnalysis([](const Function &F) {
199 return TargetTransformInfo(F.getParent()->getDataLayout());
200 });
201 }
202
203 void TargetMachine::getNameWithPrefix(SmallVectorImpl &Name,
204 const GlobalValue *GV, Mangler &Mang,
205 bool MayAlwaysUsePrivate) const {
206 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
207 // Simple case: If GV is not private, it is not important to find out if
208 // private labels are legal in this case or not.
209 Mang.getNameWithPrefix(Name, GV, false);
210 return;
211 }
212 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
213 TLOF->getNameWithPrefix(Name, GV, *this);
214 }
215
216 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
217 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
218 SmallString<128> NameStr;
219 getNameWithPrefix(NameStr, GV, TLOF->getMangler());
220 return TLOF->getContext().getOrCreateSymbol(NameStr);
221 }
+0
-244
lib/Target/TargetMachineC.cpp less more
None //===-- TargetMachine.cpp -------------------------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
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/Target.h"
15 #include "llvm-c/TargetMachine.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/LegacyPassManager.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/CodeGenCWrappers.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/FormattedStream.h"
23 #include "llvm/Support/Host.h"
24 #include "llvm/Support/TargetRegistry.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include
29 #include
30 #include
31
32 using namespace llvm;
33
34 static TargetMachine *unwrap(LLVMTargetMachineRef P) {
35 return reinterpret_cast(P);
36 }
37 static Target *unwrap(LLVMTargetRef P) {
38 return reinterpret_cast(P);
39 }
40 static LLVMTargetMachineRef wrap(const TargetMachine *P) {
41 return reinterpret_cast(const_cast(P));
42 }
43 static LLVMTargetRef wrap(const Target * P) {
44 return reinterpret_cast(const_cast(P));
45 }
46
47 LLVMTargetRef LLVMGetFirstTarget() {
48 if (TargetRegistry::targets().begin() == TargetRegistry::targets().end()) {
49 return nullptr;
50 }
51
52 const Target *target = &*TargetRegistry::targets().begin();
53 return wrap(target);
54 }
55 LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T) {
56 return wrap(unwrap(T)->getNext());
57 }
58
59 LLVMTargetRef LLVMGetTargetFromName(const char *Name) {
60 StringRef NameRef = Name;
61 auto I = find_if(TargetRegistry::targets(),
62 [&](const Target &T) { return T.getName() == NameRef; });
63 return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
64 }
65
66 LLVMBool LLVMGetTargetFromTriple(const char* TripleStr, LLVMTargetRef *T,
67 char **ErrorMessage) {
68 std::string Error;
69
70 *T = wrap(TargetRegistry::lookupTarget(TripleStr, Error));
71
72 if (!*T) {
73 if (ErrorMessage)
74 *ErrorMessage = strdup(Error.c_str());
75
76 return 1;
77 }
78
79 return 0;
80 }
81
82 const char * LLVMGetTargetName(LLVMTargetRef T) {
83 return unwrap(T)->getName();
84 }
85
86 const char * LLVMGetTargetDescription(LLVMTargetRef T) {
87 return unwrap(T)->getShortDescription();
88 }
89
90 LLVMBool LLVMTargetHasJIT(LLVMTargetRef T) {
91 return unwrap(T)->hasJIT();
92 }
93
94 LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T) {
95 return unwrap(T)->hasTargetMachine();
96 }
97
98 LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T) {
99 return unwrap(T)->hasMCAsmBackend();
100 }
101
102 LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T,
103 const char *Triple, const char *CPU, const char *Features,
104 LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc,
105 LLVMCodeModel CodeModel) {
106 Optional RM;
107 switch (Reloc){
108 case LLVMRelocStatic:
109 RM = Reloc::Static;
110 break;
111 case LLVMRelocPIC:
112 RM = Reloc::PIC_;
113 break;
114 case LLVMRelocDynamicNoPic:
115 RM = Reloc::DynamicNoPIC;
116 break;
117 default:
118 break;
119 }
120
121 bool JIT;
122 Optional CM = unwrap(CodeModel, JIT);
123
124 CodeGenOpt::Level OL;
125 switch (Level) {
126 case LLVMCodeGenLevelNone:
127 OL = CodeGenOpt::None;
128 break;
129 case LLVMCodeGenLevelLess:
130 OL = CodeGenOpt::Less;
131 break;
132 case LLVMCodeGenLevelAggressive:
133 OL = CodeGenOpt::Aggressive;
134 break;
135 default:
136 OL = CodeGenOpt::Default;
137 break;
138 }
139
140 TargetOptions opt;
141 return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt, RM, CM,
142 OL, JIT));
143 }
144
145 void LLVMDisposeTargetMachine(LLVMTargetMachineRef T) { delete unwrap(T); }
146
147 LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T) {
148 const Target* target = &(unwrap(T)->getTarget());
149 return wrap(target);
150 }
151
152 char* LLVMGetTargetMachineTriple(LLVMTargetMachineRef T) {
153 std::string StringRep = unwrap(T)->getTargetTriple().str();
154 return strdup(StringRep.c_str());
155 }
156
157 char* LLVMGetTargetMachineCPU(LLVMTargetMachineRef T) {
158 std::string StringRep = unwrap(T)->getTargetCPU();
159 return strdup(StringRep.c_str());
160 }
161
162 char* LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T) {
163 std::string StringRep = unwrap(T)->getTargetFeatureString();
164 return strdup(StringRep.c_str());
165 }
166
167 void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T,
168 LLVMBool VerboseAsm) {
169 unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
170 }
171
172 LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T) {
173 return wrap(new DataLayout(unwrap(T)->createDataLayout()));
174 }
175
176 static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M,
177 raw_pwrite_stream &OS,
178 LLVMCodeGenFileType codegen,
179 char **ErrorMessage) {
180 TargetMachine* TM = unwrap(T);
181 Module* Mod = unwrap(M);
182
183 legacy::PassManager pass;
184
185 std::string error;
186
187 Mod->setDataLayout(TM->createDataLayout());
188
189 TargetMachine::CodeGenFileType ft;
190 switch (codegen) {
191 case LLVMAssemblyFile:
192 ft = TargetMachine::CGFT_AssemblyFile;
193 break;
194 default:
195 ft = TargetMachine::CGFT_ObjectFile;
196 break;
197 }
198 if (TM->addPassesToEmitFile(pass, OS, ft)) {
199 error = "TargetMachine can't emit a file of this type";
200 *ErrorMessage = strdup(error.c_str());
201 return true;
202 }
203
204 pass.run(*Mod);
205
206 OS.flush();
207 return false;
208 }
209
210 LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
211 char* Filename, LLVMCodeGenFileType codegen, char** ErrorMessage) {
212 std::error_code EC;
213 raw_fd_ostream dest(Filename, EC, sys::fs::F_None);
214 if (EC) {
215 *ErrorMessage = strdup(EC.message().c_str());
216 return true;
217 }
218 bool Result = LLVMTargetMachineEmit(T, M, dest, codegen, ErrorMessage);
219 dest.flush();
220 return Result;
221 }
222
223 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T,
224 LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
225 LLVMMemoryBufferRef *OutMemBuf) {
226 SmallString<0> CodeString;
227 raw_svector_ostream OStream(CodeString);
228 bool Result = LLVMTargetMachineEmit(T, M, OStream, codegen, ErrorMessage);
229
230 StringRef Data = OStream.str();
231 *OutMemBuf =
232 LLVMCreateMemoryBufferWithMemoryRangeCopy(Data.data(), Data.size(), "");
233 return Result;
234 }
235
236 char *LLVMGetDefaultTargetTriple(void) {
237 return strdup(sys::getDefaultTargetTriple().c_str());
238 }
239
240 void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM) {
241 unwrap(PM)->add(
242 createTargetTransformInfoWrapperPass(unwrap(T)->getTargetIRAnalysis()));
243 }
6868 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
6969 const TargetOptions &Options, Optional RM,
7070 Optional CM, CodeGenOpt::Level OL, bool JIT)
71 : LLVMTargetMachine(T,
72 TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
73 : "e-m:e-p:32:32-i64:64-n32:64-S128",
74 TT, CPU, FS, Options, getEffectiveRelocModel(RM),
75 CM ? *CM : CodeModel::Large, OL),
71 : TargetMachine(T, TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
72 : "e-m:e-p:32:32-i64:64-n32:64-S128",
73 TT, CPU, FS, Options, getEffectiveRelocModel(RM),
74 CM ? *CM : CodeModel::Large, OL),
7675 TLOF(TT.isOSBinFormatELF() ?
7776 static_cast(
7877 new WebAssemblyTargetObjectFileELF()) :
2020
2121 namespace llvm {
2222
23 class WebAssemblyTargetMachine final : public LLVMTargetMachine {
23 class WebAssemblyTargetMachine final : public TargetMachine {
2424 std::unique_ptr TLOF;
2525 mutable StringMap> SubtargetMap;
2626
199199 Optional RM,
200200 Optional CM,
201201 CodeGenOpt::Level OL, bool JIT)
202 : LLVMTargetMachine(
202 : TargetMachine(
203203 T, computeDataLayout(TT), TT, CPU, FS, Options,
204204 getEffectiveRelocModel(TT, RM),
205205 getEffectiveCodeModel(CM, JIT, TT.getArch() == Triple::x86_64), OL),
2727 class X86Subtarget;
2828 class X86RegisterBankInfo;
2929
30 class X86TargetMachine final : public LLVMTargetMachine {
30 class X86TargetMachine final : public TargetMachine {
3131 std::unique_ptr TLOF;
3232 mutable StringMap> SubtargetMap;
3333
4747 Optional RM,
4848 Optional CM,
4949 CodeGenOpt::Level OL, bool JIT)
50 : LLVMTargetMachine(
50 : TargetMachine(
5151 T, "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i64:32-f64:32-a:0:32-n32",
5252 TT, CPU, FS, Options, getEffectiveRelocModel(RM),
5353 getEffectiveCodeModel(CM), OL),
2323
2424 namespace llvm {
2525
26 class XCoreTargetMachine : public LLVMTargetMachine {
26 class XCoreTargetMachine : public TargetMachine {
2727 std::unique_ptr TLOF;
2828 XCoreSubtarget Subtarget;
2929
510510 }
511511
512512 const char *argv0 = argv[0];
513 LLVMTargetMachine &LLVMTM = static_cast(*Target);
514 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
513 MachineModuleInfo *MMI = new MachineModuleInfo(Target.get());
515514
516515 // Construct a custom pass pipeline that starts after instruction
517516 // selection.
520519 errs() << argv0 << ": run-pass is for .mir file only.\n";
521520 return 1;
522521 }
523 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
522 TargetPassConfig &TPC = *Target->createPassConfig(PM);
524523 if (TPC.hasLimitedCodeGenPipeline()) {
525524 errs() << argv0 << ": run-pass cannot be used with "
526525 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
592592 }
593593
594594 if (TM) {
595 // FIXME: We should dyn_cast this when supported.
596 auto <M = static_cast(*TM);
597 Pass *TPC = LTM.createPassConfig(Passes);
598 Passes.add(TPC);
595 Pass *TPC = TM->createPassConfig(Passes);
596 if (TPC)
597 Passes.add(TPC);
599598 }
600599
601600 // Create a new optimization pass for each one specified on the command line
6161 TargetInstrInfo TII;
6262 };
6363
64 class BogusTargetMachine : public LLVMTargetMachine {
64 class BogusTargetMachine : public TargetMachine {
6565 public:
6666 BogusTargetMachine()
67 : LLVMTargetMachine(Target(), "", Triple(""), "", "", TargetOptions(),
68 Reloc::Static, CodeModel::Small, CodeGenOpt::Default),
67 : TargetMachine(Target(), "", Triple(""), "", "", TargetOptions(),
68 Reloc::Static, CodeModel::Small, CodeGenOpt::Default),
6969 ST(*this) {}
7070 ~BogusTargetMachine() override {}
7171