1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/TargetOptions.h"
13 #include "clang/Basic/LangOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/RegAllocRegistry.h"
22 #include "llvm/CodeGen/SchedulerRegistry.h"
23 #include "llvm/MC/SubtargetFeature.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FormattedStream.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Transforms/Instrumentation.h"
35 #include "llvm/Transforms/IPO.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 #include "llvm/Transforms/Scalar.h"
38 using namespace clang;
39 using namespace llvm;
40 
41 namespace {
42 
43 class EmitAssemblyHelper {
44   DiagnosticsEngine &Diags;
45   const CodeGenOptions &CodeGenOpts;
46   const TargetOptions &TargetOpts;
47   const LangOptions &LangOpts;
48   Module *TheModule;
49 
50   Timer CodeGenerationTime;
51 
52   mutable PassManager *CodeGenPasses;
53   mutable PassManager *PerModulePasses;
54   mutable FunctionPassManager *PerFunctionPasses;
55 
56 private:
57   PassManager *getCodeGenPasses() const {
58     if (!CodeGenPasses) {
59       CodeGenPasses = new PassManager();
60       CodeGenPasses->add(new TargetData(TheModule));
61     }
62     return CodeGenPasses;
63   }
64 
65   PassManager *getPerModulePasses() const {
66     if (!PerModulePasses) {
67       PerModulePasses = new PassManager();
68       PerModulePasses->add(new TargetData(TheModule));
69     }
70     return PerModulePasses;
71   }
72 
73   FunctionPassManager *getPerFunctionPasses() const {
74     if (!PerFunctionPasses) {
75       PerFunctionPasses = new FunctionPassManager(TheModule);
76       PerFunctionPasses->add(new TargetData(TheModule));
77     }
78     return PerFunctionPasses;
79   }
80 
81   void CreatePasses();
82 
83   /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
84   ///
85   /// \return True on success.
86   bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
87 
88 public:
89   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
90                      const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
91                      const LangOptions &LOpts,
92                      Module *M)
93     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
94       TheModule(M), CodeGenerationTime("Code Generation Time"),
95       CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
96 
97   ~EmitAssemblyHelper() {
98     delete CodeGenPasses;
99     delete PerModulePasses;
100     delete PerFunctionPasses;
101   }
102 
103   void EmitAssembly(BackendAction Action, raw_ostream *OS);
104 };
105 
106 }
107 
108 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
109   if (Builder.OptLevel > 0)
110     PM.add(createObjCARCExpandPass());
111 }
112 
113 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
114   if (Builder.OptLevel > 0)
115     PM.add(createObjCARCOptPass());
116 }
117 
118 static void addAddressSanitizerPass(const PassManagerBuilder &Builder,
119                                     PassManagerBase &PM) {
120   PM.add(createAddressSanitizerPass());
121 }
122 
123 void EmitAssemblyHelper::CreatePasses() {
124   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
125   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
126 
127   // Handle disabling of LLVM optimization, where we want to preserve the
128   // internal module before any optimization.
129   if (CodeGenOpts.DisableLLVMOpts) {
130     OptLevel = 0;
131     Inlining = CodeGenOpts.NoInlining;
132   }
133 
134   PassManagerBuilder PMBuilder;
135   PMBuilder.OptLevel = OptLevel;
136   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
137 
138   PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
139   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
140   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
141 
142   // In ObjC ARC mode, add the main ARC optimization passes.
143   if (LangOpts.ObjCAutoRefCount) {
144     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
145                            addObjCARCExpandPass);
146     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
147                            addObjCARCOptPass);
148   }
149 
150   if (CodeGenOpts.AddressSanitizer) {
151     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
152                            addAddressSanitizerPass);
153   }
154 
155   // Figure out TargetLibraryInfo.
156   Triple TargetTriple(TheModule->getTargetTriple());
157   PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
158   if (!CodeGenOpts.SimplifyLibCalls)
159     PMBuilder.LibraryInfo->disableAllFunctions();
160 
161   switch (Inlining) {
162   case CodeGenOptions::NoInlining: break;
163   case CodeGenOptions::NormalInlining: {
164     // FIXME: Derive these constants in a principled fashion.
165     unsigned Threshold = 225;
166     if (CodeGenOpts.OptimizeSize == 1)      // -Os
167       Threshold = 75;
168     else if (CodeGenOpts.OptimizeSize == 2) // -Oz
169       Threshold = 25;
170     else if (OptLevel > 2)
171       Threshold = 275;
172     PMBuilder.Inliner = createFunctionInliningPass(Threshold);
173     break;
174   }
175   case CodeGenOptions::OnlyAlwaysInlining:
176     // Respect always_inline.
177     PMBuilder.Inliner = createAlwaysInlinerPass();
178     break;
179   }
180 
181 
182   // Set up the per-function pass manager.
183   FunctionPassManager *FPM = getPerFunctionPasses();
184   if (CodeGenOpts.VerifyModule)
185     FPM->add(createVerifierPass());
186   PMBuilder.populateFunctionPassManager(*FPM);
187 
188   // Set up the per-module pass manager.
189   PassManager *MPM = getPerModulePasses();
190 
191   if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
192     MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
193                                     CodeGenOpts.EmitGcovArcs,
194                                     TargetTriple.isMacOSX()));
195 
196     if (!CodeGenOpts.DebugInfo)
197       MPM->add(createStripSymbolsPass(true));
198   }
199 
200 
201   PMBuilder.populateModulePassManager(*MPM);
202 }
203 
204 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
205                                        formatted_raw_ostream &OS) {
206   // Create the TargetMachine for generating code.
207   std::string Error;
208   std::string Triple = TheModule->getTargetTriple();
209   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
210   if (!TheTarget) {
211     Diags.Report(diag::err_fe_unable_to_create_target) << Error;
212     return false;
213   }
214 
215   // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
216   // being gross, this is also totally broken if we ever care about
217   // concurrency.
218 
219   // Set frame pointer elimination mode.
220   if (!CodeGenOpts.DisableFPElim) {
221     llvm::NoFramePointerElim = false;
222     llvm::NoFramePointerElimNonLeaf = false;
223   } else if (CodeGenOpts.OmitLeafFramePointer) {
224     llvm::NoFramePointerElim = false;
225     llvm::NoFramePointerElimNonLeaf = true;
226   } else {
227     llvm::NoFramePointerElim = true;
228     llvm::NoFramePointerElimNonLeaf = true;
229   }
230 
231   // Set float ABI type.
232   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
233     llvm::FloatABIType = llvm::FloatABI::Soft;
234   else if (CodeGenOpts.FloatABI == "hard")
235     llvm::FloatABIType = llvm::FloatABI::Hard;
236   else {
237     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
238     llvm::FloatABIType = llvm::FloatABI::Default;
239   }
240 
241   llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
242   llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
243   llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
244   NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
245   llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
246   llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
247 
248   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
249 
250   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
251   TargetMachine::setDataSections    (CodeGenOpts.DataSections);
252 
253   // FIXME: Parse this earlier.
254   llvm::CodeModel::Model CM;
255   if (CodeGenOpts.CodeModel == "small") {
256     CM = llvm::CodeModel::Small;
257   } else if (CodeGenOpts.CodeModel == "kernel") {
258     CM = llvm::CodeModel::Kernel;
259   } else if (CodeGenOpts.CodeModel == "medium") {
260     CM = llvm::CodeModel::Medium;
261   } else if (CodeGenOpts.CodeModel == "large") {
262     CM = llvm::CodeModel::Large;
263   } else {
264     assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
265     CM = llvm::CodeModel::Default;
266   }
267 
268   std::vector<const char *> BackendArgs;
269   BackendArgs.push_back("clang"); // Fake program name.
270   if (!CodeGenOpts.DebugPass.empty()) {
271     BackendArgs.push_back("-debug-pass");
272     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
273   }
274   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
275     BackendArgs.push_back("-limit-float-precision");
276     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
277   }
278   if (llvm::TimePassesIsEnabled)
279     BackendArgs.push_back("-time-passes");
280   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
281     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
282   if (CodeGenOpts.NoGlobalMerge)
283     BackendArgs.push_back("-global-merge=false");
284   BackendArgs.push_back(0);
285   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
286                                     const_cast<char **>(&BackendArgs[0]));
287 
288   std::string FeaturesStr;
289   if (TargetOpts.Features.size()) {
290     SubtargetFeatures Features;
291     for (std::vector<std::string>::const_iterator
292            it = TargetOpts.Features.begin(),
293            ie = TargetOpts.Features.end(); it != ie; ++it)
294       Features.AddFeature(*it);
295     FeaturesStr = Features.getString();
296   }
297 
298   llvm::Reloc::Model RM = llvm::Reloc::Default;
299   if (CodeGenOpts.RelocationModel == "static") {
300     RM = llvm::Reloc::Static;
301   } else if (CodeGenOpts.RelocationModel == "pic") {
302     RM = llvm::Reloc::PIC_;
303   } else {
304     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
305            "Invalid PIC model!");
306     RM = llvm::Reloc::DynamicNoPIC;
307   }
308 
309   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
310   switch (CodeGenOpts.OptimizationLevel) {
311   default: break;
312   case 0: OptLevel = CodeGenOpt::None; break;
313   case 3: OptLevel = CodeGenOpt::Aggressive; break;
314   }
315 
316   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
317                                                      FeaturesStr, RM, CM,
318                                                      OptLevel);
319 
320   if (CodeGenOpts.RelaxAll)
321     TM->setMCRelaxAll(true);
322   if (CodeGenOpts.SaveTempLabels)
323     TM->setMCSaveTempLabels(true);
324   if (CodeGenOpts.NoDwarf2CFIAsm)
325     TM->setMCUseCFI(false);
326   if (!CodeGenOpts.NoDwarfDirectoryAsm)
327     TM->setMCUseDwarfDirectory(true);
328   if (CodeGenOpts.NoExecStack)
329     TM->setMCNoExecStack(true);
330 
331   // Create the code generator passes.
332   PassManager *PM = getCodeGenPasses();
333 
334   // Normal mode, emit a .s or .o file by running the code generator. Note,
335   // this also adds codegenerator level optimization passes.
336   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
337   if (Action == Backend_EmitObj)
338     CGFT = TargetMachine::CGFT_ObjectFile;
339   else if (Action == Backend_EmitMCNull)
340     CGFT = TargetMachine::CGFT_Null;
341   else
342     assert(Action == Backend_EmitAssembly && "Invalid action!");
343 
344   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
345   // "codegen" passes so that it isn't run multiple times when there is
346   // inlining happening.
347   if (LangOpts.ObjCAutoRefCount)
348     PM->add(createObjCARCContractPass());
349 
350   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
351                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
352     Diags.Report(diag::err_fe_unable_to_interface_with_target);
353     return false;
354   }
355 
356   return true;
357 }
358 
359 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
360   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
361   llvm::formatted_raw_ostream FormattedOS;
362 
363   CreatePasses();
364   switch (Action) {
365   case Backend_EmitNothing:
366     break;
367 
368   case Backend_EmitBC:
369     getPerModulePasses()->add(createBitcodeWriterPass(*OS));
370     break;
371 
372   case Backend_EmitLL:
373     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
374     getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
375     break;
376 
377   default:
378     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
379     if (!AddEmitPasses(Action, FormattedOS))
380       return;
381   }
382 
383   // Before executing passes, print the final values of the LLVM options.
384   cl::PrintOptionValues();
385 
386   // Run passes. For now we do all passes at once, but eventually we
387   // would like to have the option of streaming code generation.
388 
389   if (PerFunctionPasses) {
390     PrettyStackTraceString CrashInfo("Per-function optimization");
391 
392     PerFunctionPasses->doInitialization();
393     for (Module::iterator I = TheModule->begin(),
394            E = TheModule->end(); I != E; ++I)
395       if (!I->isDeclaration())
396         PerFunctionPasses->run(*I);
397     PerFunctionPasses->doFinalization();
398   }
399 
400   if (PerModulePasses) {
401     PrettyStackTraceString CrashInfo("Per-module optimization passes");
402     PerModulePasses->run(*TheModule);
403   }
404 
405   if (CodeGenPasses) {
406     PrettyStackTraceString CrashInfo("Code generation");
407     CodeGenPasses->run(*TheModule);
408   }
409 }
410 
411 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
412                               const CodeGenOptions &CGOpts,
413                               const TargetOptions &TOpts,
414                               const LangOptions &LOpts,
415                               Module *M,
416                               BackendAction Action, raw_ostream *OS) {
417   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
418 
419   AsmHelper.EmitAssembly(Action, OS);
420 }
421