LLVM 22.0.0git
CodeGenTargetMachineImpl.cpp
Go to the documentation of this file.
1//===-- CodeGenTargetMachineImpl.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/// \file This file implements the CodeGenTargetMachineImpl class.
10///
11//===----------------------------------------------------------------------===//
12
19#include "llvm/CodeGen/Passes.h"
23#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCInstrInfo.h"
30#include "llvm/MC/MCStreamer.h"
38using namespace llvm;
39
40static cl::opt<bool>
41 EnableTrapUnreachable("trap-unreachable", cl::Hidden,
42 cl::desc("Enable generating trap for unreachable"));
43
45 "no-trap-after-noreturn", cl::Hidden,
46 cl::desc("Do not emit a trap instruction for 'unreachable' IR instructions "
47 "after noreturn calls, even if --trap-unreachable is set."));
48
50 MRI.reset(TheTarget.createMCRegInfo(getTargetTriple()));
51 assert(MRI && "Unable to create reg info");
52 MII.reset(TheTarget.createMCInstrInfo());
53 assert(MII && "Unable to create instruction info");
54 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
55 // to some backends having subtarget feature dependent module level
56 // code generation. This is similar to the hack in the AsmPrinter for
57 // module level assembly etc.
58 STI.reset(TheTarget.createMCSubtargetInfo(getTargetTriple(), getTargetCPU(),
60 assert(STI && "Unable to create subtarget info");
61
62 MCAsmInfo *TmpAsmInfo =
63 TheTarget.createMCAsmInfo(*MRI, getTargetTriple(), Options.MCOptions);
64 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
65 // and if the old one gets included then MCAsmInfo will be NULL and
66 // we'll crash later.
67 // Provide the user with a useful error message about what's wrong.
68 assert(TmpAsmInfo && "MCAsmInfo not initialized. "
69 "Make sure you include the correct TargetSelect.h"
70 "and that InitializeAllTargetMCs() is being invoked!");
71
72 if (Options.BinutilsVersion.first > 0)
73 TmpAsmInfo->setBinutilsVersion(Options.BinutilsVersion);
74
75 if (Options.DisableIntegratedAS) {
76 TmpAsmInfo->setUseIntegratedAssembler(false);
77 // If there is explict option disable integratedAS, we can't use it for
78 // inlineasm either.
79 TmpAsmInfo->setParseInlineAsmUsingAsmParser(false);
80 }
81
82 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
83
84 TmpAsmInfo->setFullRegisterNames(Options.MCOptions.PPCUseFullRegisterNames);
85
86 assert(TmpAsmInfo->getExceptionHandlingType() ==
87 getTargetTriple().getDefaultExceptionHandling() &&
88 "MCAsmInfo and Triple disagree on default exception handling type");
89
90 if (Options.ExceptionModel != ExceptionHandling::None)
91 TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
92
93 AsmInfo.reset(TmpAsmInfo);
94}
95
97 const Target &T, StringRef DataLayoutString, const Triple &TT,
100 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
101 this->RM = RM;
102 this->CMModel = CM;
103 this->OptLevel = OL;
104
106 this->Options.TrapUnreachable = true;
108 this->Options.NoTrapAfterNoreturn = true;
109}
110
113 return TargetTransformInfo(std::make_unique<BasicTTIImpl>(this, F));
114}
115
116/// addPassesToX helper drives creation and initialization of TargetPassConfig.
117static TargetPassConfig *
119 bool DisableVerify,
121 // Targets may override createPassConfig to provide a target-specific
122 // subclass.
123 TargetPassConfig *PassConfig = TM.createPassConfig(PM);
124 // Set PassConfig options provided by TargetMachine.
125 PassConfig->setDisableVerify(DisableVerify);
126 PM.add(PassConfig);
127 PM.add(&MMIWP);
128
129 const TargetOptions &Options = TM.Options;
131 PM.add(new TargetLibraryInfoWrapperPass(TLII));
133 TM.getTargetTriple(), Options.ExceptionModel, Options.FloatABIType,
134 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
135
136 invokeGlobalTargetPassConfigCallbacks(TM, PM, PassConfig);
137
138 if (PassConfig->addISelPasses())
139 return nullptr;
140 PassConfig->addMachinePasses();
141 PassConfig->setInitialized();
142 return PassConfig;
143}
144
147 raw_pwrite_stream *DwoOut,
148 CodeGenFileType FileType,
149 MCContext &Context) {
150 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
151 createMCStreamer(Out, DwoOut, FileType, Context);
152 if (!MCStreamerOrErr) {
153 Context.reportError(SMLoc(), toString(MCStreamerOrErr.takeError()));
154 return true;
155 }
156
157 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
159 getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
160 if (!Printer)
161 return true;
162
163 PM.add(Printer);
164 return false;
165}
166
169 raw_pwrite_stream *DwoOut,
170 CodeGenFileType FileType,
171 MCContext &Context) {
173 const MCAsmInfo &MAI = *getMCAsmInfo();
175 const MCInstrInfo &MII = *getMCInstrInfo();
176
177 std::unique_ptr<MCStreamer> AsmStreamer;
178
179 switch (FileType) {
181 std::unique_ptr<MCInstPrinter> InstPrinter(getTarget().createMCInstPrinter(
183 Options.MCOptions.OutputAsmVariant.value_or(MAI.getAssemblerDialect()),
184 MAI, MII, MRI));
185 for (StringRef Opt : Options.MCOptions.InstPrinterOptions)
186 if (!InstPrinter->applyTargetSpecificCLOption(Opt))
187 return createStringError("invalid InstPrinter option '" + Opt + "'");
188
189 // Create a code emitter if asked to show the encoding.
190 std::unique_ptr<MCCodeEmitter> MCE;
191 if (Options.MCOptions.ShowMCEncoding)
192 MCE.reset(getTarget().createMCCodeEmitter(MII, Context));
193
194 std::unique_ptr<MCAsmBackend> MAB(
195 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
196 auto FOut = std::make_unique<formatted_raw_ostream>(Out);
198 Context, std::move(FOut), std::move(InstPrinter), std::move(MCE),
199 std::move(MAB));
200 AsmStreamer.reset(S);
201 break;
202 }
204 // Create the code emitter for the target if it exists. If not, .o file
205 // emission fails.
207 if (!MCE)
208 return make_error<StringError>("createMCCodeEmitter failed",
210 MCAsmBackend *MAB =
212 if (!MAB)
213 return make_error<StringError>("createMCAsmBackend failed",
215
217 AsmStreamer.reset(getTarget().createMCObjectStreamer(
218 T, Context, std::unique_ptr<MCAsmBackend>(MAB),
219 DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
220 : MAB->createObjectWriter(Out),
221 std::unique_ptr<MCCodeEmitter>(MCE), STI));
222 break;
223 }
225 // The Null output is intended for use for performance analysis and testing,
226 // not real users.
227 AsmStreamer.reset(getTarget().createNullStreamer(Context));
228 break;
229 }
230
231 return std::move(AsmStreamer);
232}
233
236 CodeGenFileType FileType, bool DisableVerify,
238 // Add common CodeGen passes.
239 if (!MMIWP)
240 MMIWP = new MachineModuleInfoWrapperPass(this);
241 TargetPassConfig *PassConfig =
242 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
243 if (!PassConfig)
244 return true;
245
247 if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext()))
248 return true;
249 } else {
250 // MIR printing is redundant with -filetype=null.
251 if (FileType != CodeGenFileType::Null)
252 PM.add(createPrintMIRPass(Out));
253 }
254
256 return false;
257}
258
259/// addPassesToEmitMC - Add passes to the specified pass manager to get
260/// machine code emitted with the MCJIT. This method returns true if machine
261/// code is not supported. It fills the MCContext Ctx pointer which can be
262/// used to build custom MCStreamer.
263///
265 MCContext *&Ctx,
267 bool DisableVerify) {
268 // Add common CodeGen passes.
270 TargetPassConfig *PassConfig =
271 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
272 if (!PassConfig)
273 return true;
275 "Cannot emit MC with limited codegen pipeline");
276
277 Ctx = &MMIWP->getMMI().getContext();
278 // libunwind is unable to load compact unwind dynamically, so we must generate
279 // DWARF unwind info for the JIT.
280 Options.MCOptions.EmitDwarfUnwind = EmitDwarfUnwindType::Always;
281
282 // Create the code emitter for the target if it exists. If not, .o file
283 // emission fails.
286 std::unique_ptr<MCCodeEmitter> MCE(
287 getTarget().createMCCodeEmitter(*getMCInstrInfo(), *Ctx));
288 if (!MCE)
289 return true;
290 MCAsmBackend *MAB =
292 if (!MAB)
293 return true;
294
295 const Triple &T = getTargetTriple();
296 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
297 T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
298 std::move(MCE), STI));
299
300 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
302 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
303 if (!Printer)
304 return true;
305
306 PM.add(Printer);
308
309 return false; // success!
310}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
static TargetPassConfig * addPassesToGenerateCode(CodeGenTargetMachineImpl &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."))
dxil pretty DXIL Metadata Pretty Printer
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define T
if(PassOpts->AAPipeline)
Target-Independent Code Generator Pass Configuration Options pass.
static MCInstPrinter * createMCInstPrinter(const Triple &, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI)
implements a set of functionality in the TargetMachine class for targets that make use of the indepen...
Expected< std::unique_ptr< MCStreamer > > createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) override
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.
CodeGenTargetMachineImpl(const Target &T, StringRef DataLayoutString, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
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.
bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Context) override
Adds an AsmPrinter pass to the pipeline that prints assembly or machine code from the MI representati...
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Generic interface to target specific assembler backends.
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:64
unsigned getAssemblerDialect() const
Definition MCAsmInfo.h:560
virtual void setUseIntegratedAssembler(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition MCAsmInfo.h:699
virtual void setPreserveAsmComments(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition MCAsmInfo.h:712
virtual void setParseInlineAsmUsingAsmParser(bool Value)
Set whether target want to use AsmParser to parse inlineasm.
Definition MCAsmInfo.h:704
void setFullRegisterNames(bool V)
Definition MCAsmInfo.h:581
void setBinutilsVersion(std::pair< int, int > Value)
Definition MCAsmInfo.h:682
void setExceptionsType(ExceptionHandling EH)
Definition MCAsmInfo.h:636
ExceptionHandling getExceptionHandlingType() const
Definition MCAsmInfo.h:633
MCCodeEmitter - Generic instruction encoding interface.
Context object for machine code objects.
Definition MCContext.h:83
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Streaming machine code generation interface.
Definition MCStreamer.h:220
virtual void reset()
State management.
Generic base class for all target subtargets.
const MCContext & getContext() const
Represents a location in source code.
Definition SMLoc.h:22
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Implementation of the target library information.
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.
const MCRegisterInfo * getMCRegisterInfo() const
TargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TargetTriple, StringRef CPU, StringRef FS, const TargetOptions &Options)
std::unique_ptr< const MCRegisterInfo > MRI
CodeGenOptLevel OptLevel
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
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.
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.
MCAsmBackend * createMCAsmBackend(const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options) const
createMCAsmBackend - Create a target specific assembly parser.
LLVM_ABI MCStreamer * createAsmStreamer(MCContext &Ctx, std::unique_ptr< formatted_raw_ostream > OS, std::unique_ptr< 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.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
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.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI MachineFunctionPass * createPrintMIRPass(raw_ostream &OS)
MIRPrinting pass - this pass prints out the LLVM IR into the given stream using the MIR serialization...
LLVM_ABI 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.
Definition CodeGen.h:54
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
LLVM_ABI 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:111
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI void invokeGlobalTargetPassConfigCallbacks(TargetMachine &TM, PassManagerBase &PM, TargetPassConfig *PassConfig)
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.