BackendUtil.cpp 21 KB

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