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 
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/LegacyPassManager.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCCodeEmitter.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 using namespace llvm;
36 
37 static cl::opt<bool> EnableTrapUnreachable("trap-unreachable",
38   cl::Hidden, cl::ZeroOrMore, cl::init(false),
39   cl::desc("Enable generating trap for unreachable"));
40 
41 void LLVMTargetMachine::initAsmInfo() {
42   MRI.reset(TheTarget.createMCRegInfo(getTargetTriple().str()));
43   MII.reset(TheTarget.createMCInstrInfo());
44   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
45   // to some backends having subtarget feature dependent module level
46   // code generation. This is similar to the hack in the AsmPrinter for
47   // module level assembly etc.
48   STI.reset(TheTarget.createMCSubtargetInfo(
49       getTargetTriple().str(), getTargetCPU(), getTargetFeatureString()));
50 
51   MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo(
52       *MRI, getTargetTriple().str(), Options.MCOptions);
53   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
54   // and if the old one gets included then MCAsmInfo will be NULL and
55   // we'll crash later.
56   // Provide the user with a useful error message about what's wrong.
57   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
58          "Make sure you include the correct TargetSelect.h"
59          "and that InitializeAllTargetMCs() is being invoked!");
60 
61   if (Options.DisableIntegratedAS)
62     TmpAsmInfo->setUseIntegratedAssembler(false);
63 
64   TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
65 
66   TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections);
67 
68   TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
69 
70   if (Options.ExceptionModel != ExceptionHandling::None)
71     TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
72 
73   AsmInfo.reset(TmpAsmInfo);
74 }
75 
76 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
77                                      StringRef DataLayoutString,
78                                      const Triple &TT, StringRef CPU,
79                                      StringRef FS, const TargetOptions &Options,
80                                      Reloc::Model RM, CodeModel::Model CM,
81                                      CodeGenOpt::Level OL)
82     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
83   this->RM = RM;
84   this->CMModel = CM;
85   this->OptLevel = OL;
86 
87   if (EnableTrapUnreachable)
88     this->Options.TrapUnreachable = true;
89 }
90 
91 TargetTransformInfo
92 LLVMTargetMachine::getTargetTransformInfo(const Function &F) {
93   return TargetTransformInfo(BasicTTIImpl(this, F));
94 }
95 
96 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
97 static TargetPassConfig *
98 addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM,
99                         bool DisableVerify,
100                         MachineModuleInfoWrapperPass &MMIWP) {
101   // Targets may override createPassConfig to provide a target-specific
102   // subclass.
103   TargetPassConfig *PassConfig = TM.createPassConfig(PM);
104   // Set PassConfig options provided by TargetMachine.
105   PassConfig->setDisableVerify(DisableVerify);
106   PM.add(PassConfig);
107   PM.add(&MMIWP);
108 
109   if (PassConfig->addISelPasses())
110     return nullptr;
111   PassConfig->addMachinePasses();
112   PassConfig->setInitialized();
113   return PassConfig;
114 }
115 
116 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM,
117                                       raw_pwrite_stream &Out,
118                                       raw_pwrite_stream *DwoOut,
119                                       CodeGenFileType FileType,
120                                       MCContext &Context) {
121   Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
122       createMCStreamer(Out, DwoOut, FileType, Context);
123   if (auto Err = MCStreamerOrErr.takeError())
124     return true;
125 
126   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
127   FunctionPass *Printer =
128       getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
129   if (!Printer)
130     return true;
131 
132   PM.add(Printer);
133   return false;
134 }
135 
136 Expected<std::unique_ptr<MCStreamer>> LLVMTargetMachine::createMCStreamer(
137     raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
138     MCContext &Context) {
139   if (Options.MCOptions.MCSaveTempLabels)
140     Context.setAllowTemporaryLabels(false);
141 
142   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
143   const MCAsmInfo &MAI = *getMCAsmInfo();
144   const MCRegisterInfo &MRI = *getMCRegisterInfo();
145   const MCInstrInfo &MII = *getMCInstrInfo();
146 
147   std::unique_ptr<MCStreamer> AsmStreamer;
148 
149   switch (FileType) {
150   case CGFT_AssemblyFile: {
151     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
152         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
153 
154     // Create a code emitter if asked to show the encoding.
155     std::unique_ptr<MCCodeEmitter> MCE;
156     if (Options.MCOptions.ShowMCEncoding)
157       MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context));
158 
159     std::unique_ptr<MCAsmBackend> MAB(
160         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
161     auto FOut = std::make_unique<formatted_raw_ostream>(Out);
162     MCStreamer *S = getTarget().createAsmStreamer(
163         Context, std::move(FOut), Options.MCOptions.AsmVerbose,
164         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE),
165         std::move(MAB), Options.MCOptions.ShowMCInst);
166     AsmStreamer.reset(S);
167     break;
168   }
169   case CGFT_ObjectFile: {
170     // Create the code emitter for the target if it exists.  If not, .o file
171     // emission fails.
172     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
173     if (!MCE)
174       return make_error<StringError>("createMCCodeEmitter failed",
175                                      inconvertibleErrorCode());
176     MCAsmBackend *MAB =
177         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
178     if (!MAB)
179       return make_error<StringError>("createMCAsmBackend failed",
180                                      inconvertibleErrorCode());
181 
182     Triple T(getTargetTriple().str());
183     AsmStreamer.reset(getTarget().createMCObjectStreamer(
184         T, Context, std::unique_ptr<MCAsmBackend>(MAB),
185         DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
186                : MAB->createObjectWriter(Out),
187         std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
188         Options.MCOptions.MCIncrementalLinkerCompatible,
189         /*DWARFMustBeAtTheEnd*/ true));
190     break;
191   }
192   case CGFT_Null:
193     // The Null output is intended for use for performance analysis and testing,
194     // not real users.
195     AsmStreamer.reset(getTarget().createNullStreamer(Context));
196     break;
197   }
198 
199   return std::move(AsmStreamer);
200 }
201 
202 bool LLVMTargetMachine::addPassesToEmitFile(
203     PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
204     CodeGenFileType FileType, bool DisableVerify,
205     MachineModuleInfoWrapperPass *MMIWP) {
206   // Add common CodeGen passes.
207   if (!MMIWP)
208     MMIWP = new MachineModuleInfoWrapperPass(this);
209   TargetPassConfig *PassConfig =
210       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
211   if (!PassConfig)
212     return true;
213 
214   if (!TargetPassConfig::willCompleteCodeGenPipeline())
215     PM.add(createPrintMIRPass(Out));
216   else if (addAsmPrinter(PM, Out, DwoOut, FileType,
217                            MMIWP->getMMI().getContext()))
218     return true;
219 
220   PM.add(createFreeMachineFunctionPass());
221   return false;
222 }
223 
224 /// addPassesToEmitMC - Add passes to the specified pass manager to get
225 /// machine code emitted with the MCJIT. This method returns true if machine
226 /// code is not supported. It fills the MCContext Ctx pointer which can be
227 /// used to build custom MCStreamer.
228 ///
229 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
230                                           raw_pwrite_stream &Out,
231                                           bool DisableVerify) {
232   // Add common CodeGen passes.
233   MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this);
234   TargetPassConfig *PassConfig =
235       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
236   if (!PassConfig)
237     return true;
238   assert(TargetPassConfig::willCompleteCodeGenPipeline() &&
239          "Cannot emit MC with limited codegen pipeline");
240 
241   Ctx = &MMIWP->getMMI().getContext();
242   if (Options.MCOptions.MCSaveTempLabels)
243     Ctx->setAllowTemporaryLabels(false);
244 
245   // Create the code emitter for the target if it exists.  If not, .o file
246   // emission fails.
247   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
248   const MCRegisterInfo &MRI = *getMCRegisterInfo();
249   MCCodeEmitter *MCE =
250       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
251   MCAsmBackend *MAB =
252       getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
253   if (!MCE || !MAB)
254     return true;
255 
256   const Triple &T = getTargetTriple();
257   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
258       T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
259       std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
260       Options.MCOptions.MCIncrementalLinkerCompatible,
261       /*DWARFMustBeAtTheEnd*/ true));
262 
263   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
264   FunctionPass *Printer =
265       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
266   if (!Printer)
267     return true;
268 
269   PM.add(Printer);
270   PM.add(createFreeMachineFunctionPass());
271 
272   return false; // success!
273 }
274