BackendUtil.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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/Analysis/TargetLibraryInfo.h"
  18. #include "llvm/Analysis/TargetTransformInfo.h"
  19. #include "llvm/Bitcode/BitcodeWriterPass.h"
  20. #include "llvm/CodeGen/RegAllocRegistry.h"
  21. #include "llvm/CodeGen/SchedulerRegistry.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/IRPrintingPasses.h"
  24. #include "llvm/IR/LegacyPassManager.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/Verifier.h"
  27. #include "llvm/MC/SubtargetFeature.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/PrettyStackTrace.h"
  30. #include "llvm/Support/TargetRegistry.h"
  31. #include "llvm/Support/Timer.h"
  32. #include "llvm/Support/raw_ostream.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 "llvm/Transforms/Utils/SymbolRewriter.h"
  42. #include <memory>
  43. #include "dxc/HLSL/DxilGenerationPass.h" // HLSL Change
  44. #include "dxc/HLSL/HLMatrixLowerPass.h" // HLSL Change
  45. using namespace clang;
  46. using namespace llvm;
  47. namespace {
  48. class EmitAssemblyHelper {
  49. DiagnosticsEngine &Diags;
  50. const CodeGenOptions &CodeGenOpts;
  51. const clang::TargetOptions &TargetOpts;
  52. const LangOptions &LangOpts;
  53. Module *TheModule;
  54. // HLSL Changes Start
  55. std::string CodeGenPassesConfig;
  56. std::string PerModulePassesConfig;
  57. std::string PerFunctionPassesConfig;
  58. mutable llvm::raw_string_ostream CodeGenPassesConfigOS;
  59. mutable llvm::raw_string_ostream PerModulePassesConfigOS;
  60. mutable llvm::raw_string_ostream PerFunctionPassesConfigOS;
  61. // HLSL Changes End
  62. Timer CodeGenerationTime;
  63. mutable legacy::PassManager *CodeGenPasses;
  64. mutable legacy::PassManager *PerModulePasses;
  65. mutable legacy::FunctionPassManager *PerFunctionPasses;
  66. private:
  67. TargetIRAnalysis getTargetIRAnalysis() const {
  68. if (TM)
  69. return TM->getTargetIRAnalysis();
  70. return TargetIRAnalysis();
  71. }
  72. legacy::PassManager *getCodeGenPasses() const {
  73. if (!CodeGenPasses) {
  74. CodeGenPasses = new legacy::PassManager();
  75. CodeGenPasses->TrackPassOS = &CodeGenPassesConfigOS;
  76. CodeGenPasses->add(
  77. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  78. }
  79. return CodeGenPasses;
  80. }
  81. legacy::PassManager *getPerModulePasses() const {
  82. if (!PerModulePasses) {
  83. PerModulePasses = new legacy::PassManager();
  84. PerModulePasses->TrackPassOS = &PerModulePassesConfigOS;
  85. PerModulePasses->add(
  86. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  87. }
  88. return PerModulePasses;
  89. }
  90. legacy::FunctionPassManager *getPerFunctionPasses() const {
  91. if (!PerFunctionPasses) {
  92. PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
  93. PerFunctionPasses->TrackPassOS = &PerFunctionPassesConfigOS;
  94. PerFunctionPasses->add(
  95. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  96. }
  97. return PerFunctionPasses;
  98. }
  99. void CreatePasses();
  100. /// Generates the TargetMachine.
  101. /// Returns Null if it is unable to create the target machine.
  102. /// Some of our clang tests specify triples which are not built
  103. /// into clang. This is okay because these tests check the generated
  104. /// IR, and they require DataLayout which depends on the triple.
  105. /// In this case, we allow this method to fail and not report an error.
  106. /// When MustCreateTM is used, we print an error if we are unable to load
  107. /// the requested target.
  108. TargetMachine *CreateTargetMachine(bool MustCreateTM);
  109. /// Add passes necessary to emit assembly or LLVM IR.
  110. ///
  111. /// \return True on success.
  112. bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
  113. public:
  114. EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  115. const CodeGenOptions &CGOpts,
  116. const clang::TargetOptions &TOpts,
  117. const LangOptions &LOpts,
  118. Module *M)
  119. : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
  120. TheModule(M),
  121. // HLSL Changes Start
  122. CodeGenPassesConfigOS(CodeGenPassesConfig),
  123. PerModulePassesConfigOS(PerModulePassesConfig),
  124. PerFunctionPassesConfigOS(PerFunctionPassesConfig),
  125. // HLSL Changes End
  126. CodeGenerationTime("Code Generation Time"),
  127. CodeGenPasses(nullptr), PerModulePasses(nullptr),
  128. PerFunctionPasses(nullptr) {}
  129. ~EmitAssemblyHelper() {
  130. delete CodeGenPasses;
  131. delete PerModulePasses;
  132. delete PerFunctionPasses;
  133. if (CodeGenOpts.DisableFree)
  134. BuryPointer(std::move(TM));
  135. }
  136. std::unique_ptr<TargetMachine> TM;
  137. void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
  138. };
  139. // We need this wrapper to access LangOpts and CGOpts from extension functions
  140. // that we add to the PassManagerBuilder.
  141. class PassManagerBuilderWrapper : public PassManagerBuilder {
  142. public:
  143. PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
  144. const LangOptions &LangOpts)
  145. : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
  146. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  147. const LangOptions &getLangOpts() const { return LangOpts; }
  148. private:
  149. const CodeGenOptions &CGOpts;
  150. const LangOptions &LangOpts;
  151. };
  152. }
  153. #ifdef MS_ENABLE_OBJCARC // HLSL Change
  154. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  155. if (Builder.OptLevel > 0)
  156. PM.add(createObjCARCAPElimPass());
  157. }
  158. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  159. if (Builder.OptLevel > 0)
  160. PM.add(createObjCARCExpandPass());
  161. }
  162. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  163. if (Builder.OptLevel > 0)
  164. PM.add(createObjCARCOptPass());
  165. }
  166. #endif // MS_ENABLE_OBJCARC - HLSL Change
  167. static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
  168. legacy::PassManagerBase &PM) {
  169. const PassManagerBuilderWrapper &BuilderWrapper =
  170. static_cast<const PassManagerBuilderWrapper &>(Builder);
  171. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  172. PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
  173. }
  174. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  175. legacy::PassManagerBase &PM) {
  176. PM.add(createAddDiscriminatorsPass());
  177. }
  178. #ifdef MS_ENABLE_OBJCARC // HLSL Change
  179. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  180. legacy::PassManagerBase &PM) {
  181. PM.add(createBoundsCheckingPass());
  182. }
  183. #endif // MS_ENABLE_OBJCARC // HLSL Change
  184. #ifdef MS_ENABLE_INSTR // HLSL Change
  185. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  186. legacy::PassManagerBase &PM) {
  187. const PassManagerBuilderWrapper &BuilderWrapper =
  188. static_cast<const PassManagerBuilderWrapper&>(Builder);
  189. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  190. SanitizerCoverageOptions Opts;
  191. Opts.CoverageType =
  192. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  193. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  194. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  195. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  196. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  197. PM.add(createSanitizerCoverageModulePass(Opts));
  198. }
  199. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  200. legacy::PassManagerBase &PM) {
  201. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false));
  202. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false));
  203. }
  204. static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
  205. legacy::PassManagerBase &PM) {
  206. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true));
  207. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true));
  208. }
  209. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  210. legacy::PassManagerBase &PM) {
  211. const PassManagerBuilderWrapper &BuilderWrapper =
  212. static_cast<const PassManagerBuilderWrapper&>(Builder);
  213. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  214. PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
  215. // MemorySanitizer inserts complex instrumentation that mostly follows
  216. // the logic of the original code, but operates on "shadow" values.
  217. // It can benefit from re-running some general purpose optimization passes.
  218. if (Builder.OptLevel > 0) {
  219. PM.add(createEarlyCSEPass());
  220. PM.add(createReassociatePass());
  221. PM.add(createLICMPass());
  222. PM.add(createGVNPass());
  223. PM.add(createInstructionCombiningPass());
  224. PM.add(createDeadStoreEliminationPass());
  225. }
  226. }
  227. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  228. legacy::PassManagerBase &PM) {
  229. PM.add(createThreadSanitizerPass());
  230. }
  231. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  232. legacy::PassManagerBase &PM) {
  233. const PassManagerBuilderWrapper &BuilderWrapper =
  234. static_cast<const PassManagerBuilderWrapper&>(Builder);
  235. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  236. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  237. }
  238. #endif // MS_ENABLE_INSTR - HLSL Change
  239. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  240. const CodeGenOptions &CodeGenOpts) {
  241. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  242. if (!CodeGenOpts.SimplifyLibCalls)
  243. TLII->disableAllFunctions();
  244. switch (CodeGenOpts.getVecLib()) {
  245. case CodeGenOptions::Accelerate:
  246. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  247. break;
  248. default:
  249. break;
  250. }
  251. return TLII;
  252. }
  253. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  254. legacy::PassManager *MPM) {
  255. llvm::SymbolRewriter::RewriteDescriptorList DL;
  256. llvm::SymbolRewriter::RewriteMapParser MapParser;
  257. for (const auto &MapFile : Opts.RewriteMapFiles)
  258. MapParser.parse(MapFile, &DL);
  259. MPM->add(createRewriteSymbolsPass(DL));
  260. }
  261. void EmitAssemblyHelper::CreatePasses() {
  262. unsigned OptLevel = CodeGenOpts.OptimizationLevel;
  263. CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
  264. // Handle disabling of LLVM optimization, where we want to preserve the
  265. // internal module before any optimization.
  266. if (CodeGenOpts.DisableLLVMOpts || CodeGenOpts.HLSLHighLevel) { // HLSL Change
  267. OptLevel = 0;
  268. // HLSL Change Begins.
  269. // HLSL always inline.
  270. if (!LangOpts.HLSL || CodeGenOpts.HLSLHighLevel)
  271. Inlining = CodeGenOpts.NoInlining;
  272. // HLSL Change Ends.
  273. }
  274. PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
  275. PMBuilder.OptLevel = OptLevel;
  276. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  277. PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
  278. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  279. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  280. PMBuilder.HLSLHighLevel = CodeGenOpts.HLSLHighLevel; // HLSL Change
  281. PMBuilder.HLSLExtensionsCodeGen = CodeGenOpts.HLSLExtensionsCodegen.get(); // HLSL Change
  282. PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
  283. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  284. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  285. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  286. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  287. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  288. addAddDiscriminatorsPass);
  289. if (!CodeGenOpts.SampleProfileFile.empty())
  290. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  291. addSampleProfileLoaderPass);
  292. // In ObjC ARC mode, add the main ARC optimization passes.
  293. #ifdef MS_ENABLE_OBJCARC // HLSL Change
  294. if (LangOpts.ObjCAutoRefCount) {
  295. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  296. addObjCARCExpandPass);
  297. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  298. addObjCARCAPElimPass);
  299. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  300. addObjCARCOptPass);
  301. }
  302. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  303. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  304. addBoundsCheckingPass);
  305. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  306. addBoundsCheckingPass);
  307. }
  308. #endif // MS_ENABLE_OBJCARC - HLSL Change
  309. #ifdef MS_ENABLE_INSTR // HLSL Change
  310. if (CodeGenOpts.SanitizeCoverageType ||
  311. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  312. CodeGenOpts.SanitizeCoverageTraceCmp) {
  313. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  314. addSanitizerCoveragePass);
  315. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  316. addSanitizerCoveragePass);
  317. }
  318. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  319. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  320. addAddressSanitizerPasses);
  321. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  322. addAddressSanitizerPasses);
  323. }
  324. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  325. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  326. addKernelAddressSanitizerPasses);
  327. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  328. addKernelAddressSanitizerPasses);
  329. }
  330. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  331. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  332. addMemorySanitizerPass);
  333. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  334. addMemorySanitizerPass);
  335. }
  336. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  337. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  338. addThreadSanitizerPass);
  339. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  340. addThreadSanitizerPass);
  341. }
  342. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  343. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  344. addDataFlowSanitizerPass);
  345. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  346. addDataFlowSanitizerPass);
  347. }
  348. #endif // MS_ENABLE_INSTR - HLSL Change
  349. // Figure out TargetLibraryInfo.
  350. Triple TargetTriple(TheModule->getTargetTriple());
  351. PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
  352. switch (Inlining) {
  353. case CodeGenOptions::NoInlining: break;
  354. case CodeGenOptions::NormalInlining: {
  355. PMBuilder.Inliner =
  356. createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
  357. break;
  358. }
  359. case CodeGenOptions::OnlyAlwaysInlining:
  360. // Respect always_inline.
  361. if (OptLevel == 0)
  362. // Do not insert lifetime intrinsics at -O0.
  363. PMBuilder.Inliner = createAlwaysInlinerPass(false);
  364. else
  365. PMBuilder.Inliner = createAlwaysInlinerPass();
  366. break;
  367. }
  368. // Set up the per-function pass manager.
  369. legacy::FunctionPassManager *FPM = getPerFunctionPasses();
  370. if (CodeGenOpts.VerifyModule)
  371. FPM->add(createVerifierPass());
  372. PMBuilder.populateFunctionPassManager(*FPM);
  373. // Set up the per-module pass manager.
  374. legacy::PassManager *MPM = getPerModulePasses();
  375. if (!CodeGenOpts.RewriteMapFiles.empty())
  376. addSymbolRewriterPass(CodeGenOpts, MPM);
  377. #ifdef MS_ENABLE_INSTR // HLSL Change
  378. if (!CodeGenOpts.DisableGCov &&
  379. (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
  380. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  381. // LLVM's -default-gcov-version flag is set to something invalid.
  382. GCOVOptions Options;
  383. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  384. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  385. memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
  386. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  387. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  388. Options.FunctionNamesInData =
  389. !CodeGenOpts.CoverageNoFunctionNamesInData;
  390. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  391. MPM->add(createGCOVProfilerPass(Options));
  392. if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
  393. MPM->add(createStripSymbolsPass(true));
  394. }
  395. if (CodeGenOpts.ProfileInstrGenerate) {
  396. InstrProfOptions Options;
  397. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  398. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  399. MPM->add(createInstrProfilingPass(Options));
  400. }
  401. #endif
  402. PMBuilder.populateModulePassManager(*MPM);
  403. }
  404. TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  405. // Create the TargetMachine for generating code.
  406. std::string Error;
  407. std::string Triple = TheModule->getTargetTriple();
  408. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  409. if (!TheTarget) {
  410. if (MustCreateTM)
  411. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  412. return nullptr;
  413. }
  414. unsigned CodeModel =
  415. llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  416. .Case("small", llvm::CodeModel::Small)
  417. .Case("kernel", llvm::CodeModel::Kernel)
  418. .Case("medium", llvm::CodeModel::Medium)
  419. .Case("large", llvm::CodeModel::Large)
  420. .Case("default", llvm::CodeModel::Default)
  421. .Default(~0u);
  422. assert(CodeModel != ~0u && "invalid code model!");
  423. llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
  424. #if 0 // HLSL Change - no global state mutation on per-instance work
  425. SmallVector<const char *, 16> BackendArgs;
  426. BackendArgs.push_back("clang"); // Fake program name.
  427. if (!CodeGenOpts.DebugPass.empty()) {
  428. BackendArgs.push_back("-debug-pass");
  429. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  430. }
  431. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  432. BackendArgs.push_back("-limit-float-precision");
  433. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  434. }
  435. for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
  436. BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
  437. BackendArgs.push_back(nullptr);
  438. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  439. BackendArgs.data());
  440. #endif // HLSL Change
  441. std::string FeaturesStr;
  442. if (!TargetOpts.Features.empty()) {
  443. #if 0 // HLSL Change
  444. SubtargetFeatures Features;
  445. for (const std::string &Feature : TargetOpts.Features)
  446. Features.AddFeature(Feature);
  447. FeaturesStr = Features.getString();
  448. #endif // HLSL Change
  449. }
  450. llvm::Reloc::Model RM = llvm::Reloc::Default;
  451. if (CodeGenOpts.RelocationModel == "static") {
  452. RM = llvm::Reloc::Static;
  453. } else if (CodeGenOpts.RelocationModel == "pic") {
  454. RM = llvm::Reloc::PIC_;
  455. } else {
  456. assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
  457. "Invalid PIC model!");
  458. RM = llvm::Reloc::DynamicNoPIC;
  459. }
  460. CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
  461. switch (CodeGenOpts.OptimizationLevel) {
  462. default: break;
  463. case 0: OptLevel = CodeGenOpt::None; break;
  464. case 3: OptLevel = CodeGenOpt::Aggressive; break;
  465. }
  466. llvm::TargetOptions Options;
  467. if (!TargetOpts.Reciprocals.empty())
  468. Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
  469. Options.ThreadModel =
  470. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  471. .Case("posix", llvm::ThreadModel::POSIX)
  472. .Case("single", llvm::ThreadModel::Single);
  473. if (CodeGenOpts.DisableIntegratedAS)
  474. Options.DisableIntegratedAS = true;
  475. if (CodeGenOpts.CompressDebugSections)
  476. Options.CompressDebugSections = true;
  477. if (CodeGenOpts.UseInitArray)
  478. Options.UseInitArray = true;
  479. // Set float ABI type.
  480. if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
  481. Options.FloatABIType = llvm::FloatABI::Soft;
  482. else if (CodeGenOpts.FloatABI == "hard")
  483. Options.FloatABIType = llvm::FloatABI::Hard;
  484. else {
  485. assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
  486. Options.FloatABIType = llvm::FloatABI::Default;
  487. }
  488. // Set FP fusion mode.
  489. switch (CodeGenOpts.getFPContractMode()) {
  490. case CodeGenOptions::FPC_Off:
  491. Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
  492. break;
  493. case CodeGenOptions::FPC_On:
  494. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  495. break;
  496. case CodeGenOptions::FPC_Fast:
  497. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  498. break;
  499. }
  500. Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
  501. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  502. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  503. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  504. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  505. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  506. Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
  507. Options.FunctionSections = CodeGenOpts.FunctionSections;
  508. Options.DataSections = CodeGenOpts.DataSections;
  509. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  510. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  511. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  512. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  513. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  514. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  515. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  516. Options.MCOptions.ABIName = TargetOpts.ABI;
  517. TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
  518. FeaturesStr, Options,
  519. RM, CM, OptLevel);
  520. return TM;
  521. }
  522. bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
  523. raw_pwrite_stream &OS) {
  524. // Create the code generator passes.
  525. legacy::PassManager *PM = getCodeGenPasses();
  526. // Add LibraryInfo.
  527. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  528. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  529. createTLII(TargetTriple, CodeGenOpts));
  530. PM->add(new TargetLibraryInfoWrapperPass(*TLII));
  531. // Normal mode, emit a .s or .o file by running the code generator. Note,
  532. // this also adds codegenerator level optimization passes.
  533. TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
  534. if (Action == Backend_EmitObj)
  535. CGFT = TargetMachine::CGFT_ObjectFile;
  536. else if (Action == Backend_EmitMCNull)
  537. CGFT = TargetMachine::CGFT_Null;
  538. else
  539. assert(Action == Backend_EmitAssembly && "Invalid action!");
  540. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  541. // "codegen" passes so that it isn't run multiple times when there is
  542. // inlining happening.
  543. #ifdef MS_ENABLE_OBJCARC // HLSL Change
  544. if (CodeGenOpts.OptimizationLevel > 0)
  545. PM->add(createObjCARCContractPass());
  546. #endif // HLSL Change
  547. if (TM->addPassesToEmitFile(*PM, OS, CGFT,
  548. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  549. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  550. return false;
  551. }
  552. return true;
  553. }
  554. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  555. raw_pwrite_stream *OS) {
  556. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  557. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  558. Action != Backend_EmitBC &&
  559. Action != Backend_EmitPasses &&
  560. Action != Backend_EmitLL);
  561. if (!TM)
  562. TM.reset(CreateTargetMachine(UsesCodeGen));
  563. if (UsesCodeGen && !TM)
  564. return;
  565. if (TM)
  566. TheModule->setDataLayout(*TM->getDataLayout());
  567. CreatePasses();
  568. switch (Action) {
  569. case Backend_EmitNothing:
  570. case Backend_EmitPasses: // HLSL Change
  571. break;
  572. case Backend_EmitBC:
  573. getPerModulePasses()->add(
  574. createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
  575. break;
  576. case Backend_EmitLL:
  577. getPerModulePasses()->add(
  578. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  579. break;
  580. default:
  581. if (!AddEmitPasses(Action, *OS))
  582. return;
  583. }
  584. // Before executing passes, print the final values of the LLVM options.
  585. cl::PrintOptionValues();
  586. // HLSL Change Starts
  587. if (Action == Backend_EmitPasses) {
  588. if (PerFunctionPasses) {
  589. *OS << "# Per-function passes\n"
  590. "-opt-fn-passes\n";
  591. *OS << PerFunctionPassesConfigOS.str();
  592. }
  593. if (PerModulePasses) {
  594. *OS << "# Per-module passes\n"
  595. "-opt-mod-passes\n";
  596. *OS << PerModulePassesConfigOS.str();
  597. }
  598. if (CodeGenPasses) {
  599. *OS << "# Code generation passes\n"
  600. "-opt-mod-passes\n";
  601. *OS << CodeGenPassesConfigOS.str();
  602. }
  603. return;
  604. }
  605. // HLSL Change Ends
  606. // Run passes. For now we do all passes at once, but eventually we
  607. // would like to have the option of streaming code generation.
  608. if (PerFunctionPasses) {
  609. PrettyStackTraceString CrashInfo("Per-function optimization");
  610. PerFunctionPasses->doInitialization();
  611. for (Function &F : *TheModule)
  612. if (!F.isDeclaration())
  613. PerFunctionPasses->run(F);
  614. PerFunctionPasses->doFinalization();
  615. }
  616. if (PerModulePasses) {
  617. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  618. PerModulePasses->run(*TheModule);
  619. }
  620. if (CodeGenPasses) {
  621. PrettyStackTraceString CrashInfo("Code generation");
  622. CodeGenPasses->run(*TheModule);
  623. }
  624. }
  625. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  626. const CodeGenOptions &CGOpts,
  627. const clang::TargetOptions &TOpts,
  628. const LangOptions &LOpts, StringRef TDesc,
  629. Module *M, BackendAction Action,
  630. raw_pwrite_stream *OS) {
  631. EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
  632. AsmHelper.EmitAssembly(Action, OS);
  633. // If an optional clang TargetInfo description string was passed in, use it to
  634. // verify the LLVM TargetMachine's DataLayout.
  635. if (AsmHelper.TM && !TDesc.empty()) {
  636. std::string DLDesc =
  637. AsmHelper.TM->getDataLayout()->getStringRepresentation();
  638. if (DLDesc != TDesc) {
  639. unsigned DiagID = Diags.getCustomDiagID(
  640. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  641. "expected target description '%1'");
  642. Diags.Report(DiagID) << DLDesc << TDesc;
  643. }
  644. }
  645. }