Add Forward Control-Flow Integrity.
[oota-llvm.git] / lib / CodeGen / LLVMTargetMachine.cpp
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/Target/TargetMachine.h"
15
16 #include "llvm/Analysis/JumpInstrTableInfo.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/ForwardControlFlowIntegrity.h"
20 #include "llvm/CodeGen/JumpInstrTables.h"
21 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/IR/IRPrintingPasses.h"
25 #include "llvm/IR/Verifier.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/Scalar.h"
43 using namespace llvm;
44
45 // Enable or disable FastISel. Both options are needed, because
46 // FastISel is enabled by default with -fast, and we wish to be
47 // able to enable or disable fast-isel independently from -O0.
48 static cl::opt<cl::boolOrDefault>
49 EnableFastISelOption("fast-isel", cl::Hidden,
50   cl::desc("Enable the \"fast\" instruction selector"));
51
52 void LLVMTargetMachine::initAsmInfo() {
53   MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo(
54       *getSubtargetImpl()->getRegisterInfo(), getTargetTriple());
55   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
56   // and if the old one gets included then MCAsmInfo will be NULL and
57   // we'll crash later.
58   // Provide the user with a useful error message about what's wrong.
59   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
60          "Make sure you include the correct TargetSelect.h"
61          "and that InitializeAllTargetMCs() is being invoked!");
62
63   if (Options.DisableIntegratedAS)
64     TmpAsmInfo->setUseIntegratedAssembler(false);
65
66   if (Options.CompressDebugSections)
67     TmpAsmInfo->setCompressDebugSections(true);
68
69   AsmInfo = TmpAsmInfo;
70 }
71
72 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
73                                      StringRef CPU, StringRef FS,
74                                      TargetOptions Options,
75                                      Reloc::Model RM, CodeModel::Model CM,
76                                      CodeGenOpt::Level OL)
77   : TargetMachine(T, Triple, CPU, FS, Options) {
78   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
79 }
80
81 void LLVMTargetMachine::addAnalysisPasses(PassManagerBase &PM) {
82   PM.add(createBasicTargetTransformInfoPass(this));
83 }
84
85 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
86 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
87                                           PassManagerBase &PM,
88                                           bool DisableVerify,
89                                           AnalysisID StartAfter,
90                                           AnalysisID StopAfter) {
91
92   // Add internal analysis passes from the target machine.
93   TM->addAnalysisPasses(PM);
94
95   // Targets may override createPassConfig to provide a target-specific
96   // subclass.
97   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
98   PassConfig->setStartStopPasses(StartAfter, StopAfter);
99
100   // Set PassConfig options provided by TargetMachine.
101   PassConfig->setDisableVerify(DisableVerify);
102
103   PM.add(PassConfig);
104
105   PassConfig->addIRPasses();
106
107   PassConfig->addCodeGenPrepare();
108
109   PassConfig->addPassesToHandleExceptions();
110
111   PassConfig->addISelPrepare();
112
113   // Install a MachineModuleInfo class, which is an immutable pass that holds
114   // all the per-module stuff we're generating, including MCContext.
115   MachineModuleInfo *MMI = new MachineModuleInfo(
116       *TM->getMCAsmInfo(), *TM->getSubtargetImpl()->getRegisterInfo(),
117       &TM->getSubtargetImpl()->getTargetLowering()->getObjFileLowering());
118   PM.add(MMI);
119
120   // Set up a MachineFunction for the rest of CodeGen to work on.
121   PM.add(new MachineFunctionAnalysis(*TM));
122
123   // Enable FastISel with -fast, but allow that to be overridden.
124   if (EnableFastISelOption == cl::BOU_TRUE ||
125       (TM->getOptLevel() == CodeGenOpt::None &&
126        EnableFastISelOption != cl::BOU_FALSE))
127     TM->setFastISel(true);
128
129   // Ask the target for an isel.
130   if (PassConfig->addInstSelector())
131     return nullptr;
132
133   PassConfig->addMachinePasses();
134
135   PassConfig->setInitialized();
136
137   return &MMI->getContext();
138 }
139
140 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
141                                             formatted_raw_ostream &Out,
142                                             CodeGenFileType FileType,
143                                             bool DisableVerify,
144                                             AnalysisID StartAfter,
145                                             AnalysisID StopAfter) {
146   // Passes to handle jumptable function annotations. These can't be handled at
147   // JIT time, so we don't add them directly to addPassesToGenerateCode.
148   PM.add(createJumpInstrTableInfoPass(
149       getSubtargetImpl()->getInstrInfo()->getJumpInstrTableEntryBound()));
150   PM.add(createJumpInstrTablesPass(Options.JTType));
151   if (Options.FCFI)
152     PM.add(createForwardControlFlowIntegrityPass(
153         Options.JTType, Options.CFIType, Options.CFIEnforcing,
154         Options.getCFIFuncName()));
155
156   // Add common CodeGen passes.
157   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
158                                                StartAfter, StopAfter);
159   if (!Context)
160     return true;
161
162   if (StopAfter) {
163     // FIXME: The intent is that this should eventually write out a YAML file,
164     // containing the LLVM IR, the machine-level IR (when stopping after a
165     // machine-level pass), and whatever other information is needed to
166     // deserialize the code and resume compilation.  For now, just write the
167     // LLVM IR.
168     PM.add(createPrintModulePass(Out));
169     return false;
170   }
171
172   if (Options.MCOptions.MCSaveTempLabels)
173     Context->setAllowTemporaryLabels(false);
174
175   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
176   const MCAsmInfo &MAI = *getMCAsmInfo();
177   const MCRegisterInfo &MRI = *getSubtargetImpl()->getRegisterInfo();
178   const MCInstrInfo &MII = *getSubtargetImpl()->getInstrInfo();
179   std::unique_ptr<MCStreamer> AsmStreamer;
180
181   switch (FileType) {
182   case CGFT_AssemblyFile: {
183     MCInstPrinter *InstPrinter =
184       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
185                                       MII, MRI, STI);
186
187     // Create a code emitter if asked to show the encoding.
188     MCCodeEmitter *MCE = nullptr;
189     if (Options.MCOptions.ShowMCEncoding)
190       MCE = getTarget().createMCCodeEmitter(MII, MRI, STI, *Context);
191
192     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
193                                                        TargetCPU);
194     MCStreamer *S = getTarget().createAsmStreamer(
195         *Context, Out, Options.MCOptions.AsmVerbose,
196         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
197         Options.MCOptions.ShowMCInst);
198     AsmStreamer.reset(S);
199     break;
200   }
201   case CGFT_ObjectFile: {
202     // Create the code emitter for the target if it exists.  If not, .o file
203     // emission fails.
204     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, STI,
205                                                          *Context);
206     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
207                                                        TargetCPU);
208     if (!MCE || !MAB)
209       return true;
210
211     AsmStreamer.reset(
212         getTarget()
213             .createMCObjectStreamer(getTargetTriple(), *Context, *MAB, Out, MCE,
214                                     STI, Options.MCOptions.MCRelaxAll));
215     break;
216   }
217   case CGFT_Null:
218     // The Null output is intended for use for performance analysis and testing,
219     // not real users.
220     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
221     break;
222   }
223
224   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
225   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
226   if (!Printer)
227     return true;
228
229   // If successful, createAsmPrinter took ownership of AsmStreamer.
230   AsmStreamer.release();
231
232   PM.add(Printer);
233
234   return false;
235 }
236
237 /// addPassesToEmitMC - Add passes to the specified pass manager to get
238 /// machine code emitted with the MCJIT. This method returns true if machine
239 /// code is not supported. It fills the MCContext Ctx pointer which can be
240 /// used to build custom MCStreamer.
241 ///
242 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
243                                           MCContext *&Ctx,
244                                           raw_ostream &Out,
245                                           bool DisableVerify) {
246   // Add common CodeGen passes.
247   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr);
248   if (!Ctx)
249     return true;
250
251   if (Options.MCOptions.MCSaveTempLabels)
252     Ctx->setAllowTemporaryLabels(false);
253
254   // Create the code emitter for the target if it exists.  If not, .o file
255   // emission fails.
256   const MCRegisterInfo &MRI = *getSubtargetImpl()->getRegisterInfo();
257   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
258   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(
259       *getSubtargetImpl()->getInstrInfo(), MRI, STI, *Ctx);
260   MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
261                                                      TargetCPU);
262   if (!MCE || !MAB)
263     return true;
264
265   std::unique_ptr<MCStreamer> AsmStreamer;
266   AsmStreamer.reset(getTarget()
267                         .createMCObjectStreamer(getTargetTriple(), *Ctx, *MAB,
268                                                 Out, MCE, STI,
269                                                 Options.MCOptions.MCRelaxAll));
270
271   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
272   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
273   if (!Printer)
274     return true;
275
276   // If successful, createAsmPrinter took ownership of AsmStreamer.
277   AsmStreamer.release();
278
279   PM.add(Printer);
280
281   return false; // success!
282 }