BackendUtil.cpp 22 KB

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