blob: fc6c5949d5742c80ba863b0d0ee1ae84e111b4d2 [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"
Stephen Hines651f13c2014-04-23 16:59:28 -070016#include "clang/Frontend/Utils.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070017#include "llvm/ADT/StringSwitch.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070018#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000019#include "llvm/CodeGen/RegAllocRegistry.h"
20#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/DataLayout.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070022#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000023#include "llvm/IR/Module.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070024#include "llvm/IR/Verifier.h"
Evan Cheng693769c2011-06-29 01:14:32 +000025#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "llvm/PassManager.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FormattedStream.h"
29#include "llvm/Support/PrettyStackTrace.h"
Evan Chenga6b40452011-08-24 18:09:14 +000030#include "llvm/Support/TargetRegistry.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000031#include "llvm/Support/Timer.h"
32#include "llvm/Support/raw_ostream.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000033#include "llvm/Target/TargetLibraryInfo.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000034#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000036#include "llvm/Transforms/IPO.h"
37#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/Transforms/Instrumentation.h"
Michael Gottesman23d5b092013-01-28 01:36:00 +000039#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000040#include "llvm/Transforms/Scalar.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070041#include <memory>
Daniel Dunbar897c6762010-06-07 23:20:08 +000042using namespace clang;
43using namespace llvm;
44
45namespace {
46
47class EmitAssemblyHelper {
David Blaikied6471f72011-09-25 23:23:43 +000048 DiagnosticsEngine &Diags;
Daniel Dunbar897c6762010-06-07 23:20:08 +000049 const CodeGenOptions &CodeGenOpts;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +000050 const clang::TargetOptions &TargetOpts;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000051 const LangOptions &LangOpts;
Daniel Dunbar897c6762010-06-07 23:20:08 +000052 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000053
54 Timer CodeGenerationTime;
55
Daniel Dunbardb2f2372010-09-17 07:35:16 +000056 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000057 mutable PassManager *PerModulePasses;
58 mutable FunctionPassManager *PerFunctionPasses;
59
60private:
Stephen Hines651f13c2014-04-23 16:59:28 -070061 PassManager *getCodeGenPasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000062 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000063 CodeGenPasses = new PassManager();
Stephen Hines651f13c2014-04-23 16:59:28 -070064 CodeGenPasses->add(new DataLayoutPass(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000065 if (TM)
66 TM->addAnalysisPasses(*CodeGenPasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000067 }
68 return CodeGenPasses;
69 }
70
Stephen Hines651f13c2014-04-23 16:59:28 -070071 PassManager *getPerModulePasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000072 if (!PerModulePasses) {
73 PerModulePasses = new PassManager();
Stephen Hines651f13c2014-04-23 16:59:28 -070074 PerModulePasses->add(new DataLayoutPass(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000075 if (TM)
76 TM->addAnalysisPasses(*PerModulePasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000077 }
78 return PerModulePasses;
79 }
80
Stephen Hines651f13c2014-04-23 16:59:28 -070081 FunctionPassManager *getPerFunctionPasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000082 if (!PerFunctionPasses) {
83 PerFunctionPasses = new FunctionPassManager(TheModule);
Stephen Hines651f13c2014-04-23 16:59:28 -070084 PerFunctionPasses->add(new DataLayoutPass(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000085 if (TM)
86 TM->addAnalysisPasses(*PerFunctionPasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000087 }
88 return PerFunctionPasses;
89 }
90
Stephen Hines651f13c2014-04-23 16:59:28 -070091 void CreatePasses();
Nadav Rotemfa60be02012-10-24 00:53:38 +000092
Nadav Rotem129369d2012-10-24 03:52:31 +000093 /// CreateTargetMachine - Generates the TargetMachine.
94 /// Returns Null if it is unable to create the target machine.
95 /// Some of our clang tests specify triples which are not built
96 /// into clang. This is okay because these tests check the generated
97 /// IR, and they require DataLayout which depends on the triple.
98 /// In this case, we allow this method to fail and not report an error.
99 /// When MustCreateTM is used, we print an error if we are unable to load
100 /// the requested target.
101 TargetMachine *CreateTargetMachine(bool MustCreateTM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000102
103 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
104 ///
105 /// \return True on success.
Stephen Hines651f13c2014-04-23 16:59:28 -0700106 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000107
108public:
David Blaikied6471f72011-09-25 23:23:43 +0000109 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000110 const CodeGenOptions &CGOpts,
111 const clang::TargetOptions &TOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000112 const LangOptions &LOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000113 Module *M)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000114 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000115 TheModule(M), CodeGenerationTime("Code Generation Time"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700116 CodeGenPasses(nullptr), PerModulePasses(nullptr),
117 PerFunctionPasses(nullptr) {}
Daniel Dunbar897c6762010-06-07 23:20:08 +0000118
119 ~EmitAssemblyHelper() {
120 delete CodeGenPasses;
121 delete PerModulePasses;
122 delete PerFunctionPasses;
Stephen Hines651f13c2014-04-23 16:59:28 -0700123 if (CodeGenOpts.DisableFree)
124 BuryPointer(TM.release());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000125 }
126
Stephen Hines651f13c2014-04-23 16:59:28 -0700127 std::unique_ptr<TargetMachine> TM;
128
Daniel Dunbar897c6762010-06-07 23:20:08 +0000129 void EmitAssembly(BackendAction Action, raw_ostream *OS);
130};
131
Alexey Samsonove8c03222012-12-28 09:31:34 +0000132// We need this wrapper to access LangOpts and CGOpts from extension functions
133// that we add to the PassManagerBuilder.
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000134class PassManagerBuilderWrapper : public PassManagerBuilder {
135public:
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000136 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
137 const LangOptions &LangOpts)
138 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
139 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000140 const LangOptions &getLangOpts() const { return LangOpts; }
141private:
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000142 const CodeGenOptions &CGOpts;
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000143 const LangOptions &LangOpts;
144};
145
Daniel Dunbar897c6762010-06-07 23:20:08 +0000146}
147
Dan Gohmana8398ea2012-01-17 20:54:51 +0000148static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
149 if (Builder.OptLevel > 0)
150 PM.add(createObjCARCAPElimPass());
151}
152
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000153static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
154 if (Builder.OptLevel > 0)
155 PM.add(createObjCARCExpandPass());
156}
157
158static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
159 if (Builder.OptLevel > 0)
160 PM.add(createObjCARCOptPass());
161}
162
Diego Novillob85a9ec2013-11-13 12:22:39 +0000163static void addSampleProfileLoaderPass(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(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
169}
170
Stephen Hines651f13c2014-04-23 16:59:28 -0700171static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
172 PassManagerBase &PM) {
173 PM.add(createAddDiscriminatorsPass());
174}
175
Nuno Lopesdef18492012-05-22 17:19:45 +0000176static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
177 PassManagerBase &PM) {
Joey Gouly85489082012-11-23 10:39:49 +0000178 PM.add(createBoundsCheckingPass());
Nuno Lopesdef18492012-05-22 17:19:45 +0000179}
180
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000181static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
182 PassManagerBase &PM) {
183 const PassManagerBuilderWrapper &BuilderWrapper =
184 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000185 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000186 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonov4bdc6042013-01-20 13:12:12 +0000187 PM.add(createAddressSanitizerFunctionPass(
188 LangOpts.Sanitize.InitOrder,
189 LangOpts.Sanitize.UseAfterReturn,
190 LangOpts.Sanitize.UseAfterScope,
Stephen Hines651f13c2014-04-23 16:59:28 -0700191 CGOpts.SanitizerBlacklistFile));
Alexey Samsonov4bdc6042013-01-20 13:12:12 +0000192 PM.add(createAddressSanitizerModulePass(
193 LangOpts.Sanitize.InitOrder,
Stephen Hines651f13c2014-04-23 16:59:28 -0700194 CGOpts.SanitizerBlacklistFile));
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000195}
196
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000197static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
198 PassManagerBase &PM) {
Evgeniy Stepanov34ef11b2012-12-24 08:42:34 +0000199 const PassManagerBuilderWrapper &BuilderWrapper =
200 static_cast<const PassManagerBuilderWrapper&>(Builder);
201 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov4bdc6042013-01-20 13:12:12 +0000202 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins,
Alexey Samsonove8c03222012-12-28 09:31:34 +0000203 CGOpts.SanitizerBlacklistFile));
Evgeniy Stepanova8d39042013-01-31 09:53:29 +0000204
205 // MemorySanitizer inserts complex instrumentation that mostly follows
206 // the logic of the original code, but operates on "shadow" values.
207 // It can benefit from re-running some general purpose optimization passes.
208 if (Builder.OptLevel > 0) {
209 PM.add(createEarlyCSEPass());
210 PM.add(createReassociatePass());
211 PM.add(createLICMPass());
212 PM.add(createGVNPass());
213 PM.add(createInstructionCombiningPass());
214 PM.add(createDeadStoreEliminationPass());
215 }
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000216}
217
Kostya Serebryany3c931222012-03-01 22:27:08 +0000218static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
219 PassManagerBase &PM) {
Alexey Samsonove8c03222012-12-28 09:31:34 +0000220 const PassManagerBuilderWrapper &BuilderWrapper =
221 static_cast<const PassManagerBuilderWrapper&>(Builder);
222 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
223 PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile));
Kostya Serebryany3c931222012-03-01 22:27:08 +0000224}
225
Peter Collingbourne2eeed712013-08-07 22:47:34 +0000226static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
227 PassManagerBase &PM) {
Peter Collingbourne5d27a512013-08-14 18:54:18 +0000228 const PassManagerBuilderWrapper &BuilderWrapper =
229 static_cast<const PassManagerBuilderWrapper&>(Builder);
230 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
231 PM.add(createDataFlowSanitizerPass(CGOpts.SanitizerBlacklistFile));
Peter Collingbourne2eeed712013-08-07 22:47:34 +0000232}
233
Stephen Hines651f13c2014-04-23 16:59:28 -0700234void EmitAssemblyHelper::CreatePasses() {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000235 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000236 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000237
238 // Handle disabling of LLVM optimization, where we want to preserve the
239 // internal module before any optimization.
240 if (CodeGenOpts.DisableLLVMOpts) {
241 OptLevel = 0;
242 Inlining = CodeGenOpts.NoInlining;
243 }
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000244
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000245 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
Chris Lattner9ca02e52011-05-21 23:50:44 +0000246 PMBuilder.OptLevel = OptLevel;
247 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyfdf137b2013-06-25 01:49:44 +0000248 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
249 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
250 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trick6445d622011-04-05 18:49:32 +0000251
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700252 PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000253 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
254 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Hal Finkelce5b5f12013-11-17 16:03:29 +0000255 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000256
Stephen Hines651f13c2014-04-23 16:59:28 -0700257 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
258 addAddDiscriminatorsPass);
259
Diego Novillob85a9ec2013-11-13 12:22:39 +0000260 if (!CodeGenOpts.SampleProfileFile.empty())
261 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
262 addSampleProfileLoaderPass);
263
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000264 // In ObjC ARC mode, add the main ARC optimization passes.
265 if (LangOpts.ObjCAutoRefCount) {
266 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
267 addObjCARCExpandPass);
Dan Gohmana8398ea2012-01-17 20:54:51 +0000268 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
269 addObjCARCAPElimPass);
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000270 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
271 addObjCARCOptPass);
272 }
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000273
Richard Smith69170e62013-10-22 22:51:04 +0000274 if (LangOpts.Sanitize.LocalBounds) {
Nuno Lopesdef18492012-05-22 17:19:45 +0000275 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
276 addBoundsCheckingPass);
277 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
278 addBoundsCheckingPass);
279 }
280
Will Dietz4f45bc02013-01-18 11:30:38 +0000281 if (LangOpts.Sanitize.Address) {
Kostya Serebryanyba1f0402012-10-15 14:22:56 +0000282 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000283 addAddressSanitizerPasses);
Kostya Serebryanye5dd2ea2011-11-30 22:20:21 +0000284 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000285 addAddressSanitizerPasses);
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000286 }
Kostya Serebryany3c931222012-03-01 22:27:08 +0000287
Will Dietz4f45bc02013-01-18 11:30:38 +0000288 if (LangOpts.Sanitize.Memory) {
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000289 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
290 addMemorySanitizerPass);
291 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
292 addMemorySanitizerPass);
293 }
294
Will Dietz4f45bc02013-01-18 11:30:38 +0000295 if (LangOpts.Sanitize.Thread) {
Kostya Serebryanye78ec3e2012-03-23 23:25:23 +0000296 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany3c931222012-03-01 22:27:08 +0000297 addThreadSanitizerPass);
298 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
299 addThreadSanitizerPass);
300 }
301
Peter Collingbourne2eeed712013-08-07 22:47:34 +0000302 if (LangOpts.Sanitize.DataFlow) {
303 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
304 addDataFlowSanitizerPass);
305 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
306 addDataFlowSanitizerPass);
307 }
308
Chris Lattner33c09d52011-05-21 20:40:11 +0000309 // Figure out TargetLibraryInfo.
Bill Wendling3621b312011-05-17 23:06:23 +0000310 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattner9ca02e52011-05-21 23:50:44 +0000311 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000312 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattner9ca02e52011-05-21 23:50:44 +0000313 PMBuilder.LibraryInfo->disableAllFunctions();
Stephen Hines651f13c2014-04-23 16:59:28 -0700314
Daniel Dunbar897c6762010-06-07 23:20:08 +0000315 switch (Inlining) {
316 case CodeGenOptions::NoInlining: break;
317 case CodeGenOptions::NormalInlining: {
Stephen Hines651f13c2014-04-23 16:59:28 -0700318 PMBuilder.Inliner =
319 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000320 break;
321 }
322 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner33c09d52011-05-21 20:40:11 +0000323 // Respect always_inline.
Chad Rosier98759622012-02-25 02:56:13 +0000324 if (OptLevel == 0)
325 // Do not insert lifetime intrinsics at -O0.
326 PMBuilder.Inliner = createAlwaysInlinerPass(false);
327 else
328 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000329 break;
330 }
331
Chris Lattner33c09d52011-05-21 20:40:11 +0000332 // Set up the per-function pass manager.
Stephen Hines651f13c2014-04-23 16:59:28 -0700333 FunctionPassManager *FPM = getPerFunctionPasses();
Chris Lattner33c09d52011-05-21 20:40:11 +0000334 if (CodeGenOpts.VerifyModule)
335 FPM->add(createVerifierPass());
336 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trick6445d622011-04-05 18:49:32 +0000337
Chris Lattner33c09d52011-05-21 20:40:11 +0000338 // Set up the per-module pass manager.
Stephen Hines651f13c2014-04-23 16:59:28 -0700339 PassManager *MPM = getPerModulePasses();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700340 if (CodeGenOpts.VerifyModule)
341 MPM->add(createDebugInfoVerifierPass());
Chris Lattnerdf619762011-02-18 22:20:38 +0000342
Nick Lewyckyf2b5e072013-03-20 01:38:16 +0000343 if (!CodeGenOpts.DisableGCov &&
344 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
Nick Lewyckyc3ae5832013-03-14 05:14:01 +0000345 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
346 // LLVM's -default-gcov-version flag is set to something invalid.
347 GCOVOptions Options;
348 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
349 Options.EmitData = CodeGenOpts.EmitGcovArcs;
350 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
351 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
352 Options.NoRedZone = CodeGenOpts.DisableRedZone;
Nick Lewyckyc3ae5832013-03-14 05:14:01 +0000353 Options.FunctionNamesInData =
Nick Lewycky83c546a2013-03-20 02:14:38 +0000354 !CodeGenOpts.CoverageNoFunctionNamesInData;
Nick Lewyckyc3ae5832013-03-14 05:14:01 +0000355 MPM->add(createGCOVProfilerPass(Options));
Douglas Gregor4cdad312012-10-23 20:05:01 +0000356 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000357 MPM->add(createStripSymbolsPass(true));
358 }
Nadav Rotem129369d2012-10-24 03:52:31 +0000359
Chris Lattner33c09d52011-05-21 20:40:11 +0000360 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000361}
362
Nadav Rotem129369d2012-10-24 03:52:31 +0000363TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000364 // Create the TargetMachine for generating code.
365 std::string Error;
366 std::string Triple = TheModule->getTargetTriple();
367 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
368 if (!TheTarget) {
Nadav Rotem129369d2012-10-24 03:52:31 +0000369 if (MustCreateTM)
Chad Rosiera03fc6e2013-03-27 00:14:35 +0000370 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700371 return nullptr;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000372 }
373
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700374 unsigned CodeModel =
375 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
376 .Case("small", llvm::CodeModel::Small)
377 .Case("kernel", llvm::CodeModel::Kernel)
378 .Case("medium", llvm::CodeModel::Medium)
379 .Case("large", llvm::CodeModel::Large)
380 .Case("default", llvm::CodeModel::Default)
381 .Default(~0u);
382 assert(CodeModel != ~0u && "invalid code model!");
383 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000384
David Blaikie6bd17d22012-02-07 19:36:38 +0000385 SmallVector<const char *, 16> BackendArgs;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000386 BackendArgs.push_back("clang"); // Fake program name.
387 if (!CodeGenOpts.DebugPass.empty()) {
388 BackendArgs.push_back("-debug-pass");
389 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
390 }
391 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
392 BackendArgs.push_back("-limit-float-precision");
393 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
394 }
395 if (llvm::TimePassesIsEnabled)
396 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000397 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
398 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Chad Rosier1b906052011-08-26 00:26:29 +0000399 if (CodeGenOpts.NoGlobalMerge)
400 BackendArgs.push_back("-global-merge=false");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700401 BackendArgs.push_back(nullptr);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000402 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
David Blaikie6bd17d22012-02-07 19:36:38 +0000403 BackendArgs.data());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000404
405 std::string FeaturesStr;
Evan Cheng368691e2011-06-30 02:06:32 +0000406 if (TargetOpts.Features.size()) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000407 SubtargetFeatures Features;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000408 for (std::vector<std::string>::const_iterator
409 it = TargetOpts.Features.begin(),
410 ie = TargetOpts.Features.end(); it != ie; ++it)
411 Features.AddFeature(*it);
412 FeaturesStr = Features.getString();
413 }
Evan Cheng2860e302011-07-19 06:37:41 +0000414
415 llvm::Reloc::Model RM = llvm::Reloc::Default;
416 if (CodeGenOpts.RelocationModel == "static") {
417 RM = llvm::Reloc::Static;
418 } else if (CodeGenOpts.RelocationModel == "pic") {
419 RM = llvm::Reloc::PIC_;
420 } else {
421 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
422 "Invalid PIC model!");
423 RM = llvm::Reloc::DynamicNoPIC;
424 }
425
Evan Cheng9254bf72011-11-16 08:38:55 +0000426 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
427 switch (CodeGenOpts.OptimizationLevel) {
428 default: break;
429 case 0: OptLevel = CodeGenOpt::None; break;
430 case 3: OptLevel = CodeGenOpt::Aggressive; break;
431 }
432
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000433 llvm::TargetOptions Options;
434
Stephen Hines651f13c2014-04-23 16:59:28 -0700435 if (CodeGenOpts.DisableIntegratedAS)
436 Options.DisableIntegratedAS = true;
437
438 if (CodeGenOpts.CompressDebugSections)
439 Options.CompressDebugSections = true;
440
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000441 // Set frame pointer elimination mode.
442 if (!CodeGenOpts.DisableFPElim) {
443 Options.NoFramePointerElim = false;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000444 } else if (CodeGenOpts.OmitLeafFramePointer) {
445 Options.NoFramePointerElim = false;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000446 } else {
447 Options.NoFramePointerElim = true;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000448 }
449
Rafael Espindola8af669f2012-06-19 01:26:10 +0000450 if (CodeGenOpts.UseInitArray)
451 Options.UseInitArray = true;
452
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000453 // Set float ABI type.
454 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
455 Options.FloatABIType = llvm::FloatABI::Soft;
456 else if (CodeGenOpts.FloatABI == "hard")
457 Options.FloatABIType = llvm::FloatABI::Hard;
458 else {
459 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
460 Options.FloatABIType = llvm::FloatABI::Default;
461 }
462
Lang Hamesc9686712012-07-06 00:59:19 +0000463 // Set FP fusion mode.
Lang Hames931c0832012-11-15 07:51:26 +0000464 switch (CodeGenOpts.getFPContractMode()) {
465 case CodeGenOptions::FPC_Off:
Lang Hamesc9686712012-07-06 00:59:19 +0000466 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
467 break;
Lang Hames931c0832012-11-15 07:51:26 +0000468 case CodeGenOptions::FPC_On:
Lang Hamesc9686712012-07-06 00:59:19 +0000469 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
470 break;
Lang Hames931c0832012-11-15 07:51:26 +0000471 case CodeGenOptions::FPC_Fast:
Lang Hamesc9686712012-07-06 00:59:19 +0000472 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
Nadav Rotem25030c42012-10-19 04:15:32 +0000473 break;
Lang Hamesc9686712012-07-06 00:59:19 +0000474 }
475
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000476 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
477 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
478 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
479 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
480 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
481 Options.UseSoftFloat = CodeGenOpts.SoftFloat;
Nick Lewycky4e785c92011-12-06 03:33:03 +0000482 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
Nick Lewycky1db772b2012-01-23 08:29:12 +0000483 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Bob Wilson71fd6cc2012-02-03 06:27:22 +0000484 Options.TrapFuncName = CodeGenOpts.TrapFuncName;
Chandler Carruth5081de52012-04-08 21:09:51 +0000485 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700486 Options.FunctionSections = CodeGenOpts.FunctionSections;
487 Options.DataSections = CodeGenOpts.DataSections;
488
489 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
490 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
491 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
492 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
493 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000494
Evan Cheng368691e2011-06-30 02:06:32 +0000495 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000496 FeaturesStr, Options,
497 RM, CM, OptLevel);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000498
Nadav Rotemfa60be02012-10-24 00:53:38 +0000499 return TM;
500}
501
502bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
Stephen Hines651f13c2014-04-23 16:59:28 -0700503 formatted_raw_ostream &OS) {
Nadav Rotemfa60be02012-10-24 00:53:38 +0000504
Daniel Dunbar897c6762010-06-07 23:20:08 +0000505 // Create the code generator passes.
Stephen Hines651f13c2014-04-23 16:59:28 -0700506 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000507
Chad Rosier3f3335d2012-02-29 20:14:59 +0000508 // Add LibraryInfo.
Daniel Dunbarcbbe2c02012-10-19 20:10:10 +0000509 llvm::Triple TargetTriple(TheModule->getTargetTriple());
510 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chad Rosier3f3335d2012-02-29 20:14:59 +0000511 if (!CodeGenOpts.SimplifyLibCalls)
512 TLI->disableAllFunctions();
513 PM->add(TLI);
514
Chandler Carruthd938e872013-01-07 01:38:01 +0000515 // Add Target specific analysis passes.
516 TM->addAnalysisPasses(*PM);
Nadav Rotem25030c42012-10-19 04:15:32 +0000517
Daniel Dunbar897c6762010-06-07 23:20:08 +0000518 // Normal mode, emit a .s or .o file by running the code generator. Note,
519 // this also adds codegenerator level optimization passes.
520 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
521 if (Action == Backend_EmitObj)
522 CGFT = TargetMachine::CGFT_ObjectFile;
523 else if (Action == Backend_EmitMCNull)
524 CGFT = TargetMachine::CGFT_Null;
525 else
526 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000527
528 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
529 // "codegen" passes so that it isn't run multiple times when there is
530 // inlining happening.
Dan Gohman465a8992012-04-04 21:04:56 +0000531 if (LangOpts.ObjCAutoRefCount &&
532 CodeGenOpts.OptimizationLevel > 0)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000533 PM->add(createObjCARCContractPass());
534
Evan Cheng9254bf72011-11-16 08:38:55 +0000535 if (TM->addPassesToEmitFile(*PM, OS, CGFT,
Daniel Dunbar897c6762010-06-07 23:20:08 +0000536 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
537 Diags.Report(diag::err_fe_unable_to_interface_with_target);
538 return false;
539 }
540
541 return true;
542}
543
544void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700545 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000546 llvm::formatted_raw_ostream FormattedOS;
547
Nadav Rotem129369d2012-10-24 03:52:31 +0000548 bool UsesCodeGen = (Action != Backend_EmitNothing &&
549 Action != Backend_EmitBC &&
550 Action != Backend_EmitLL);
Stephen Hines651f13c2014-04-23 16:59:28 -0700551 if (!TM)
552 TM.reset(CreateTargetMachine(UsesCodeGen));
553
Chad Rosiera03fc6e2013-03-27 00:14:35 +0000554 if (UsesCodeGen && !TM) return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700555 CreatePasses();
Nadav Rotemfa60be02012-10-24 00:53:38 +0000556
Daniel Dunbar897c6762010-06-07 23:20:08 +0000557 switch (Action) {
558 case Backend_EmitNothing:
559 break;
560
561 case Backend_EmitBC:
Stephen Hines651f13c2014-04-23 16:59:28 -0700562 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
Daniel Dunbar897c6762010-06-07 23:20:08 +0000563 break;
564
565 case Backend_EmitLL:
566 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Stephen Hines651f13c2014-04-23 16:59:28 -0700567 getPerModulePasses()->add(createPrintModulePass(FormattedOS));
Daniel Dunbar897c6762010-06-07 23:20:08 +0000568 break;
569
570 default:
571 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Stephen Hines651f13c2014-04-23 16:59:28 -0700572 if (!AddEmitPasses(Action, FormattedOS))
Daniel Dunbar897c6762010-06-07 23:20:08 +0000573 return;
574 }
575
Andrew Trick92b5d942011-04-05 18:56:55 +0000576 // Before executing passes, print the final values of the LLVM options.
577 cl::PrintOptionValues();
578
Daniel Dunbar897c6762010-06-07 23:20:08 +0000579 // Run passes. For now we do all passes at once, but eventually we
580 // would like to have the option of streaming code generation.
581
582 if (PerFunctionPasses) {
583 PrettyStackTraceString CrashInfo("Per-function optimization");
584
585 PerFunctionPasses->doInitialization();
586 for (Module::iterator I = TheModule->begin(),
587 E = TheModule->end(); I != E; ++I)
588 if (!I->isDeclaration())
589 PerFunctionPasses->run(*I);
590 PerFunctionPasses->doFinalization();
591 }
592
593 if (PerModulePasses) {
594 PrettyStackTraceString CrashInfo("Per-module optimization passes");
595 PerModulePasses->run(*TheModule);
596 }
597
598 if (CodeGenPasses) {
599 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000600 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000601 }
602}
603
David Blaikied6471f72011-09-25 23:23:43 +0000604void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
605 const CodeGenOptions &CGOpts,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000606 const clang::TargetOptions &TOpts,
Stephen Hines651f13c2014-04-23 16:59:28 -0700607 const LangOptions &LOpts, StringRef TDesc,
608 Module *M, BackendAction Action,
609 raw_ostream *OS) {
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000610 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000611
612 AsmHelper.EmitAssembly(Action, OS);
Stephen Hines651f13c2014-04-23 16:59:28 -0700613
614 // If an optional clang TargetInfo description string was passed in, use it to
615 // verify the LLVM TargetMachine's DataLayout.
616 if (AsmHelper.TM && !TDesc.empty()) {
617 std::string DLDesc =
618 AsmHelper.TM->getDataLayout()->getStringRepresentation();
619 if (DLDesc != TDesc) {
620 unsigned DiagID = Diags.getCustomDiagID(
621 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
622 "expected target description '%1'");
623 Diags.Report(DiagID) << DLDesc << TDesc;
624 }
625 }
Daniel Dunbar897c6762010-06-07 23:20:08 +0000626}