blob: ab65801ce56b49d77e5a80e002e21385916f5cf5 [file] [log] [blame]
Daniel Dunbar897c6762010-06-07 23:20:08 +00001//===--- 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
Daniel Dunbar9b414d32010-06-15 17:48:49 +000010#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000012#include "clang/Basic/LangOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000013#include "clang/Basic/TargetOptions.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000014#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000016#include "llvm/Analysis/Verifier.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000017#include "llvm/Assembly/PrintModulePass.h"
18#include "llvm/Bitcode/ReaderWriter.h"
19#include "llvm/CodeGen/RegAllocRegistry.h"
20#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Module.h"
Evan Cheng693769c2011-06-29 01:14:32 +000023#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "llvm/PassManager.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/FormattedStream.h"
27#include "llvm/Support/PrettyStackTrace.h"
Evan Chenga6b40452011-08-24 18:09:14 +000028#include "llvm/Support/TargetRegistry.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000029#include "llvm/Support/Timer.h"
30#include "llvm/Support/raw_ostream.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000031#include "llvm/Target/TargetLibraryInfo.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000032#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetOptions.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000034#include "llvm/Transforms/IPO.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/Transforms/Instrumentation.h"
Michael Gottesman23d5b092013-01-28 01:36:00 +000037#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000038#include "llvm/Transforms/Scalar.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000039using namespace clang;
40using namespace llvm;
41
42namespace {
43
44class EmitAssemblyHelper {
David Blaikied6471f72011-09-25 23:23:43 +000045 DiagnosticsEngine &Diags;
Daniel Dunbar897c6762010-06-07 23:20:08 +000046 const CodeGenOptions &CodeGenOpts;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +000047 const clang::TargetOptions &TargetOpts;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000048 const LangOptions &LangOpts;
Daniel Dunbar897c6762010-06-07 23:20:08 +000049 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000050
51 Timer CodeGenerationTime;
52
Daniel Dunbardb2f2372010-09-17 07:35:16 +000053 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000054 mutable PassManager *PerModulePasses;
55 mutable FunctionPassManager *PerFunctionPasses;
56
57private:
Nadav Rotemfa60be02012-10-24 00:53:38 +000058 PassManager *getCodeGenPasses(TargetMachine *TM) const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000059 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000060 CodeGenPasses = new PassManager();
Micah Villmow25a6a842012-10-08 16:25:52 +000061 CodeGenPasses->add(new DataLayout(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000062 if (TM)
63 TM->addAnalysisPasses(*CodeGenPasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000064 }
65 return CodeGenPasses;
66 }
67
Nadav Rotemfa60be02012-10-24 00:53:38 +000068 PassManager *getPerModulePasses(TargetMachine *TM) const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000069 if (!PerModulePasses) {
70 PerModulePasses = new PassManager();
Micah Villmow25a6a842012-10-08 16:25:52 +000071 PerModulePasses->add(new DataLayout(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000072 if (TM)
73 TM->addAnalysisPasses(*PerModulePasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000074 }
75 return PerModulePasses;
76 }
77
Nadav Rotemfa60be02012-10-24 00:53:38 +000078 FunctionPassManager *getPerFunctionPasses(TargetMachine *TM) const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000079 if (!PerFunctionPasses) {
80 PerFunctionPasses = new FunctionPassManager(TheModule);
Micah Villmow25a6a842012-10-08 16:25:52 +000081 PerFunctionPasses->add(new DataLayout(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000082 if (TM)
83 TM->addAnalysisPasses(*PerFunctionPasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000084 }
85 return PerFunctionPasses;
86 }
87
Nadav Rotemfa60be02012-10-24 00:53:38 +000088
89 void CreatePasses(TargetMachine *TM);
90
Nadav Rotem129369d2012-10-24 03:52:31 +000091 /// CreateTargetMachine - Generates the TargetMachine.
92 /// Returns Null if it is unable to create the target machine.
93 /// Some of our clang tests specify triples which are not built
94 /// into clang. This is okay because these tests check the generated
95 /// IR, and they require DataLayout which depends on the triple.
96 /// In this case, we allow this method to fail and not report an error.
97 /// When MustCreateTM is used, we print an error if we are unable to load
98 /// the requested target.
99 TargetMachine *CreateTargetMachine(bool MustCreateTM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000100
101 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
102 ///
103 /// \return True on success.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000104 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS,
105 TargetMachine *TM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000106
107public:
David Blaikied6471f72011-09-25 23:23:43 +0000108 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000109 const CodeGenOptions &CGOpts,
110 const clang::TargetOptions &TOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000111 const LangOptions &LOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000112 Module *M)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000113 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000114 TheModule(M), CodeGenerationTime("Code Generation Time"),
Daniel Dunbar897c6762010-06-07 23:20:08 +0000115 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
116
117 ~EmitAssemblyHelper() {
118 delete CodeGenPasses;
119 delete PerModulePasses;
120 delete PerFunctionPasses;
121 }
122
123 void EmitAssembly(BackendAction Action, raw_ostream *OS);
124};
125
Alexey Samsonove8c03222012-12-28 09:31:34 +0000126// We need this wrapper to access LangOpts and CGOpts from extension functions
127// that we add to the PassManagerBuilder.
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000128class PassManagerBuilderWrapper : public PassManagerBuilder {
129public:
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000130 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
131 const LangOptions &LangOpts)
132 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
133 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000134 const LangOptions &getLangOpts() const { return LangOpts; }
135private:
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000136 const CodeGenOptions &CGOpts;
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000137 const LangOptions &LangOpts;
138};
139
Daniel Dunbar897c6762010-06-07 23:20:08 +0000140}
141
Dan Gohmana8398ea2012-01-17 20:54:51 +0000142static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
143 if (Builder.OptLevel > 0)
144 PM.add(createObjCARCAPElimPass());
145}
146
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000147static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148 if (Builder.OptLevel > 0)
149 PM.add(createObjCARCExpandPass());
150}
151
152static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153 if (Builder.OptLevel > 0)
154 PM.add(createObjCARCOptPass());
155}
156
Nuno Lopesdef18492012-05-22 17:19:45 +0000157static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
158 PassManagerBase &PM) {
Joey Gouly85489082012-11-23 10:39:49 +0000159 PM.add(createBoundsCheckingPass());
Nuno Lopesdef18492012-05-22 17:19:45 +0000160}
161
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000162static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
163 PassManagerBase &PM) {
164 const PassManagerBuilderWrapper &BuilderWrapper =
165 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000166 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000167 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonov4bdc6042013-01-20 13:12:12 +0000168 PM.add(createAddressSanitizerFunctionPass(
169 LangOpts.Sanitize.InitOrder,
170 LangOpts.Sanitize.UseAfterReturn,
171 LangOpts.Sanitize.UseAfterScope,
172 CGOpts.SanitizerBlacklistFile,
173 CGOpts.SanitizeAddressZeroBaseShadow));
174 PM.add(createAddressSanitizerModulePass(
175 LangOpts.Sanitize.InitOrder,
176 CGOpts.SanitizerBlacklistFile,
177 CGOpts.SanitizeAddressZeroBaseShadow));
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000178}
179
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000180static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
181 PassManagerBase &PM) {
Evgeniy Stepanov34ef11b2012-12-24 08:42:34 +0000182 const PassManagerBuilderWrapper &BuilderWrapper =
183 static_cast<const PassManagerBuilderWrapper&>(Builder);
184 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov4bdc6042013-01-20 13:12:12 +0000185 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins,
Alexey Samsonove8c03222012-12-28 09:31:34 +0000186 CGOpts.SanitizerBlacklistFile));
Evgeniy Stepanova8d39042013-01-31 09:53:29 +0000187
188 // MemorySanitizer inserts complex instrumentation that mostly follows
189 // the logic of the original code, but operates on "shadow" values.
190 // It can benefit from re-running some general purpose optimization passes.
191 if (Builder.OptLevel > 0) {
192 PM.add(createEarlyCSEPass());
193 PM.add(createReassociatePass());
194 PM.add(createLICMPass());
195 PM.add(createGVNPass());
196 PM.add(createInstructionCombiningPass());
197 PM.add(createDeadStoreEliminationPass());
198 }
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000199}
200
Kostya Serebryany3c931222012-03-01 22:27:08 +0000201static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
202 PassManagerBase &PM) {
Alexey Samsonove8c03222012-12-28 09:31:34 +0000203 const PassManagerBuilderWrapper &BuilderWrapper =
204 static_cast<const PassManagerBuilderWrapper&>(Builder);
205 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
206 PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile));
Kostya Serebryany3c931222012-03-01 22:27:08 +0000207}
208
Nadav Rotemfa60be02012-10-24 00:53:38 +0000209void EmitAssemblyHelper::CreatePasses(TargetMachine *TM) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000210 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000211 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000212
213 // Handle disabling of LLVM optimization, where we want to preserve the
214 // internal module before any optimization.
215 if (CodeGenOpts.DisableLLVMOpts) {
216 OptLevel = 0;
217 Inlining = CodeGenOpts.NoInlining;
218 }
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000219
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000220 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
Chris Lattner9ca02e52011-05-21 23:50:44 +0000221 PMBuilder.OptLevel = OptLevel;
222 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Andrew Trick6445d622011-04-05 18:49:32 +0000223
Chris Lattner9ca02e52011-05-21 23:50:44 +0000224 PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
225 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
226 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000227
228 // In ObjC ARC mode, add the main ARC optimization passes.
229 if (LangOpts.ObjCAutoRefCount) {
230 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
231 addObjCARCExpandPass);
Dan Gohmana8398ea2012-01-17 20:54:51 +0000232 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
233 addObjCARCAPElimPass);
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000234 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
235 addObjCARCOptPass);
236 }
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000237
Will Dietz4f45bc02013-01-18 11:30:38 +0000238 if (LangOpts.Sanitize.Bounds) {
Nuno Lopesdef18492012-05-22 17:19:45 +0000239 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
240 addBoundsCheckingPass);
241 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
242 addBoundsCheckingPass);
243 }
244
Will Dietz4f45bc02013-01-18 11:30:38 +0000245 if (LangOpts.Sanitize.Address) {
Kostya Serebryanyba1f0402012-10-15 14:22:56 +0000246 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000247 addAddressSanitizerPasses);
Kostya Serebryanye5dd2ea2011-11-30 22:20:21 +0000248 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000249 addAddressSanitizerPasses);
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000250 }
Kostya Serebryany3c931222012-03-01 22:27:08 +0000251
Will Dietz4f45bc02013-01-18 11:30:38 +0000252 if (LangOpts.Sanitize.Memory) {
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000253 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
254 addMemorySanitizerPass);
255 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
256 addMemorySanitizerPass);
257 }
258
Will Dietz4f45bc02013-01-18 11:30:38 +0000259 if (LangOpts.Sanitize.Thread) {
Kostya Serebryanye78ec3e2012-03-23 23:25:23 +0000260 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany3c931222012-03-01 22:27:08 +0000261 addThreadSanitizerPass);
262 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
263 addThreadSanitizerPass);
264 }
265
Chris Lattner33c09d52011-05-21 20:40:11 +0000266 // Figure out TargetLibraryInfo.
Bill Wendling3621b312011-05-17 23:06:23 +0000267 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattner9ca02e52011-05-21 23:50:44 +0000268 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000269 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattner9ca02e52011-05-21 23:50:44 +0000270 PMBuilder.LibraryInfo->disableAllFunctions();
Chris Lattner33c09d52011-05-21 20:40:11 +0000271
Daniel Dunbar897c6762010-06-07 23:20:08 +0000272 switch (Inlining) {
273 case CodeGenOptions::NoInlining: break;
274 case CodeGenOptions::NormalInlining: {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000275 // FIXME: Derive these constants in a principled fashion.
276 unsigned Threshold = 225;
Chris Lattner33c09d52011-05-21 20:40:11 +0000277 if (CodeGenOpts.OptimizeSize == 1) // -Os
Daniel Dunbar897c6762010-06-07 23:20:08 +0000278 Threshold = 75;
Chris Lattner33c09d52011-05-21 20:40:11 +0000279 else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Bob Wilsona0fa2032011-04-29 22:49:50 +0000280 Threshold = 25;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000281 else if (OptLevel > 2)
282 Threshold = 275;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000283 PMBuilder.Inliner = createFunctionInliningPass(Threshold);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000284 break;
285 }
286 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner33c09d52011-05-21 20:40:11 +0000287 // Respect always_inline.
Chad Rosier98759622012-02-25 02:56:13 +0000288 if (OptLevel == 0)
289 // Do not insert lifetime intrinsics at -O0.
290 PMBuilder.Inliner = createAlwaysInlinerPass(false);
291 else
292 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000293 break;
294 }
295
Chris Lattner33c09d52011-05-21 20:40:11 +0000296 // Set up the per-function pass manager.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000297 FunctionPassManager *FPM = getPerFunctionPasses(TM);
Chris Lattner33c09d52011-05-21 20:40:11 +0000298 if (CodeGenOpts.VerifyModule)
299 FPM->add(createVerifierPass());
300 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trick6445d622011-04-05 18:49:32 +0000301
Chris Lattner33c09d52011-05-21 20:40:11 +0000302 // Set up the per-module pass manager.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000303 PassManager *MPM = getPerModulePasses(TM);
Chris Lattnerdf619762011-02-18 22:20:38 +0000304
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000305 if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
306 MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
Bill Wendling3621b312011-05-17 23:06:23 +0000307 CodeGenOpts.EmitGcovArcs,
Nick Lewycky9789d0d22013-03-07 08:42:27 +0000308 CodeGenOpts.CoverageVersion,
309 CodeGenOpts.CoverageExtraChecksum,
Nick Lewyckyf4086eb2013-02-27 06:22:58 +0000310 CodeGenOpts.DisableRedZone,
Nick Lewycky9789d0d22013-03-07 08:42:27 +0000311 CodeGenOpts.CoverageFunctionNamesInData));
Bill Wendling3621b312011-05-17 23:06:23 +0000312
Douglas Gregor4cdad312012-10-23 20:05:01 +0000313 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000314 MPM->add(createStripSymbolsPass(true));
315 }
Nadav Rotem129369d2012-10-24 03:52:31 +0000316
Chris Lattner33c09d52011-05-21 20:40:11 +0000317 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000318}
319
Nadav Rotem129369d2012-10-24 03:52:31 +0000320TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000321 // Create the TargetMachine for generating code.
322 std::string Error;
323 std::string Triple = TheModule->getTargetTriple();
324 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
325 if (!TheTarget) {
Nadav Rotem129369d2012-10-24 03:52:31 +0000326 if (MustCreateTM)
327 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Nadav Rotemfa60be02012-10-24 00:53:38 +0000328 return 0;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000329 }
330
331 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
332 // being gross, this is also totally broken if we ever care about
333 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000334
Daniel Dunbar897c6762010-06-07 23:20:08 +0000335 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
336
337 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
338 TargetMachine::setDataSections (CodeGenOpts.DataSections);
339
340 // FIXME: Parse this earlier.
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000341 llvm::CodeModel::Model CM;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000342 if (CodeGenOpts.CodeModel == "small") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000343 CM = llvm::CodeModel::Small;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000344 } else if (CodeGenOpts.CodeModel == "kernel") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000345 CM = llvm::CodeModel::Kernel;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000346 } else if (CodeGenOpts.CodeModel == "medium") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000347 CM = llvm::CodeModel::Medium;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000348 } else if (CodeGenOpts.CodeModel == "large") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000349 CM = llvm::CodeModel::Large;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000350 } else {
351 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000352 CM = llvm::CodeModel::Default;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000353 }
354
David Blaikie6bd17d22012-02-07 19:36:38 +0000355 SmallVector<const char *, 16> BackendArgs;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000356 BackendArgs.push_back("clang"); // Fake program name.
357 if (!CodeGenOpts.DebugPass.empty()) {
358 BackendArgs.push_back("-debug-pass");
359 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
360 }
361 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
362 BackendArgs.push_back("-limit-float-precision");
363 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
364 }
365 if (llvm::TimePassesIsEnabled)
366 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000367 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
368 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Chad Rosier1b906052011-08-26 00:26:29 +0000369 if (CodeGenOpts.NoGlobalMerge)
370 BackendArgs.push_back("-global-merge=false");
Daniel Dunbar897c6762010-06-07 23:20:08 +0000371 BackendArgs.push_back(0);
372 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
David Blaikie6bd17d22012-02-07 19:36:38 +0000373 BackendArgs.data());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000374
375 std::string FeaturesStr;
Evan Cheng368691e2011-06-30 02:06:32 +0000376 if (TargetOpts.Features.size()) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000377 SubtargetFeatures Features;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000378 for (std::vector<std::string>::const_iterator
379 it = TargetOpts.Features.begin(),
380 ie = TargetOpts.Features.end(); it != ie; ++it)
381 Features.AddFeature(*it);
382 FeaturesStr = Features.getString();
383 }
Evan Cheng2860e302011-07-19 06:37:41 +0000384
385 llvm::Reloc::Model RM = llvm::Reloc::Default;
386 if (CodeGenOpts.RelocationModel == "static") {
387 RM = llvm::Reloc::Static;
388 } else if (CodeGenOpts.RelocationModel == "pic") {
389 RM = llvm::Reloc::PIC_;
390 } else {
391 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
392 "Invalid PIC model!");
393 RM = llvm::Reloc::DynamicNoPIC;
394 }
395
Evan Cheng9254bf72011-11-16 08:38:55 +0000396 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
397 switch (CodeGenOpts.OptimizationLevel) {
398 default: break;
399 case 0: OptLevel = CodeGenOpt::None; break;
400 case 3: OptLevel = CodeGenOpt::Aggressive; break;
401 }
402
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000403 llvm::TargetOptions Options;
404
405 // Set frame pointer elimination mode.
406 if (!CodeGenOpts.DisableFPElim) {
407 Options.NoFramePointerElim = false;
408 Options.NoFramePointerElimNonLeaf = false;
409 } else if (CodeGenOpts.OmitLeafFramePointer) {
410 Options.NoFramePointerElim = false;
411 Options.NoFramePointerElimNonLeaf = true;
412 } else {
413 Options.NoFramePointerElim = true;
414 Options.NoFramePointerElimNonLeaf = true;
415 }
416
Rafael Espindola8af669f2012-06-19 01:26:10 +0000417 if (CodeGenOpts.UseInitArray)
418 Options.UseInitArray = true;
419
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000420 // Set float ABI type.
421 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
422 Options.FloatABIType = llvm::FloatABI::Soft;
423 else if (CodeGenOpts.FloatABI == "hard")
424 Options.FloatABIType = llvm::FloatABI::Hard;
425 else {
426 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
427 Options.FloatABIType = llvm::FloatABI::Default;
428 }
429
Lang Hamesc9686712012-07-06 00:59:19 +0000430 // Set FP fusion mode.
Lang Hames931c0832012-11-15 07:51:26 +0000431 switch (CodeGenOpts.getFPContractMode()) {
432 case CodeGenOptions::FPC_Off:
Lang Hamesc9686712012-07-06 00:59:19 +0000433 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
434 break;
Lang Hames931c0832012-11-15 07:51:26 +0000435 case CodeGenOptions::FPC_On:
Lang Hamesc9686712012-07-06 00:59:19 +0000436 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
437 break;
Lang Hames931c0832012-11-15 07:51:26 +0000438 case CodeGenOptions::FPC_Fast:
Lang Hamesc9686712012-07-06 00:59:19 +0000439 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
Nadav Rotem25030c42012-10-19 04:15:32 +0000440 break;
Lang Hamesc9686712012-07-06 00:59:19 +0000441 }
442
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000443 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
444 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
445 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
446 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
447 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
448 Options.UseSoftFloat = CodeGenOpts.SoftFloat;
Nick Lewycky4e785c92011-12-06 03:33:03 +0000449 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
450 Options.RealignStack = CodeGenOpts.StackRealignment;
Nick Lewycky1db772b2012-01-23 08:29:12 +0000451 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Bob Wilson71fd6cc2012-02-03 06:27:22 +0000452 Options.TrapFuncName = CodeGenOpts.TrapFuncName;
Chandler Carruth5081de52012-04-08 21:09:51 +0000453 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
Chad Rosiera7afeb02012-08-21 16:16:06 +0000454 Options.SSPBufferSize = CodeGenOpts.SSPBufferSize;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000455
Evan Cheng368691e2011-06-30 02:06:32 +0000456 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000457 FeaturesStr, Options,
458 RM, CM, OptLevel);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000459
460 if (CodeGenOpts.RelaxAll)
461 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000462 if (CodeGenOpts.SaveTempLabels)
463 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000464 if (CodeGenOpts.NoDwarf2CFIAsm)
465 TM->setMCUseCFI(false);
Nick Lewyckyaaf2f362011-10-31 01:06:42 +0000466 if (!CodeGenOpts.NoDwarfDirectoryAsm)
467 TM->setMCUseDwarfDirectory(true);
Nick Lewyckyc3b90142011-06-21 00:14:18 +0000468 if (CodeGenOpts.NoExecStack)
469 TM->setMCNoExecStack(true);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000470
Nadav Rotemfa60be02012-10-24 00:53:38 +0000471 return TM;
472}
473
474bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
475 formatted_raw_ostream &OS,
476 TargetMachine *TM) {
477
Daniel Dunbar897c6762010-06-07 23:20:08 +0000478 // Create the code generator passes.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000479 PassManager *PM = getCodeGenPasses(TM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000480
Chad Rosier3f3335d2012-02-29 20:14:59 +0000481 // Add LibraryInfo.
Daniel Dunbarcbbe2c02012-10-19 20:10:10 +0000482 llvm::Triple TargetTriple(TheModule->getTargetTriple());
483 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chad Rosier3f3335d2012-02-29 20:14:59 +0000484 if (!CodeGenOpts.SimplifyLibCalls)
485 TLI->disableAllFunctions();
486 PM->add(TLI);
487
Chandler Carruthd938e872013-01-07 01:38:01 +0000488 // Add Target specific analysis passes.
489 TM->addAnalysisPasses(*PM);
Nadav Rotem25030c42012-10-19 04:15:32 +0000490
Daniel Dunbar897c6762010-06-07 23:20:08 +0000491 // Normal mode, emit a .s or .o file by running the code generator. Note,
492 // this also adds codegenerator level optimization passes.
493 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
494 if (Action == Backend_EmitObj)
495 CGFT = TargetMachine::CGFT_ObjectFile;
496 else if (Action == Backend_EmitMCNull)
497 CGFT = TargetMachine::CGFT_Null;
498 else
499 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000500
501 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
502 // "codegen" passes so that it isn't run multiple times when there is
503 // inlining happening.
Dan Gohman465a8992012-04-04 21:04:56 +0000504 if (LangOpts.ObjCAutoRefCount &&
505 CodeGenOpts.OptimizationLevel > 0)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000506 PM->add(createObjCARCContractPass());
507
Evan Cheng9254bf72011-11-16 08:38:55 +0000508 if (TM->addPassesToEmitFile(*PM, OS, CGFT,
Daniel Dunbar897c6762010-06-07 23:20:08 +0000509 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
510 Diags.Report(diag::err_fe_unable_to_interface_with_target);
511 return false;
512 }
513
514 return true;
515}
516
517void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
518 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
519 llvm::formatted_raw_ostream FormattedOS;
520
Nadav Rotem129369d2012-10-24 03:52:31 +0000521 bool UsesCodeGen = (Action != Backend_EmitNothing &&
522 Action != Backend_EmitBC &&
523 Action != Backend_EmitLL);
524 TargetMachine *TM = CreateTargetMachine(UsesCodeGen);
Nadav Rotemfa60be02012-10-24 00:53:38 +0000525 CreatePasses(TM);
526
Daniel Dunbar897c6762010-06-07 23:20:08 +0000527 switch (Action) {
528 case Backend_EmitNothing:
529 break;
530
531 case Backend_EmitBC:
Nadav Rotemfa60be02012-10-24 00:53:38 +0000532 getPerModulePasses(TM)->add(createBitcodeWriterPass(*OS));
Daniel Dunbar897c6762010-06-07 23:20:08 +0000533 break;
534
535 case Backend_EmitLL:
536 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Nadav Rotemfa60be02012-10-24 00:53:38 +0000537 getPerModulePasses(TM)->add(createPrintModulePass(&FormattedOS));
Daniel Dunbar897c6762010-06-07 23:20:08 +0000538 break;
539
540 default:
541 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Nadav Rotemfa60be02012-10-24 00:53:38 +0000542 if (!AddEmitPasses(Action, FormattedOS, TM))
Daniel Dunbar897c6762010-06-07 23:20:08 +0000543 return;
544 }
545
Andrew Trick92b5d942011-04-05 18:56:55 +0000546 // Before executing passes, print the final values of the LLVM options.
547 cl::PrintOptionValues();
548
Daniel Dunbar897c6762010-06-07 23:20:08 +0000549 // Run passes. For now we do all passes at once, but eventually we
550 // would like to have the option of streaming code generation.
551
552 if (PerFunctionPasses) {
553 PrettyStackTraceString CrashInfo("Per-function optimization");
554
555 PerFunctionPasses->doInitialization();
556 for (Module::iterator I = TheModule->begin(),
557 E = TheModule->end(); I != E; ++I)
558 if (!I->isDeclaration())
559 PerFunctionPasses->run(*I);
560 PerFunctionPasses->doFinalization();
561 }
562
563 if (PerModulePasses) {
564 PrettyStackTraceString CrashInfo("Per-module optimization passes");
565 PerModulePasses->run(*TheModule);
566 }
567
568 if (CodeGenPasses) {
569 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000570 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000571 }
572}
573
David Blaikied6471f72011-09-25 23:23:43 +0000574void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
575 const CodeGenOptions &CGOpts,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000576 const clang::TargetOptions &TOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000577 const LangOptions &LOpts,
578 Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000579 BackendAction Action, raw_ostream *OS) {
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000580 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000581
582 AsmHelper.EmitAssembly(Action, OS);
583}