1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVMTargetMachine class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/Passes.h"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/CodeGen/BasicTTIImpl.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/TargetPassConfig.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCCodeEmitter.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCInstrInfo.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 = TheTarget.createMCRegInfo(getTargetTriple().str());
43   MII = 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 = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
49                                         getTargetFeatureString());
50 
51   MCAsmInfo *TmpAsmInfo =
52       TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
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 = 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 MCContext *
98 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
99                         bool DisableVerify, bool &WillCompleteCodeGenPipeline,
100                         raw_pwrite_stream &Out, MachineModuleInfo *MMI) {
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   WillCompleteCodeGenPipeline = PassConfig->willCompleteCodeGenPipeline();
107   PM.add(PassConfig);
108   if (!MMI)
109     MMI = new MachineModuleInfo(TM);
110   PM.add(MMI);
111 
112   if (PassConfig->addISelPasses())
113     return nullptr;
114   PassConfig->addMachinePasses();
115   PassConfig->setInitialized();
116   if (!WillCompleteCodeGenPipeline)
117     PM.add(createPrintMIRPass(Out));
118 
119   return &MMI->getContext();
120 }
121 
122 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM,
123     raw_pwrite_stream &Out, CodeGenFileType FileType,
124     MCContext &Context) {
125   if (Options.MCOptions.MCSaveTempLabels)
126     Context.setAllowTemporaryLabels(false);
127 
128   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
129   const MCAsmInfo &MAI = *getMCAsmInfo();
130   const MCRegisterInfo &MRI = *getMCRegisterInfo();
131   const MCInstrInfo &MII = *getMCInstrInfo();
132 
133   std::unique_ptr<MCStreamer> AsmStreamer;
134 
135   switch (FileType) {
136   case CGFT_AssemblyFile: {
137     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
138         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
139 
140     // Create a code emitter if asked to show the encoding.
141     std::unique_ptr<MCCodeEmitter> MCE;
142     if (Options.MCOptions.ShowMCEncoding)
143       MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context));
144 
145     std::unique_ptr<MCAsmBackend> MAB(
146         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
147     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
148     MCStreamer *S = getTarget().createAsmStreamer(
149         Context, std::move(FOut), Options.MCOptions.AsmVerbose,
150         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE),
151         std::move(MAB), Options.MCOptions.ShowMCInst);
152     AsmStreamer.reset(S);
153     break;
154   }
155   case CGFT_ObjectFile: {
156     // Create the code emitter for the target if it exists.  If not, .o file
157     // emission fails.
158     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
159     MCAsmBackend *MAB =
160         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
161     if (!MCE || !MAB)
162       return true;
163 
164     // Don't waste memory on names of temp labels.
165     Context.setUseNamesOnTempLabels(false);
166 
167     Triple T(getTargetTriple().str());
168     AsmStreamer.reset(getTarget().createMCObjectStreamer(
169         T, Context, std::unique_ptr<MCAsmBackend>(MAB), Out,
170         std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
171         Options.MCOptions.MCIncrementalLinkerCompatible,
172         /*DWARFMustBeAtTheEnd*/ true));
173     break;
174   }
175   case CGFT_Null:
176     // The Null output is intended for use for performance analysis and testing,
177     // not real users.
178     AsmStreamer.reset(getTarget().createNullStreamer(Context));
179     break;
180   }
181 
182   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
183   FunctionPass *Printer =
184       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
185   if (!Printer)
186     return true;
187 
188   PM.add(Printer);
189   return false;
190 }
191 
192 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
193                                             raw_pwrite_stream &Out,
194                                             CodeGenFileType FileType,
195                                             bool DisableVerify,
196                                             MachineModuleInfo *MMI) {
197   // Add common CodeGen passes.
198   bool WillCompleteCodeGenPipeline = true;
199   MCContext *Context = addPassesToGenerateCode(
200       this, PM, DisableVerify, WillCompleteCodeGenPipeline, Out, MMI);
201   if (!Context)
202     return true;
203 
204   if (WillCompleteCodeGenPipeline && addAsmPrinter(PM, Out, FileType, *Context))
205     return true;
206 
207   PM.add(createFreeMachineFunctionPass());
208   return false;
209 }
210 
211 /// addPassesToEmitMC - Add passes to the specified pass manager to get
212 /// machine code emitted with the MCJIT. This method returns true if machine
213 /// code is not supported. It fills the MCContext Ctx pointer which can be
214 /// used to build custom MCStreamer.
215 ///
216 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
217                                           raw_pwrite_stream &Out,
218                                           bool DisableVerify) {
219   // Add common CodeGen passes.
220   bool WillCompleteCodeGenPipeline = true;
221   Ctx = addPassesToGenerateCode(this, PM, DisableVerify,
222                                 WillCompleteCodeGenPipeline, Out,
223                                 /*MachineModuleInfo*/ nullptr);
224   if (!Ctx)
225     return true;
226   assert(WillCompleteCodeGenPipeline && "CodeGen pipeline has been altered");
227 
228   if (Options.MCOptions.MCSaveTempLabels)
229     Ctx->setAllowTemporaryLabels(false);
230 
231   // Create the code emitter for the target if it exists.  If not, .o file
232   // emission fails.
233   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
234   const MCRegisterInfo &MRI = *getMCRegisterInfo();
235   MCCodeEmitter *MCE =
236       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
237   MCAsmBackend *MAB =
238       getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
239   if (!MCE || !MAB)
240     return true;
241 
242   const Triple &T = getTargetTriple();
243   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
244       T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), Out,
245       std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
246       Options.MCOptions.MCIncrementalLinkerCompatible,
247       /*DWARFMustBeAtTheEnd*/ true));
248 
249   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
250   FunctionPass *Printer =
251       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
252   if (!Printer)
253     return true;
254 
255   PM.add(Printer);
256   PM.add(createFreeMachineFunctionPass());
257 
258   return false; // success!
259 }
260