LLVM 24.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.MCOptions.DisableIntegratedAS) {
73 TmpAsmInfo->setUseIntegratedAssembler(false);
74 // If there is explict option disable integratedAS, we can't use it for
75 // inlineasm either.
76 TmpAsmInfo->setParseInlineAsmUsingAsmParser(false);
77 }
78
79 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
80
81 TmpAsmInfo->setFullRegisterNames(Options.MCOptions.PPCUseFullRegisterNames);
82
83 AsmInfo.reset(TmpAsmInfo);
84}
85
87 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
90 : TargetMachine(T, TT.computeDataLayout(Options.MCOptions.getABIName()), TT,
91 CPU, FS, Options) {
92 this->RM = RM;
93 this->CMModel = CM;
94 this->OptLevel = OL;
95
97 this->Options.TrapUnreachable = true;
99 this->Options.NoTrapAfterNoreturn = true;
100}
101
104 return TargetTransformInfo(std::make_unique<BasicTTIImpl>(this, F));
105}
106
107/// addPassesToX helper drives creation and initialization of TargetPassConfig.
108static TargetPassConfig *
110 bool DisableVerify,
112 // Targets may override createPassConfig to provide a target-specific
113 // subclass.
114 TargetPassConfig *PassConfig = TM.createPassConfig(PM);
115 // Set PassConfig options provided by TargetMachine.
116 PassConfig->setDisableVerify(DisableVerify);
117 PM.add(PassConfig);
118 PM.add(&MMIWP);
119
120 const TargetOptions &Options = TM.Options;
122 PM.add(new TargetLibraryInfoWrapperPass(TLII));
123 PM.add(
124 new RuntimeLibraryInfoWrapper(Options.MCOptions.ABIName, Options.VecLib));
125
126 invokeGlobalTargetPassConfigCallbacks(TM, PM, PassConfig);
127
128 if (PassConfig->addISelPasses())
129 return nullptr;
130 PassConfig->addMachinePasses();
131 PassConfig->setInitialized();
132 return PassConfig;
133}
134
137 raw_pwrite_stream *DwoOut,
138 CodeGenFileType FileType,
139 MCContext &Context) {
140 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
141 createMCStreamer(Out, DwoOut, FileType, Context);
142 if (!MCStreamerOrErr) {
143 Context.reportError(SMLoc(), toString(MCStreamerOrErr.takeError()));
144 return true;
145 }
146
147 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
149 getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
150 if (!Printer)
151 return true;
152
153 PM.add(Printer);
154 return false;
155}
156
159 raw_pwrite_stream *DwoOut,
160 CodeGenFileType FileType,
161 MCContext &Context) {
163 const MCAsmInfo &MAI = getMCAsmInfo();
165 const MCInstrInfo &MII = *getMCInstrInfo();
166
167 std::unique_ptr<MCStreamer> AsmStreamer;
168
169 switch (FileType) {
171 std::unique_ptr<MCInstPrinter> InstPrinter(getTarget().createMCInstPrinter(
173 for (StringRef Opt : Options.MCOptions.InstPrinterOptions)
174 if (!InstPrinter->applyTargetSpecificCLOption(Opt))
175 return createStringError("invalid InstPrinter option '" + Opt + "'");
176
177 // Create a code emitter if asked to show the encoding.
178 std::unique_ptr<MCCodeEmitter> MCE;
179 if (Options.MCOptions.ShowMCEncoding)
180 MCE.reset(getTarget().createMCCodeEmitter(MII, Context));
181
182 std::unique_ptr<MCAsmBackend> MAB(
183 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
184 auto FOut = std::make_unique<formatted_raw_ostream>(Out);
186 Context, std::move(FOut), std::move(InstPrinter), std::move(MCE),
187 std::move(MAB));
188 AsmStreamer.reset(S);
189 break;
190 }
192 // Create the code emitter for the target if it exists. If not, .o file
193 // emission fails.
195 if (!MCE)
196 return make_error<StringError>("createMCCodeEmitter failed",
198 MCAsmBackend *MAB =
200 if (!MAB)
201 return make_error<StringError>("createMCAsmBackend failed",
203
205 AsmStreamer.reset(getTarget().createMCObjectStreamer(
206 T, Context, std::unique_ptr<MCAsmBackend>(MAB),
207 DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
208 : MAB->createObjectWriter(Out),
209 std::unique_ptr<MCCodeEmitter>(MCE), STI));
210 break;
211 }
213 // The Null output is intended for use for performance analysis and testing,
214 // not real users.
215 AsmStreamer.reset(getTarget().createNullStreamer(Context));
216 break;
217 }
218
219 return std::move(AsmStreamer);
220}
221
224 CodeGenFileType FileType, bool DisableVerify,
226 // Add common CodeGen passes.
227 if (!MMIWP)
228 MMIWP = new MachineModuleInfoWrapperPass(this);
229 TargetPassConfig *PassConfig =
230 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
231 if (!PassConfig)
232 return true;
233
234 if (PassConfig->willCompleteCodeGenPipeline()) {
235 if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext()))
236 return true;
237 } else {
239 PM.add(createMachineVerifierPass("At end of pipeline"));
240 // MIR printing is redundant with -filetype=null.
241 if (FileType != CodeGenFileType::Null)
242 PM.add(createPrintMIRPass(Out));
243 }
244
246 return false;
247}
248
249/// addPassesToEmitMC - Add passes to the specified pass manager to get
250/// machine code emitted with the MCJIT. This method returns true if machine
251/// code is not supported. It fills the MCContext Ctx pointer which can be
252/// used to build custom MCStreamer.
253///
255 MCContext *&Ctx,
257 bool DisableVerify) {
258 // Add common CodeGen passes.
260 TargetPassConfig *PassConfig =
261 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
262 if (!PassConfig)
263 return true;
264 assert(PassConfig->willCompleteCodeGenPipeline() &&
265 "Cannot emit MC with limited codegen pipeline");
266
267 Ctx = &MMIWP->getMMI().getContext();
268 // libunwind is unable to load compact unwind dynamically, so we must generate
269 // DWARF unwind info for the JIT.
270 Options.MCOptions.EmitDwarfUnwind = EmitDwarfUnwindType::Always;
271
272 // Create the code emitter for the target if it exists. If not, .o file
273 // emission fails.
276 std::unique_ptr<MCCodeEmitter> MCE(
277 getTarget().createMCCodeEmitter(*getMCInstrInfo(), *Ctx));
278 if (!MCE)
279 return true;
280 MCAsmBackend *MAB =
282 if (!MAB)
283 return true;
284
285 const Triple &T = getTargetTriple();
286 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
287 T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
288 std::move(MCE), STI));
289
290 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
292 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
293 if (!Printer)
294 return true;
295
296 PM.add(Printer);
298
299 return false; // success!
300}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu next use AMDGPU Next Use Analysis Printer
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."))
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...
CodeGenTargetMachineImpl(const Target &T, 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) 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.
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:312
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:67
virtual void setUseIntegratedAssembler(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition MCAsmInfo.h:731
void setFullRegisterNames(bool V)
Definition MCAsmInfo.h:601
void setParseInlineAsmUsingAsmParser(bool Value)
Set whether target want to use AsmParser to parse inlineasm.
Definition MCAsmInfo.h:736
void setPreserveAsmComments(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition MCAsmInfo.h:744
unsigned getOutputAssemblerDialect() const
Definition MCAsmInfo.h:578
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:222
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
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.
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 MCRegisterInfo & getMCRegisterInfo() const
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.
MachineVerifierMode getMachineVerifierMode() const
Return where the machine verifier runs in the pipeline.
virtual void addMachinePasses()
Add the complete, standard set of LLVM CodeGen passes.
bool willCompleteCodeGenPipeline() const
Returns true if none of the -stop-before and -stop-after options is set.
void setDisableVerify(bool Disable)
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:48
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.
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:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
LLVM_ABI MCStreamer * createNullStreamer(MCContext &Ctx)
Create a dummy machine code streamer, which does nothing.
LLVM_ABI FunctionPass * createMachineVerifierPass(const std::string &Banner)
createMachineVerifierPass - This pass verifies cenerated machine code instructions for correctness.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:256
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
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)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
LLVM_ABI FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.