BackendUtil.cpp 22 KB

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