LLVM 20.0.0git
LLVMTargetMachine.cpp
Go to the documentation of this file.
1//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
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 LLVMTargetMachine class.
10//
11//===----------------------------------------------------------------------===//
12
17#include "llvm/CodeGen/Passes.h"
21#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCInstrInfo.h"
27#include "llvm/MC/MCStreamer.h"
34using namespace llvm;
35
36static cl::opt<bool>
37 EnableTrapUnreachable("trap-unreachable", cl::Hidden,
38 cl::desc("Enable generating trap for unreachable"));
39
41 "no-trap-after-noreturn", cl::Hidden,
42 cl::desc("Do not emit a trap instruction for 'unreachable' IR instructions "
43 "after noreturn calls, even if --trap-unreachable is set."));
44
47 assert(MRI && "Unable to create reg info");
49 assert(MII && "Unable to create instruction info");
50 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
51 // to some backends having subtarget feature dependent module level
52 // code generation. This is similar to the hack in the AsmPrinter for
53 // module level assembly etc.
56 assert(STI && "Unable to create subtarget info");
57
60 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
61 // and if the old one gets included then MCAsmInfo will be NULL and
62 // we'll crash later.
63 // Provide the user with a useful error message about what's wrong.
64 assert(TmpAsmInfo && "MCAsmInfo not initialized. "
65 "Make sure you include the correct TargetSelect.h"
66 "and that InitializeAllTargetMCs() is being invoked!");
67
68 if (Options.BinutilsVersion.first > 0)
70
72 TmpAsmInfo->setUseIntegratedAssembler(false);
73 // If there is explict option disable integratedAS, we can't use it for
74 // inlineasm either.
75 TmpAsmInfo->setParseInlineAsmUsingAsmParser(false);
76 }
77
79
81
84
85 AsmInfo.reset(TmpAsmInfo);
86}
87
89 StringRef DataLayoutString,
90 const Triple &TT, StringRef CPU,
94 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
95 this->RM = RM;
96 this->CMModel = CM;
97 this->OptLevel = OL;
98
100 this->Options.TrapUnreachable = true;
102 this->Options.NoTrapAfterNoreturn = true;
103}
104
107 return TargetTransformInfo(BasicTTIImpl(this, F));
108}
109
110/// addPassesToX helper drives creation and initialization of TargetPassConfig.
111static TargetPassConfig *
113 bool DisableVerify,
115 // Targets may override createPassConfig to provide a target-specific
116 // subclass.
117 TargetPassConfig *PassConfig = TM.createPassConfig(PM);
118 // Set PassConfig options provided by TargetMachine.
119 PassConfig->setDisableVerify(DisableVerify);
120 PM.add(PassConfig);
121 PM.add(&MMIWP);
122
123 if (PassConfig->addISelPasses())
124 return nullptr;
125 PassConfig->addMachinePasses();
126 PassConfig->setInitialized();
127 return PassConfig;
128}
129
132 raw_pwrite_stream *DwoOut,
133 CodeGenFileType FileType,
134 MCContext &Context) {
135 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
136 createMCStreamer(Out, DwoOut, FileType, Context);
137 if (auto Err = MCStreamerOrErr.takeError())
138 return true;
139
140 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
142 getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
143 if (!Printer)
144 return true;
145
146 PM.add(Printer);
147 return false;
148}
149
152 MCContext &Context) {
154 const MCAsmInfo &MAI = *getMCAsmInfo();
156 const MCInstrInfo &MII = *getMCInstrInfo();
157
158 std::unique_ptr<MCStreamer> AsmStreamer;
159
160 switch (FileType) {
164
165 // Create a code emitter if asked to show the encoding.
166 std::unique_ptr<MCCodeEmitter> MCE;
168 MCE.reset(getTarget().createMCCodeEmitter(MII, Context));
169
170 std::unique_ptr<MCAsmBackend> MAB(
171 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
172 auto FOut = std::make_unique<formatted_raw_ostream>(Out);
174 Context, std::move(FOut), InstPrinter, std::move(MCE), std::move(MAB));
175 AsmStreamer.reset(S);
176 break;
177 }
179 // Create the code emitter for the target if it exists. If not, .o file
180 // emission fails.
182 if (!MCE)
183 return make_error<StringError>("createMCCodeEmitter failed",
185 MCAsmBackend *MAB =
187 if (!MAB)
188 return make_error<StringError>("createMCAsmBackend failed",
190
191 Triple T(getTargetTriple().str());
192 AsmStreamer.reset(getTarget().createMCObjectStreamer(
193 T, Context, std::unique_ptr<MCAsmBackend>(MAB),
194 DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
195 : MAB->createObjectWriter(Out),
196 std::unique_ptr<MCCodeEmitter>(MCE), STI));
197 break;
198 }
200 // The Null output is intended for use for performance analysis and testing,
201 // not real users.
202 AsmStreamer.reset(getTarget().createNullStreamer(Context));
203 break;
204 }
205
206 return std::move(AsmStreamer);
207}
208
211 CodeGenFileType FileType, bool DisableVerify,
213 // Add common CodeGen passes.
214 if (!MMIWP)
215 MMIWP = new MachineModuleInfoWrapperPass(this);
216 TargetPassConfig *PassConfig =
217 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
218 if (!PassConfig)
219 return true;
220
222 if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext()))
223 return true;
224 } else {
225 // MIR printing is redundant with -filetype=null.
226 if (FileType != CodeGenFileType::Null)
227 PM.add(createPrintMIRPass(Out));
228 }
229
231 return false;
232}
233
234/// addPassesToEmitMC - Add passes to the specified pass manager to get
235/// machine code emitted with the MCJIT. This method returns true if machine
236/// code is not supported. It fills the MCContext Ctx pointer which can be
237/// used to build custom MCStreamer.
238///
241 bool DisableVerify) {
242 // Add common CodeGen passes.
244 TargetPassConfig *PassConfig =
245 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
246 if (!PassConfig)
247 return true;
249 "Cannot emit MC with limited codegen pipeline");
250
251 Ctx = &MMIWP->getMMI().getContext();
252 // libunwind is unable to load compact unwind dynamically, so we must generate
253 // DWARF unwind info for the JIT.
255
256 // Create the code emitter for the target if it exists. If not, .o file
257 // emission fails.
260 std::unique_ptr<MCCodeEmitter> MCE(
261 getTarget().createMCCodeEmitter(*getMCInstrInfo(), *Ctx));
262 MCAsmBackend *MAB =
264 if (!MCE || !MAB)
265 return true;
266
267 const Triple &T = getTargetTriple();
268 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
269 T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
270 std::move(MCE), STI));
271
272 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
274 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
275 if (!Printer)
276 return true;
277
278 PM.add(Printer);
280
281 return false; // success!
282}
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
dxil pretty DXIL Metadata Pretty Printer
static TargetPassConfig * addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM, bool DisableVerify, MachineModuleInfoWrapperPass &MMIWP)
addPassesToX helper drives creation and initialization of TargetPassConfig.
static cl::opt< bool > EnableTrapUnreachable("trap-unreachable", cl::Hidden, cl::desc("Enable generating trap for unreachable"))
static cl::opt< bool > EnableNoTrapAfterNoreturn("no-trap-after-noreturn", cl::Hidden, cl::desc("Do not emit a trap instruction for 'unreachable' IR instructions " "after noreturn calls, even if --trap-unreachable is set."))
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Target-Independent Code Generator Pass Configuration Options pass.
Concrete BasicTTIImpl that can be used if no further customization is needed.
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
This class describes a target machine that is implemented with the LLVM target-independent code gener...
bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Context)
Adds an AsmPrinter pass to the pipeline that prints assembly or machine code from the MI representati...
bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, bool DisableVerify=true, MachineModuleInfoWrapperPass *MMIWP=nullptr) override
Add passes to the specified pass manager to get the specified file emitted.
bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, raw_pwrite_stream &Out, bool DisableVerify=true) override
Add passes to the specified pass manager to get machine code emitted with the MCJIT.
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
LLVMTargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
Expected< std::unique_ptr< MCStreamer > > createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:42
std::unique_ptr< MCObjectWriter > createObjectWriter(raw_pwrite_stream &OS) const
Create a new MCObjectWriter instance for use by the assembler backend to emit the final object file.
std::unique_ptr< MCObjectWriter > createDwoObjectWriter(raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS) const
Create an MCObjectWriter that writes two object files: a .o file which is linked into the final progr...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:646
virtual void setUseIntegratedAssembler(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:814
virtual void setPreserveAsmComments(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:827
virtual void setParseInlineAsmUsingAsmParser(bool Value)
Set whether target want to use AsmParser to parse inlineasm.
Definition: MCAsmInfo.h:819
void setFullRegisterNames(bool V)
Definition: MCAsmInfo.h:674
void setBinutilsVersion(std::pair< int, int > Value)
Definition: MCAsmInfo.h:797
void setExceptionsType(ExceptionHandling EH)
Definition: MCAsmInfo.h:743
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:21
Context object for machine code objects.
Definition: MCContext.h:83
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:45
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:26
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Streaming machine code generation interface.
Definition: MCStreamer.h:213
virtual void reset()
State management.
Definition: MCStreamer.cpp:101
Generic base class for all target subtargets.
bool PreserveAsmComments
Preserve Comments in Assembly.
EmitDwarfUnwindType EmitDwarfUnwind
const MCContext & getContext() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
std::unique_ptr< const MCAsmInfo > AsmInfo
Contains target specific asm information.
CodeModel::Model CMModel
const Triple & getTargetTriple() const
const MCSubtargetInfo * getMCSubtargetInfo() const
std::unique_ptr< const MCInstrInfo > MII
StringRef getTargetFeatureString() const
StringRef getTargetCPU() const
const MCInstrInfo * getMCInstrInfo() const
std::unique_ptr< const MCSubtargetInfo > STI
TargetOptions Options
const Target & getTarget() const
const Target & TheTarget
The Target that this machine was created for.
Definition: TargetMachine.h:84
const MCRegisterInfo * getMCRegisterInfo() const
std::unique_ptr< const MCRegisterInfo > MRI
CodeGenOptLevel OptLevel
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
MCTargetOptions MCOptions
Machine level options.
std::pair< int, int > BinutilsVersion
If greater than 0, override the default value of MCAsmInfo::BinutilsVersion.
unsigned NoTrapAfterNoreturn
Do not emit a trap instruction for 'unreachable' IR instructions behind noreturn calls,...
unsigned TrapUnreachable
Emit target-specific trap instruction for 'unreachable' IR instructions.
unsigned DisableIntegratedAS
Disable the integrated assembler.
ExceptionHandling ExceptionModel
What exception model to use.
Target-Independent Code Generator Pass Configuration Options.
virtual void addMachinePasses()
Add the complete, standard set of LLVM CodeGen passes.
void setDisableVerify(bool Disable)
static bool willCompleteCodeGenPipeline()
Returns true if none of the -stop-before and -stop-after options is set.
bool addISelPasses()
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
MCCodeEmitter * createMCCodeEmitter(const MCInstrInfo &II, MCContext &Ctx) const
createMCCodeEmitter - Create a target specific code emitter.
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
MCAsmBackend * createMCAsmBackend(const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options) const
createMCAsmBackend - Create a target specific assembly parser.
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple, const MCTargetOptions &Options) const
createMCAsmInfo - Create a MCAsmInfo implementation for the specified target triple.
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
MCStreamer * createAsmStreamer(MCContext &Ctx, std::unique_ptr< formatted_raw_ostream > OS, MCInstPrinter *IP, std::unique_ptr< MCCodeEmitter > CE, std::unique_ptr< MCAsmBackend > TAB) const
AsmPrinter * createAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > &&Streamer) const
createAsmPrinter - Create a target specific assembly printer pass.
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
virtual void add(Pass *P)=0
Add a pass to the queue of passes to run.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:434
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineFunctionPass * createPrintMIRPass(raw_ostream &OS)
MIRPrinting pass - this pass prints out the LLVM IR into the given stream using the MIR serialization...
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
@ None
No exception support.
MCStreamer * createNullStreamer(MCContext &Ctx)
Create a dummy machine code streamer, which does nothing.
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
FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.