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/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/MC/SubtargetFeature.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Transforms/IPO.h"
35 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
36 #include "llvm/Transforms/Instrumentation.h"
37 #include "llvm/Transforms/ObjCARC.h"
38 #include "llvm/Transforms/Scalar.h"
39 using namespace clang;
40 using namespace llvm;
41 
42 namespace {
43 
44 class EmitAssemblyHelper {
45   DiagnosticsEngine &Diags;
46   const CodeGenOptions &CodeGenOpts;
47   const clang::TargetOptions &TargetOpts;
48   const LangOptions &LangOpts;
49   Module *TheModule;
50 
51   Timer CodeGenerationTime;
52 
53   mutable PassManager *CodeGenPasses;
54   mutable PassManager *PerModulePasses;
55   mutable FunctionPassManager *PerFunctionPasses;
56 
57 private:
58   PassManager *getCodeGenPasses(TargetMachine *TM) const {
59     if (!CodeGenPasses) {
60       CodeGenPasses = new PassManager();
61       CodeGenPasses->add(new DataLayout(TheModule));
62       if (TM)
63         TM->addAnalysisPasses(*CodeGenPasses);
64     }
65     return CodeGenPasses;
66   }
67 
68   PassManager *getPerModulePasses(TargetMachine *TM) const {
69     if (!PerModulePasses) {
70       PerModulePasses = new PassManager();
71       PerModulePasses->add(new DataLayout(TheModule));
72       if (TM)
73         TM->addAnalysisPasses(*PerModulePasses);
74     }
75     return PerModulePasses;
76   }
77 
78   FunctionPassManager *getPerFunctionPasses(TargetMachine *TM) const {
79     if (!PerFunctionPasses) {
80       PerFunctionPasses = new FunctionPassManager(TheModule);
81       PerFunctionPasses->add(new DataLayout(TheModule));
82       if (TM)
83         TM->addAnalysisPasses(*PerFunctionPasses);
84     }
85     return PerFunctionPasses;
86   }
87 
88 
89   void CreatePasses(TargetMachine *TM);
90 
91   /// CreateTargetMachine - Generates the TargetMachine.
92   /// Returns Null if it is unable to create the target machine.
93   /// Some of our clang tests specify triples which are not built
94   /// into clang. This is okay because these tests check the generated
95   /// IR, and they require DataLayout which depends on the triple.
96   /// In this case, we allow this method to fail and not report an error.
97   /// When MustCreateTM is used, we print an error if we are unable to load
98   /// the requested target.
99   TargetMachine *CreateTargetMachine(bool MustCreateTM);
100 
101   /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
102   ///
103   /// \return True on success.
104   bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS,
105                      TargetMachine *TM);
106 
107 public:
108   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
109                      const CodeGenOptions &CGOpts,
110                      const clang::TargetOptions &TOpts,
111                      const LangOptions &LOpts,
112                      Module *M)
113     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
114       TheModule(M), CodeGenerationTime("Code Generation Time"),
115       CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
116 
117   ~EmitAssemblyHelper() {
118     delete CodeGenPasses;
119     delete PerModulePasses;
120     delete PerFunctionPasses;
121   }
122 
123   void EmitAssembly(BackendAction Action, raw_ostream *OS);
124 };
125 
126 // We need this wrapper to access LangOpts and CGOpts from extension functions
127 // that we add to the PassManagerBuilder.
128 class PassManagerBuilderWrapper : public PassManagerBuilder {
129 public:
130   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
131                             const LangOptions &LangOpts)
132       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
133   const CodeGenOptions &getCGOpts() const { return CGOpts; }
134   const LangOptions &getLangOpts() const { return LangOpts; }
135 private:
136   const CodeGenOptions &CGOpts;
137   const LangOptions &LangOpts;
138 };
139 
140 }
141 
142 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
143   if (Builder.OptLevel > 0)
144     PM.add(createObjCARCAPElimPass());
145 }
146 
147 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148   if (Builder.OptLevel > 0)
149     PM.add(createObjCARCExpandPass());
150 }
151 
152 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153   if (Builder.OptLevel > 0)
154     PM.add(createObjCARCOptPass());
155 }
156 
157 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
158                                     PassManagerBase &PM) {
159   PM.add(createBoundsCheckingPass());
160 }
161 
162 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
163                                       PassManagerBase &PM) {
164   const PassManagerBuilderWrapper &BuilderWrapper =
165       static_cast<const PassManagerBuilderWrapper&>(Builder);
166   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
167   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
168   PM.add(createAddressSanitizerFunctionPass(
169       LangOpts.Sanitize.InitOrder,
170       LangOpts.Sanitize.UseAfterReturn,
171       LangOpts.Sanitize.UseAfterScope,
172       CGOpts.SanitizerBlacklistFile,
173       CGOpts.SanitizeAddressZeroBaseShadow));
174   PM.add(createAddressSanitizerModulePass(
175       LangOpts.Sanitize.InitOrder,
176       CGOpts.SanitizerBlacklistFile,
177       CGOpts.SanitizeAddressZeroBaseShadow));
178 }
179 
180 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
181                                    PassManagerBase &PM) {
182   const PassManagerBuilderWrapper &BuilderWrapper =
183       static_cast<const PassManagerBuilderWrapper&>(Builder);
184   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
185   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins,
186                                    CGOpts.SanitizerBlacklistFile));
187 }
188 
189 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
190                                    PassManagerBase &PM) {
191   const PassManagerBuilderWrapper &BuilderWrapper =
192       static_cast<const PassManagerBuilderWrapper&>(Builder);
193   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
194   PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile));
195 }
196 
197 void EmitAssemblyHelper::CreatePasses(TargetMachine *TM) {
198   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
199   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
200 
201   // Handle disabling of LLVM optimization, where we want to preserve the
202   // internal module before any optimization.
203   if (CodeGenOpts.DisableLLVMOpts) {
204     OptLevel = 0;
205     Inlining = CodeGenOpts.NoInlining;
206   }
207 
208   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
209   PMBuilder.OptLevel = OptLevel;
210   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
211 
212   PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
213   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
214   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
215 
216   // In ObjC ARC mode, add the main ARC optimization passes.
217   if (LangOpts.ObjCAutoRefCount) {
218     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
219                            addObjCARCExpandPass);
220     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
221                            addObjCARCAPElimPass);
222     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
223                            addObjCARCOptPass);
224   }
225 
226   if (LangOpts.Sanitize.Bounds) {
227     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
228                            addBoundsCheckingPass);
229     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
230                            addBoundsCheckingPass);
231   }
232 
233   if (LangOpts.Sanitize.Address) {
234     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
235                            addAddressSanitizerPasses);
236     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
237                            addAddressSanitizerPasses);
238   }
239 
240   if (LangOpts.Sanitize.Memory) {
241     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
242                            addMemorySanitizerPass);
243     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
244                            addMemorySanitizerPass);
245   }
246 
247   if (LangOpts.Sanitize.Thread) {
248     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
249                            addThreadSanitizerPass);
250     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
251                            addThreadSanitizerPass);
252   }
253 
254   // Figure out TargetLibraryInfo.
255   Triple TargetTriple(TheModule->getTargetTriple());
256   PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
257   if (!CodeGenOpts.SimplifyLibCalls)
258     PMBuilder.LibraryInfo->disableAllFunctions();
259 
260   switch (Inlining) {
261   case CodeGenOptions::NoInlining: break;
262   case CodeGenOptions::NormalInlining: {
263     // FIXME: Derive these constants in a principled fashion.
264     unsigned Threshold = 225;
265     if (CodeGenOpts.OptimizeSize == 1)      // -Os
266       Threshold = 75;
267     else if (CodeGenOpts.OptimizeSize == 2) // -Oz
268       Threshold = 25;
269     else if (OptLevel > 2)
270       Threshold = 275;
271     PMBuilder.Inliner = createFunctionInliningPass(Threshold);
272     break;
273   }
274   case CodeGenOptions::OnlyAlwaysInlining:
275     // Respect always_inline.
276     if (OptLevel == 0)
277       // Do not insert lifetime intrinsics at -O0.
278       PMBuilder.Inliner = createAlwaysInlinerPass(false);
279     else
280       PMBuilder.Inliner = createAlwaysInlinerPass();
281     break;
282   }
283 
284   // Set up the per-function pass manager.
285   FunctionPassManager *FPM = getPerFunctionPasses(TM);
286   if (CodeGenOpts.VerifyModule)
287     FPM->add(createVerifierPass());
288   PMBuilder.populateFunctionPassManager(*FPM);
289 
290   // Set up the per-module pass manager.
291   PassManager *MPM = getPerModulePasses(TM);
292 
293   if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
294     MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
295                                     CodeGenOpts.EmitGcovArcs,
296                                     TargetTriple.isMacOSX(),
297                                     false,
298                                     CodeGenOpts.DisableRedZone));
299 
300     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
301       MPM->add(createStripSymbolsPass(true));
302   }
303 
304   PMBuilder.populateModulePassManager(*MPM);
305 }
306 
307 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
308   // Create the TargetMachine for generating code.
309   std::string Error;
310   std::string Triple = TheModule->getTargetTriple();
311   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
312   if (!TheTarget) {
313     if (MustCreateTM)
314       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
315     return 0;
316   }
317 
318   // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
319   // being gross, this is also totally broken if we ever care about
320   // concurrency.
321 
322   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
323 
324   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
325   TargetMachine::setDataSections    (CodeGenOpts.DataSections);
326 
327   // FIXME: Parse this earlier.
328   llvm::CodeModel::Model CM;
329   if (CodeGenOpts.CodeModel == "small") {
330     CM = llvm::CodeModel::Small;
331   } else if (CodeGenOpts.CodeModel == "kernel") {
332     CM = llvm::CodeModel::Kernel;
333   } else if (CodeGenOpts.CodeModel == "medium") {
334     CM = llvm::CodeModel::Medium;
335   } else if (CodeGenOpts.CodeModel == "large") {
336     CM = llvm::CodeModel::Large;
337   } else {
338     assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
339     CM = llvm::CodeModel::Default;
340   }
341 
342   SmallVector<const char *, 16> BackendArgs;
343   BackendArgs.push_back("clang"); // Fake program name.
344   if (!CodeGenOpts.DebugPass.empty()) {
345     BackendArgs.push_back("-debug-pass");
346     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
347   }
348   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
349     BackendArgs.push_back("-limit-float-precision");
350     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
351   }
352   if (llvm::TimePassesIsEnabled)
353     BackendArgs.push_back("-time-passes");
354   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
355     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
356   if (CodeGenOpts.NoGlobalMerge)
357     BackendArgs.push_back("-global-merge=false");
358   BackendArgs.push_back(0);
359   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
360                                     BackendArgs.data());
361 
362   std::string FeaturesStr;
363   if (TargetOpts.Features.size()) {
364     SubtargetFeatures Features;
365     for (std::vector<std::string>::const_iterator
366            it = TargetOpts.Features.begin(),
367            ie = TargetOpts.Features.end(); it != ie; ++it)
368       Features.AddFeature(*it);
369     FeaturesStr = Features.getString();
370   }
371 
372   llvm::Reloc::Model RM = llvm::Reloc::Default;
373   if (CodeGenOpts.RelocationModel == "static") {
374     RM = llvm::Reloc::Static;
375   } else if (CodeGenOpts.RelocationModel == "pic") {
376     RM = llvm::Reloc::PIC_;
377   } else {
378     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
379            "Invalid PIC model!");
380     RM = llvm::Reloc::DynamicNoPIC;
381   }
382 
383   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
384   switch (CodeGenOpts.OptimizationLevel) {
385   default: break;
386   case 0: OptLevel = CodeGenOpt::None; break;
387   case 3: OptLevel = CodeGenOpt::Aggressive; break;
388   }
389 
390   llvm::TargetOptions Options;
391 
392   // Set frame pointer elimination mode.
393   if (!CodeGenOpts.DisableFPElim) {
394     Options.NoFramePointerElim = false;
395     Options.NoFramePointerElimNonLeaf = false;
396   } else if (CodeGenOpts.OmitLeafFramePointer) {
397     Options.NoFramePointerElim = false;
398     Options.NoFramePointerElimNonLeaf = true;
399   } else {
400     Options.NoFramePointerElim = true;
401     Options.NoFramePointerElimNonLeaf = true;
402   }
403 
404   if (CodeGenOpts.UseInitArray)
405     Options.UseInitArray = true;
406 
407   // Set float ABI type.
408   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
409     Options.FloatABIType = llvm::FloatABI::Soft;
410   else if (CodeGenOpts.FloatABI == "hard")
411     Options.FloatABIType = llvm::FloatABI::Hard;
412   else {
413     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
414     Options.FloatABIType = llvm::FloatABI::Default;
415   }
416 
417   // Set FP fusion mode.
418   switch (CodeGenOpts.getFPContractMode()) {
419   case CodeGenOptions::FPC_Off:
420     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
421     break;
422   case CodeGenOptions::FPC_On:
423     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
424     break;
425   case CodeGenOptions::FPC_Fast:
426     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
427     break;
428   }
429 
430   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
431   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
432   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
433   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
434   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
435   Options.UseSoftFloat = CodeGenOpts.SoftFloat;
436   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
437   Options.RealignStack = CodeGenOpts.StackRealignment;
438   Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
439   Options.TrapFuncName = CodeGenOpts.TrapFuncName;
440   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
441   Options.SSPBufferSize = CodeGenOpts.SSPBufferSize;
442 
443   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
444                                                      FeaturesStr, Options,
445                                                      RM, CM, OptLevel);
446 
447   if (CodeGenOpts.RelaxAll)
448     TM->setMCRelaxAll(true);
449   if (CodeGenOpts.SaveTempLabels)
450     TM->setMCSaveTempLabels(true);
451   if (CodeGenOpts.NoDwarf2CFIAsm)
452     TM->setMCUseCFI(false);
453   if (!CodeGenOpts.NoDwarfDirectoryAsm)
454     TM->setMCUseDwarfDirectory(true);
455   if (CodeGenOpts.NoExecStack)
456     TM->setMCNoExecStack(true);
457 
458   return TM;
459 }
460 
461 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
462                                        formatted_raw_ostream &OS,
463                                        TargetMachine *TM) {
464 
465   // Create the code generator passes.
466   PassManager *PM = getCodeGenPasses(TM);
467 
468   // Add LibraryInfo.
469   llvm::Triple TargetTriple(TheModule->getTargetTriple());
470   TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
471   if (!CodeGenOpts.SimplifyLibCalls)
472     TLI->disableAllFunctions();
473   PM->add(TLI);
474 
475   // Add Target specific analysis passes.
476   TM->addAnalysisPasses(*PM);
477 
478   // Normal mode, emit a .s or .o file by running the code generator. Note,
479   // this also adds codegenerator level optimization passes.
480   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
481   if (Action == Backend_EmitObj)
482     CGFT = TargetMachine::CGFT_ObjectFile;
483   else if (Action == Backend_EmitMCNull)
484     CGFT = TargetMachine::CGFT_Null;
485   else
486     assert(Action == Backend_EmitAssembly && "Invalid action!");
487 
488   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
489   // "codegen" passes so that it isn't run multiple times when there is
490   // inlining happening.
491   if (LangOpts.ObjCAutoRefCount &&
492       CodeGenOpts.OptimizationLevel > 0)
493     PM->add(createObjCARCContractPass());
494 
495   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
496                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
497     Diags.Report(diag::err_fe_unable_to_interface_with_target);
498     return false;
499   }
500 
501   return true;
502 }
503 
504 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
505   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
506   llvm::formatted_raw_ostream FormattedOS;
507 
508   bool UsesCodeGen = (Action != Backend_EmitNothing &&
509                       Action != Backend_EmitBC &&
510                       Action != Backend_EmitLL);
511   TargetMachine *TM = CreateTargetMachine(UsesCodeGen);
512   CreatePasses(TM);
513 
514   switch (Action) {
515   case Backend_EmitNothing:
516     break;
517 
518   case Backend_EmitBC:
519     getPerModulePasses(TM)->add(createBitcodeWriterPass(*OS));
520     break;
521 
522   case Backend_EmitLL:
523     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
524     getPerModulePasses(TM)->add(createPrintModulePass(&FormattedOS));
525     break;
526 
527   default:
528     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
529     if (!AddEmitPasses(Action, FormattedOS, TM))
530       return;
531   }
532 
533   // Before executing passes, print the final values of the LLVM options.
534   cl::PrintOptionValues();
535 
536   // Run passes. For now we do all passes at once, but eventually we
537   // would like to have the option of streaming code generation.
538 
539   if (PerFunctionPasses) {
540     PrettyStackTraceString CrashInfo("Per-function optimization");
541 
542     PerFunctionPasses->doInitialization();
543     for (Module::iterator I = TheModule->begin(),
544            E = TheModule->end(); I != E; ++I)
545       if (!I->isDeclaration())
546         PerFunctionPasses->run(*I);
547     PerFunctionPasses->doFinalization();
548   }
549 
550   if (PerModulePasses) {
551     PrettyStackTraceString CrashInfo("Per-module optimization passes");
552     PerModulePasses->run(*TheModule);
553   }
554 
555   if (CodeGenPasses) {
556     PrettyStackTraceString CrashInfo("Code generation");
557     CodeGenPasses->run(*TheModule);
558   }
559 }
560 
561 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
562                               const CodeGenOptions &CGOpts,
563                               const clang::TargetOptions &TOpts,
564                               const LangOptions &LOpts,
565                               Module *M,
566                               BackendAction Action, raw_ostream *OS) {
567   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
568 
569   AsmHelper.EmitAssembly(Action, OS);
570 }
571