blob: fc6c5949d5742c80ba863b0d0ee1ae84e111b4d2 [file] [log] [blame]
Daniel Dunbarf976d1b2010-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 Dunbarc1b17292010-06-15 17:48:49 +000010#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
Dan Gohmanfec0ff82011-07-05 22:02:36 +000012#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/TargetOptions.h"
Chandler Carruth85098242010-06-15 23:19:56 +000014#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Kostya Serebryanyce2c7262013-12-27 08:11:08 +000016#include "clang/Frontend/Utils.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000017#include "llvm/ADT/StringSwitch.h"
Chandler Carruth1b3304d2014-01-13 07:47:38 +000018#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000019#include "llvm/CodeGen/RegAllocRegistry.h"
20#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000022#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/Module.h"
Chandler Carruthca884742014-01-13 09:26:48 +000024#include "llvm/IR/Verifier.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000025#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "llvm/PassManager.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FormattedStream.h"
29#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000030#include "llvm/Support/TargetRegistry.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000031#include "llvm/Support/Timer.h"
32#include "llvm/Support/raw_ostream.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000033#include "llvm/Target/TargetLibraryInfo.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000034#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000036#include "llvm/Transforms/IPO.h"
37#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/Transforms/Instrumentation.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000039#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000040#include "llvm/Transforms/Scalar.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000041#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000042using namespace clang;
43using namespace llvm;
44
45namespace {
46
47class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000048 DiagnosticsEngine &Diags;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000049 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000050 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000051 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000052 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000053
54 Timer CodeGenerationTime;
55
Daniel Dunbar195fa002010-09-17 07:35:16 +000056 mutable PassManager *CodeGenPasses;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000057 mutable PassManager *PerModulePasses;
58 mutable FunctionPassManager *PerFunctionPasses;
59
60private:
Alp Tokerf4e22382013-12-20 20:26:53 +000061 PassManager *getCodeGenPasses() const {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000062 if (!CodeGenPasses) {
Daniel Dunbar195fa002010-09-17 07:35:16 +000063 CodeGenPasses = new PassManager();
Rafael Espindola303f8b02014-02-25 17:30:40 +000064 CodeGenPasses->add(new DataLayoutPass(TheModule));
Chandler Carruthed0f133b2013-01-07 01:38:01 +000065 if (TM)
66 TM->addAnalysisPasses(*CodeGenPasses);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000067 }
68 return CodeGenPasses;
69 }
70
Alp Tokerf4e22382013-12-20 20:26:53 +000071 PassManager *getPerModulePasses() const {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000072 if (!PerModulePasses) {
73 PerModulePasses = new PassManager();
Rafael Espindola303f8b02014-02-25 17:30:40 +000074 PerModulePasses->add(new DataLayoutPass(TheModule));
Chandler Carruthed0f133b2013-01-07 01:38:01 +000075 if (TM)
76 TM->addAnalysisPasses(*PerModulePasses);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000077 }
78 return PerModulePasses;
79 }
80
Alp Tokerf4e22382013-12-20 20:26:53 +000081 FunctionPassManager *getPerFunctionPasses() const {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000082 if (!PerFunctionPasses) {
83 PerFunctionPasses = new FunctionPassManager(TheModule);
Rafael Espindola303f8b02014-02-25 17:30:40 +000084 PerFunctionPasses->add(new DataLayoutPass(TheModule));
Chandler Carruthed0f133b2013-01-07 01:38:01 +000085 if (TM)
86 TM->addAnalysisPasses(*PerFunctionPasses);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000087 }
88 return PerFunctionPasses;
89 }
90
Alp Tokerf4e22382013-12-20 20:26:53 +000091 void CreatePasses();
Nadav Rotemec57ab32012-10-24 00:53:38 +000092
Nadav Rotemdc06b2d2012-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 Dunbarf976d1b2010-06-07 23:20:08 +0000102
103 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
104 ///
105 /// \return True on success.
Alp Tokerf4e22382013-12-20 20:26:53 +0000106 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000107
108public:
David Blaikie9c902b52011-09-25 23:23:43 +0000109 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
Nick Lewycky432add52011-12-02 22:17:00 +0000110 const CodeGenOptions &CGOpts,
111 const clang::TargetOptions &TOpts,
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000112 const LangOptions &LOpts,
Daniel Dunbar3e111522010-06-07 23:21:04 +0000113 Module *M)
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000114 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
Daniel Dunbar3e111522010-06-07 23:21:04 +0000115 TheModule(M), CodeGenerationTime("Code Generation Time"),
Craig Topper8a13c412014-05-21 05:09:00 +0000116 CodeGenPasses(nullptr), PerModulePasses(nullptr),
117 PerFunctionPasses(nullptr) {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000118
119 ~EmitAssemblyHelper() {
120 delete CodeGenPasses;
121 delete PerModulePasses;
122 delete PerFunctionPasses;
Alp Tokerf4e22382013-12-20 20:26:53 +0000123 if (CodeGenOpts.DisableFree)
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000124 BuryPointer(TM.release());
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000125 }
126
Ahmed Charlesb8984322014-03-07 20:03:18 +0000127 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000128
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000129 void EmitAssembly(BackendAction Action, raw_ostream *OS);
130};
131
Alexey Samsonovc6515b62012-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 Samsonov0e96bec2012-11-29 22:36:21 +0000134class PassManagerBuilderWrapper : public PassManagerBuilder {
135public:
Alexey Samsonov9ab73622012-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 Samsonov0e96bec2012-11-29 22:36:21 +0000140 const LangOptions &getLangOpts() const { return LangOpts; }
141private:
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000142 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000143 const LangOptions &LangOpts;
144};
145
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000146}
147
Dan Gohman5932ce22012-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 Gohmanfec0ff82011-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 Novillo5c297052013-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
Diego Novillob56be642014-03-03 20:06:18 +0000171static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
172 PassManagerBase &PM) {
173 PM.add(createAddDiscriminatorsPass());
174}
175
Nuno Lopesa4255892012-05-22 17:19:45 +0000176static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
177 PassManagerBase &PM) {
Joey Goulyebc59d52012-11-23 10:39:49 +0000178 PM.add(createBoundsCheckingPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000179}
180
Alexey Samsonov0e96bec2012-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 Samsonov9ab73622012-12-03 19:12:58 +0000185 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000186 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonov29524a92013-01-20 13:12:12 +0000187 PM.add(createAddressSanitizerFunctionPass(
188 LangOpts.Sanitize.InitOrder,
189 LangOpts.Sanitize.UseAfterReturn,
190 LangOpts.Sanitize.UseAfterScope,
Evgeniy Stepanovd04b8612014-01-16 10:19:31 +0000191 CGOpts.SanitizerBlacklistFile));
Alexey Samsonov29524a92013-01-20 13:12:12 +0000192 PM.add(createAddressSanitizerModulePass(
193 LangOpts.Sanitize.InitOrder,
Evgeniy Stepanovd04b8612014-01-16 10:19:31 +0000194 CGOpts.SanitizerBlacklistFile));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000195}
196
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000197static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
198 PassManagerBase &PM) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000199 const PassManagerBuilderWrapper &BuilderWrapper =
200 static_cast<const PassManagerBuilderWrapper&>(Builder);
201 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov29524a92013-01-20 13:12:12 +0000202 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins,
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000203 CGOpts.SanitizerBlacklistFile));
Evgeniy Stepanov10284672013-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 Stepanovaea92e52012-12-03 13:20:43 +0000216}
217
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000218static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
219 PassManagerBase &PM) {
Alexey Samsonovc6515b62012-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 Serebryany28a7a112012-03-01 22:27:08 +0000224}
225
Peter Collingbournec3772752013-08-07 22:47:34 +0000226static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
227 PassManagerBase &PM) {
Peter Collingbourne276be3c2013-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 Collingbournec3772752013-08-07 22:47:34 +0000232}
233
Alp Tokerf4e22382013-12-20 20:26:53 +0000234void EmitAssemblyHelper::CreatePasses() {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000235 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000236 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
Daniel Dunbarf976d1b2010-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 Samsonov0e96bec2012-11-29 22:36:21 +0000244
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000245 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000246 PMBuilder.OptLevel = OptLevel;
247 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000248 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
249 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
250 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000251
Duncan P. N. Exon Smith85e349f2014-04-18 01:05:25 +0000252 PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000253 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
254 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Hal Finkelce0697f2013-11-17 16:03:29 +0000255 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000256
Diego Novillob56be642014-03-03 20:06:18 +0000257 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
258 addAddDiscriminatorsPass);
259
Diego Novillo5c297052013-11-13 12:22:39 +0000260 if (!CodeGenOpts.SampleProfileFile.empty())
261 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
262 addSampleProfileLoaderPass);
263
Dan Gohmanfec0ff82011-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 Gohman5932ce22012-01-17 20:54:51 +0000268 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
269 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000270 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
271 addObjCARCOptPass);
272 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000273
Richard Smith6b53e222013-10-22 22:51:04 +0000274 if (LangOpts.Sanitize.LocalBounds) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000275 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
276 addBoundsCheckingPass);
277 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
278 addBoundsCheckingPass);
279 }
280
Will Dietzf54319c2013-01-18 11:30:38 +0000281 if (LangOpts.Sanitize.Address) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000282 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000283 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000284 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000285 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000286 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000287
Will Dietzf54319c2013-01-18 11:30:38 +0000288 if (LangOpts.Sanitize.Memory) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000289 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
290 addMemorySanitizerPass);
291 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
292 addMemorySanitizerPass);
293 }
294
Will Dietzf54319c2013-01-18 11:30:38 +0000295 if (LangOpts.Sanitize.Thread) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000296 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000297 addThreadSanitizerPass);
298 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
299 addThreadSanitizerPass);
300 }
301
Peter Collingbournec3772752013-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 Lattner5c123672011-05-21 20:40:11 +0000309 // Figure out TargetLibraryInfo.
Bill Wendling28b9e8b2011-05-17 23:06:23 +0000310 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000311 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattnerfa222df2011-02-18 22:34:47 +0000312 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000313 PMBuilder.LibraryInfo->disableAllFunctions();
Eli Benderskyb5cfa8c2014-03-12 16:30:34 +0000314
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000315 switch (Inlining) {
316 case CodeGenOptions::NoInlining: break;
317 case CodeGenOptions::NormalInlining: {
Eli Benderskyb5cfa8c2014-03-12 16:30:34 +0000318 PMBuilder.Inliner =
319 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000320 break;
321 }
322 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner5c123672011-05-21 20:40:11 +0000323 // Respect always_inline.
Chad Rosiere2c45062012-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 Dunbarf976d1b2010-06-07 23:20:08 +0000329 break;
330 }
331
Chris Lattner5c123672011-05-21 20:40:11 +0000332 // Set up the per-function pass manager.
Alp Tokerf4e22382013-12-20 20:26:53 +0000333 FunctionPassManager *FPM = getPerFunctionPasses();
Chris Lattner5c123672011-05-21 20:40:11 +0000334 if (CodeGenOpts.VerifyModule)
335 FPM->add(createVerifierPass());
336 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trickb2a84722011-04-05 18:49:32 +0000337
Chris Lattner5c123672011-05-21 20:40:11 +0000338 // Set up the per-module pass manager.
Alp Tokerf4e22382013-12-20 20:26:53 +0000339 PassManager *MPM = getPerModulePasses();
Duncan P. N. Exon Smith52eaffe2014-04-15 16:27:43 +0000340 if (CodeGenOpts.VerifyModule)
341 MPM->add(createDebugInfoVerifierPass());
Chris Lattnerd98cec52011-02-18 22:20:38 +0000342
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000343 if (!CodeGenOpts.DisableGCov &&
344 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
Nick Lewyckyc8bf8242013-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 Lewyckyc8bf8242013-03-14 05:14:01 +0000353 Options.FunctionNamesInData =
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000354 !CodeGenOpts.CoverageNoFunctionNamesInData;
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000355 MPM->add(createGCOVProfilerPass(Options));
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000356 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
Nick Lewycky207bce32011-04-21 23:44:07 +0000357 MPM->add(createStripSymbolsPass(true));
358 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000359
Chris Lattner5c123672011-05-21 20:40:11 +0000360 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000361}
362
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000363TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-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 Rotemdc06b2d2012-10-24 03:52:31 +0000369 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000370 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Craig Topper8a13c412014-05-21 05:09:00 +0000371 return nullptr;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000372 }
373
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000374 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)
Saleem Abdulrasool61449c62014-05-08 16:28:48 +0000379 .Case("large", llvm::CodeModel::Large)
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000380 .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 Dunbarf976d1b2010-06-07 23:20:08 +0000384
David Blaikie09d20ee2012-02-07 19:36:38 +0000385 SmallVector<const char *, 16> BackendArgs;
Daniel Dunbarf976d1b2010-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 Dunbar12100e22011-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 Rosierba3df1d2011-08-26 00:26:29 +0000399 if (CodeGenOpts.NoGlobalMerge)
400 BackendArgs.push_back("-global-merge=false");
Craig Topper8a13c412014-05-21 05:09:00 +0000401 BackendArgs.push_back(nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000402 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
David Blaikie09d20ee2012-02-07 19:36:38 +0000403 BackendArgs.data());
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000404
405 std::string FeaturesStr;
Evan Chengadc79592011-06-30 02:06:32 +0000406 if (TargetOpts.Features.size()) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000407 SubtargetFeatures Features;
Daniel Dunbarf976d1b2010-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 Cheng3f37dd02011-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 Chengdd286bc2011-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 Lewycky432add52011-12-02 22:17:00 +0000433 llvm::TargetOptions Options;
434
Rafael Espindola33ebd212014-02-21 03:14:07 +0000435 if (CodeGenOpts.DisableIntegratedAS)
436 Options.DisableIntegratedAS = true;
437
David Blaikie7e2fd942014-03-27 20:47:30 +0000438 if (CodeGenOpts.CompressDebugSections)
439 Options.CompressDebugSections = true;
440
Nick Lewycky432add52011-12-02 22:17:00 +0000441 // Set frame pointer elimination mode.
442 if (!CodeGenOpts.DisableFPElim) {
443 Options.NoFramePointerElim = false;
Nick Lewycky432add52011-12-02 22:17:00 +0000444 } else if (CodeGenOpts.OmitLeafFramePointer) {
445 Options.NoFramePointerElim = false;
Nick Lewycky432add52011-12-02 22:17:00 +0000446 } else {
447 Options.NoFramePointerElim = true;
Nick Lewycky432add52011-12-02 22:17:00 +0000448 }
449
Rafael Espindola66aa0452012-06-19 01:26:10 +0000450 if (CodeGenOpts.UseInitArray)
451 Options.UseInitArray = true;
452
Nick Lewycky432add52011-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 Hamesaa53b932012-07-06 00:59:19 +0000463 // Set FP fusion mode.
Lang Hames65992f42012-11-15 07:51:26 +0000464 switch (CodeGenOpts.getFPContractMode()) {
465 case CodeGenOptions::FPC_Off:
Lang Hamesaa53b932012-07-06 00:59:19 +0000466 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
467 break;
Lang Hames65992f42012-11-15 07:51:26 +0000468 case CodeGenOptions::FPC_On:
Lang Hamesaa53b932012-07-06 00:59:19 +0000469 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
470 break;
Lang Hames65992f42012-11-15 07:51:26 +0000471 case CodeGenOptions::FPC_Fast:
Lang Hamesaa53b932012-07-06 00:59:19 +0000472 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
Nadav Roteme9c233b2012-10-19 04:15:32 +0000473 break;
Lang Hamesaa53b932012-07-06 00:59:19 +0000474 }
475
Nick Lewycky432add52011-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 Lewyckyf4d3f7a2011-12-06 03:33:03 +0000482 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
Nick Lewycky1c8c4362012-01-23 08:29:12 +0000483 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Bob Wilson14adb362012-02-03 06:27:22 +0000484 Options.TrapFuncName = CodeGenOpts.TrapFuncName;
Chandler Carruth097d0192012-04-08 21:09:51 +0000485 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
Eric Christopheracca0082014-05-20 21:25:41 +0000486 Options.FunctionSections = CodeGenOpts.FunctionSections;
487 Options.DataSections = CodeGenOpts.DataSections;
Nick Lewycky432add52011-12-02 22:17:00 +0000488
Eric Christopher7e72a092014-05-15 01:21:56 +0000489 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
490 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
Eric Christophere76eee42014-05-16 20:46:14 +0000491 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
Eric Christopher7e72a092014-05-15 01:21:56 +0000492 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
Eric Christopher4015e124e2014-05-21 00:00:03 +0000493 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
Eric Christopher7e72a092014-05-15 01:21:56 +0000494
Evan Chengadc79592011-06-30 02:06:32 +0000495 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Nick Lewycky432add52011-12-02 22:17:00 +0000496 FeaturesStr, Options,
497 RM, CM, OptLevel);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000498
Nadav Rotemec57ab32012-10-24 00:53:38 +0000499 return TM;
500}
501
502bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
Alp Tokerf4e22382013-12-20 20:26:53 +0000503 formatted_raw_ostream &OS) {
Nadav Rotemec57ab32012-10-24 00:53:38 +0000504
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000505 // Create the code generator passes.
Alp Tokerf4e22382013-12-20 20:26:53 +0000506 PassManager *PM = getCodeGenPasses();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000507
Chad Rosierb1cfc682012-02-29 20:14:59 +0000508 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000509 llvm::Triple TargetTriple(TheModule->getTargetTriple());
510 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chad Rosierb1cfc682012-02-29 20:14:59 +0000511 if (!CodeGenOpts.SimplifyLibCalls)
512 TLI->disableAllFunctions();
513 PM->add(TLI);
514
Chandler Carruthed0f133b2013-01-07 01:38:01 +0000515 // Add Target specific analysis passes.
516 TM->addAnalysisPasses(*PM);
Nadav Roteme9c233b2012-10-19 04:15:32 +0000517
Daniel Dunbarf976d1b2010-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 Gohmanfec0ff82011-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 Gohman1170b082012-04-04 21:04:56 +0000531 if (LangOpts.ObjCAutoRefCount &&
532 CodeGenOpts.OptimizationLevel > 0)
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000533 PM->add(createObjCARCContractPass());
534
Evan Chengdd286bc2011-11-16 08:38:55 +0000535 if (TM->addPassesToEmitFile(*PM, OS, CGFT,
Daniel Dunbarf976d1b2010-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) {
Craig Topper8a13c412014-05-21 05:09:00 +0000545 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000546 llvm::formatted_raw_ostream FormattedOS;
547
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000548 bool UsesCodeGen = (Action != Backend_EmitNothing &&
549 Action != Backend_EmitBC &&
550 Action != Backend_EmitLL);
Alp Tokerf4e22382013-12-20 20:26:53 +0000551 if (!TM)
552 TM.reset(CreateTargetMachine(UsesCodeGen));
553
Chad Rosierecafbe62013-03-27 00:14:35 +0000554 if (UsesCodeGen && !TM) return;
Alp Tokerf4e22382013-12-20 20:26:53 +0000555 CreatePasses();
Nadav Rotemec57ab32012-10-24 00:53:38 +0000556
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000557 switch (Action) {
558 case Backend_EmitNothing:
559 break;
560
561 case Backend_EmitBC:
Alp Tokerf4e22382013-12-20 20:26:53 +0000562 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000563 break;
564
565 case Backend_EmitLL:
566 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Chandler Carruth809403f2014-01-12 11:31:22 +0000567 getPerModulePasses()->add(createPrintModulePass(FormattedOS));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000568 break;
569
570 default:
571 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Alp Tokerf4e22382013-12-20 20:26:53 +0000572 if (!AddEmitPasses(Action, FormattedOS))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000573 return;
574 }
575
Andrew Trick15e36e82011-04-05 18:56:55 +0000576 // Before executing passes, print the final values of the LLVM options.
577 cl::PrintOptionValues();
578
Daniel Dunbarf976d1b2010-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 Dunbar195fa002010-09-17 07:35:16 +0000600 CodeGenPasses->run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000601 }
602}
603
David Blaikie9c902b52011-09-25 23:23:43 +0000604void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
605 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000606 const clang::TargetOptions &TOpts,
Alp Tokere83b9062014-01-02 15:08:04 +0000607 const LangOptions &LOpts, StringRef TDesc,
608 Module *M, BackendAction Action,
609 raw_ostream *OS) {
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000610 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000611
612 AsmHelper.EmitAssembly(Action, OS);
Alp Tokere83b9062014-01-02 15:08:04 +0000613
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 Dunbarf976d1b2010-06-07 23:20:08 +0000626}