blob: 51d089988178fb40d39966b25c9b820a2fba8fa7 [file] [log] [blame]
Nick Kledzik07b4a622008-02-26 20:26:43 +00001//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
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.
Bill Wendling39d942b2012-03-31 10:50:14 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling39d942b2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000015#include "llvm/LTO/LTOCodeGenerator.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000017#include "llvm/Analysis/Passes.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000018#include "llvm/Bitcode/ReaderWriter.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000019#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000020#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000024#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/LLVMContext.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000027#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000030#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000031#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000032#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000033#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000035#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/PassManager.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000037#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000038#include "llvm/Support/FileSystem.h"
David Greenea31f96c2009-07-14 20:18:05 +000039#include "llvm/Support/FormattedStream.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000040#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000042#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000043#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000045#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000046#include "llvm/Support/raw_ostream.h"
Michael J. Spencerd4227232010-12-09 18:06:07 +000047#include "llvm/Support/system_error.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000048#include "llvm/Target/TargetLibraryInfo.h"
49#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000050#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000051#include "llvm/Target/TargetRegisterInfo.h"
52#include "llvm/Transforms/IPO.h"
53#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000054#include "llvm/Transforms/ObjCARC.h"
Shuxin Yang76d082b2013-08-12 18:29:43 +000055using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000056
Bill Wendling534a6582012-03-31 10:49:43 +000057const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000058#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000059 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000060#else
Bill Wendling534a6582012-03-31 10:49:43 +000061 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000062#endif
63}
64
Bill Wendling39d942b2012-03-31 10:50:14 +000065LTOCodeGenerator::LTOCodeGenerator()
Rafael Espindolac80c9692013-09-04 17:44:24 +000066 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
67 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +000068 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL),
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000069 DiagHandler(NULL), DiagContext(NULL) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000070 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000071}
72
Bill Wendling534a6582012-03-31 10:49:43 +000073LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000074 delete TargetMach;
75 delete NativeObjectFile;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000076 TargetMach = NULL;
77 NativeObjectFile = NULL;
78
79 Linker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000080
Rafael Espindolac80c9692013-09-04 17:44:24 +000081 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
82 E = CodegenOptions.end();
83 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000084 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000085}
86
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000087// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000088// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000089// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000090void LTOCodeGenerator::initializeLTOPasses() {
91 PassRegistry &R = *PassRegistry::getPassRegistry();
92
93 initializeInternalizePassPass(R);
94 initializeIPSCCPPass(R);
95 initializeGlobalOptPass(R);
96 initializeConstantMergePass(R);
97 initializeDAHPass(R);
98 initializeInstCombinerPass(R);
99 initializeSimpleInlinerPass(R);
100 initializePruneEHPass(R);
101 initializeGlobalDCEPass(R);
102 initializeArgPromotionPass(R);
103 initializeJumpThreadingPass(R);
104 initializeSROAPass(R);
105 initializeSROA_DTPass(R);
106 initializeSROA_SSAUpPass(R);
107 initializeFunctionAttrsPass(R);
108 initializeGlobalsModRefPass(R);
109 initializeLICMPass(R);
110 initializeGVNPass(R);
111 initializeMemCpyOptPass(R);
112 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000113 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000114}
115
Bill Wendling0e1824c2012-03-31 11:15:43 +0000116bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000117 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000118
119 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
120 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000121 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000122
Shuxin Yangb6696a92013-08-07 05:19:23 +0000123 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000124}
Bill Wendling39d942b2012-03-31 10:50:14 +0000125
Rafael Espindola0b385c72013-09-30 16:39:19 +0000126void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
127 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
128 Options.NoFramePointerElim = options.NoFramePointerElim;
129 Options.AllowFPOpFusion = options.AllowFPOpFusion;
130 Options.UnsafeFPMath = options.UnsafeFPMath;
131 Options.NoInfsFPMath = options.NoInfsFPMath;
132 Options.NoNaNsFPMath = options.NoNaNsFPMath;
133 Options.HonorSignDependentRoundingFPMathOption =
134 options.HonorSignDependentRoundingFPMathOption;
135 Options.UseSoftFloat = options.UseSoftFloat;
136 Options.FloatABIType = options.FloatABIType;
137 Options.NoZerosInBSS = options.NoZerosInBSS;
138 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
139 Options.DisableTailCalls = options.DisableTailCalls;
140 Options.StackAlignmentOverride = options.StackAlignmentOverride;
141 Options.TrapFuncName = options.TrapFuncName;
142 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
143 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
144 Options.UseInitArray = options.UseInitArray;
145}
146
Shuxin Yangb6696a92013-08-07 05:19:23 +0000147void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000148 switch (debug) {
149 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000150 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000151 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000152
Bill Wendling0e1824c2012-03-31 11:15:43 +0000153 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000154 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000155 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000156 }
157 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000158}
159
Shuxin Yangb6696a92013-08-07 05:19:23 +0000160void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000161 switch (model) {
162 case LTO_CODEGEN_PIC_MODEL_STATIC:
163 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
164 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000165 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000166 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000167 }
168 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000169}
170
Chris Lattner69733952009-08-23 07:49:08 +0000171bool LTOCodeGenerator::writeMergedModules(const char *path,
172 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000173 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000174 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000175
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000176 // mark which symbols can not be internalized
177 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000178
Chris Lattner69733952009-08-23 07:49:08 +0000179 // create output file
180 std::string ErrInfo;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000181 tool_output_file Out(path, ErrInfo, sys::fs::F_None);
Chris Lattner69733952009-08-23 07:49:08 +0000182 if (!ErrInfo.empty()) {
183 errMsg = "could not open bitcode file for writing: ";
184 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000185 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000186 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000187
Chris Lattner69733952009-08-23 07:49:08 +0000188 // write bitcode to it
Rafael Espindolac80c9692013-09-04 17:44:24 +0000189 WriteBitcodeToFile(Linker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000190 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000191
Dan Gohmana2233f22010-09-01 14:20:41 +0000192 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000193 errMsg = "could not write bitcode file: ";
194 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000195 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000196 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000197 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000198
Dan Gohman8525fe72010-08-20 16:59:15 +0000199 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000200 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000201}
202
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000203bool LTOCodeGenerator::compile_to_file(const char** name,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000204 bool disableOpt,
205 bool disableInline,
206 bool disableGVNLoadPRE,
207 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000208 // make unique temp .o file to put generated object file
209 SmallString<128> Filename;
210 int FD;
211 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
212 if (EC) {
213 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000214 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000215 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000216
Shuxin Yang1826ae22013-08-12 21:07:31 +0000217 // generate object file
218 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000219
Rafael Espindola0b385c72013-09-30 16:39:19 +0000220 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
221 disableGVNLoadPRE, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000222 objFile.os().close();
223 if (objFile.os().has_error()) {
224 objFile.os().clear_error();
225 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000226 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000227 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000228
Shuxin Yang1826ae22013-08-12 21:07:31 +0000229 objFile.keep();
230 if (!genResult) {
231 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000232 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000233 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000234
Rafael Espindolac80c9692013-09-04 17:44:24 +0000235 NativeObjectPath = Filename.c_str();
236 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000237 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000238}
239
Rafael Espindola0b385c72013-09-30 16:39:19 +0000240const void* LTOCodeGenerator::compile(size_t* length,
241 bool disableOpt,
242 bool disableInline,
243 bool disableGVNLoadPRE,
244 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000245 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000246 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
247 errMsg))
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000248 return NULL;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000249
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000250 // remove old buffer if compile() called twice
Rafael Espindolac80c9692013-09-04 17:44:24 +0000251 delete NativeObjectFile;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000252
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000253 // read .o file into memory buffer
Ahmed Charles56440fd2014-03-06 05:51:42 +0000254 std::unique_ptr<MemoryBuffer> BuffPtr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000255 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
256 errMsg = ec.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000257 sys::fs::remove(NativeObjectPath);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000258 return NULL;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000259 }
Ahmed Charles96c9d952014-03-05 10:19:29 +0000260 NativeObjectFile = BuffPtr.release();
Rafael Espindolafac373c2011-02-24 21:04:06 +0000261
Shuxin Yang1826ae22013-08-12 21:07:31 +0000262 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000263 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000264
Shuxin Yang1826ae22013-08-12 21:07:31 +0000265 // return buffer, unless error
Rafael Espindolac80c9692013-09-04 17:44:24 +0000266 if (NativeObjectFile == NULL)
Shuxin Yang1826ae22013-08-12 21:07:31 +0000267 return NULL;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000268 *length = NativeObjectFile->getBufferSize();
269 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000270}
271
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000272bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000273 if (TargetMach != NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000274 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000275
Rafael Espindolac80c9692013-09-04 17:44:24 +0000276 std::string TripleStr = Linker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000277 if (TripleStr.empty())
278 TripleStr = sys::getDefaultTargetTriple();
279 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000280
Bill Wendling45f74e32012-08-06 22:52:45 +0000281 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000282 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling6a0abed2012-08-08 22:03:50 +0000283 if (march == NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000284 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000285
Bill Wendling45f74e32012-08-06 22:52:45 +0000286 // The relocation model is actually a static member of TargetMachine and
287 // needs to be set before the TargetMachine is instantiated.
288 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000289 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000290 case LTO_CODEGEN_PIC_MODEL_STATIC:
291 RelocModel = Reloc::Static;
292 break;
293 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
294 RelocModel = Reloc::PIC_;
295 break;
296 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
297 RelocModel = Reloc::DynamicNoPIC;
298 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000299 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000300
301 // construct LTOModule, hand over ownership of module and target
302 SubtargetFeatures Features;
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000303 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000304 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000305 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000306 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000307 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000308 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000309 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000310 MCpu = "yonah";
Tim Northover00ed9962014-03-29 10:18:08 +0000311 else if (Triple.getArch() == llvm::Triple::arm64)
312 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000313 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000314
Rafael Espindolac80c9692013-09-04 17:44:24 +0000315 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
316 RelocModel, CodeModel::Default,
317 CodeGenOpt::Aggressive);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000318 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000319}
320
Bill Wendling0e1824c2012-03-31 11:15:43 +0000321void LTOCodeGenerator::
322applyRestriction(GlobalValue &GV,
Justin Bognerb10a5202013-11-12 21:44:01 +0000323 const ArrayRef<StringRef> &Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000324 std::vector<const char*> &MustPreserveList,
325 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
326 Mangler &Mangler) {
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000327 // There are no restrictions to apply to declarations.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000328 if (GV.isDeclaration())
329 return;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000330
331 // There is nothing more restrictive than private linkage.
332 if (GV.hasPrivateLinkage())
333 return;
334
335 SmallString<64> Buffer;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000336 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000337
Rafael Espindolac80c9692013-09-04 17:44:24 +0000338 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000339 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000340 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000341 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000342
343 // Conservatively append user-supplied runtime library functions to
344 // llvm.compiler.used. These could be internalized and deleted by
345 // optimizations like -globalopt, causing problems when later optimizations
346 // add new library calls (e.g., llvm.memset => memset and printf => puts).
347 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
348 if (isa<Function>(GV) &&
349 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
350 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000351}
352
353static void findUsedValues(GlobalVariable *LLVMUsed,
354 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
355 if (LLVMUsed == 0) return;
356
Rafael Espindolacc111b22013-04-24 17:54:35 +0000357 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000358 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000359 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000360 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000361 UsedValues.insert(GV);
362}
363
Justin Bognerb10a5202013-11-12 21:44:01 +0000364static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
365 const TargetLibraryInfo& TLI,
366 const TargetLowering *Lowering)
367{
368 // TargetLibraryInfo has info on C runtime library calls on the current
369 // target.
370 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
371 I != E; ++I) {
372 LibFunc::Func F = static_cast<LibFunc::Func>(I);
373 if (TLI.has(F))
374 Libcalls.push_back(TLI.getName(F));
375 }
376
377 // TargetLowering has info on library calls that CodeGen expects to be
378 // available, both from the C runtime and compiler-rt.
379 if (Lowering)
380 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
381 I != E; ++I)
382 if (const char *Name
383 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
384 Libcalls.push_back(Name);
385
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000386 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000387 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
388 Libcalls.end());
389}
390
Chris Lattner2eff5052010-03-12 18:44:54 +0000391void LTOCodeGenerator::applyScopeRestrictions() {
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000392 if (ScopeRestrictionsDone)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000393 return;
394 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000395
Chris Lattner2eff5052010-03-12 18:44:54 +0000396 // Start off with a verification pass.
397 PassManager passes;
398 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000399
Bill Wendling39d942b2012-03-31 10:50:14 +0000400 // mark which symbols can not be internalized
Rafael Espindola58873562014-01-03 19:21:54 +0000401 Mangler Mangler(TargetMach->getDataLayout());
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000402 std::vector<const char*> MustPreserveList;
403 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000404 std::vector<StringRef> Libcalls;
405 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
406 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000407
408 for (Module::iterator f = mergedModule->begin(),
409 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000410 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000411 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000412 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000413 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000414 for (Module::alias_iterator a = mergedModule->alias_begin(),
415 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000416 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000417
418 GlobalVariable *LLVMCompilerUsed =
419 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000420 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000421 if (LLVMCompilerUsed)
422 LLVMCompilerUsed->eraseFromParent();
423
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000424 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000425 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000426 std::vector<Constant*> asmUsed2;
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000427 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
428 e = AsmUsed.end(); i !=e; ++i) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000429 GlobalValue *GV = *i;
430 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
431 asmUsed2.push_back(c);
432 }
433
434 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
435 LLVMCompilerUsed =
436 new llvm::GlobalVariable(*mergedModule, ATy, false,
437 llvm::GlobalValue::AppendingLinkage,
438 llvm::ConstantArray::get(ATy, asmUsed2),
439 "llvm.compiler.used");
440
441 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000442 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000443
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000444 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000445
Chris Lattner2eff5052010-03-12 18:44:54 +0000446 // apply scope restrictions
447 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000448
Rafael Espindolac80c9692013-09-04 17:44:24 +0000449 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000450}
451
Nick Kledzik07b4a622008-02-26 20:26:43 +0000452/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000453bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000454 bool DisableOpt,
455 bool DisableInline,
456 bool DisableGVNLoadPRE,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000457 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000458 if (!this->determineTarget(errMsg))
459 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000460
Rafael Espindolac80c9692013-09-04 17:44:24 +0000461 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000462
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000463 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000464 this->applyScopeRestrictions();
465
Bill Wendling0e1824c2012-03-31 11:15:43 +0000466 // Instantiate the pass manager to organize the passes.
467 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000468
Bill Wendling0e1824c2012-03-31 11:15:43 +0000469 // Start off with a verification pass.
470 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000471
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000472 // Add an appropriate DataLayout instance for this module...
Rafael Espindola339430f2014-02-25 23:25:17 +0000473 mergedModule->setDataLayout(TargetMach->getDataLayout());
474 passes.add(new DataLayoutPass(mergedModule));
Yi Jiang53823be2013-12-12 01:37:39 +0000475
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000476 // Add appropriate TargetLibraryInfo for this module.
Yi Jiang53823be2013-12-12 01:37:39 +0000477 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
478
Rafael Espindolac80c9692013-09-04 17:44:24 +0000479 TargetMach->addAnalysisPasses(passes);
Bill Wendling39d942b2012-03-31 10:50:14 +0000480
Rafael Espindola0ecb8fa2012-04-16 10:58:38 +0000481 // Enabling internalize here would use its AllButMain variant. It
482 // keeps only main if it exists and does nothing for libraries. Instead
483 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000484 if (!DisableOpt)
Bill Wendlingc7e0a042013-02-28 14:11:10 +0000485 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling4a8fc8f2012-12-10 21:33:45 +0000486 /*Internalize=*/false,
Bill Wendling932b9922012-04-02 22:16:50 +0000487 !DisableInline,
488 DisableGVNLoadPRE);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000489
Bill Wendling0e1824c2012-03-31 11:15:43 +0000490 // Make sure everything is still good.
491 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000492
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000493 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000494
Rafael Espindola339430f2014-02-25 23:25:17 +0000495 codeGenPasses.add(new DataLayoutPass(mergedModule));
Nick Kledzik07b4a622008-02-26 20:26:43 +0000496
Bill Wendling0e1824c2012-03-31 11:15:43 +0000497 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000498
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000499 // If the bitcode files contain ARC code and were compiled with optimization,
500 // the ObjCARCContractPass must be run, so do it unconditionally here.
501 codeGenPasses.add(createObjCARCContractPass());
502
Rafael Espindolac80c9692013-09-04 17:44:24 +0000503 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
504 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000505 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000506 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000507 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000508
Bill Wendling0e1824c2012-03-31 11:15:43 +0000509 // Run our queue of passes all at once now, efficiently.
510 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000511
Bill Wendling0e1824c2012-03-31 11:15:43 +0000512 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000513 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000514
Shuxin Yang95866fa2013-08-06 21:51:21 +0000515 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000516}
517
Bill Wendling534a6582012-03-31 10:49:43 +0000518/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
519/// LTO problems.
520void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
521 for (std::pair<StringRef, StringRef> o = getToken(options);
522 !o.first.empty(); o = getToken(o.second)) {
523 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
524 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000525 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000526 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000527 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000528 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000529}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000530
531void LTOCodeGenerator::parseCodeGenDebugOptions() {
532 // if options were requested, set them
533 if (!CodegenOptions.empty())
534 cl::ParseCommandLineOptions(CodegenOptions.size(),
535 const_cast<char **>(&CodegenOptions[0]));
536}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000537
538void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
539 void *Context) {
540 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
541}
542
543void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
544 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
545 lto_codegen_diagnostic_severity_t Severity;
546 switch (DI.getSeverity()) {
547 case DS_Error:
548 Severity = LTO_DS_ERROR;
549 break;
550 case DS_Warning:
551 Severity = LTO_DS_WARNING;
552 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000553 case DS_Remark:
554 Severity = LTO_DS_REMARK;
555 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000556 case DS_Note:
557 Severity = LTO_DS_NOTE;
558 break;
559 }
560 // Create the string that will be reported to the external diagnostic handler.
561 std::string MsgStorage;
562 raw_string_ostream Stream(MsgStorage);
563 DiagnosticPrinterRawOStream DP(Stream);
564 DI.print(DP);
565 Stream.flush();
566
567 // If this method has been called it means someone has set up an external
568 // diagnostic handler. Assert on that.
569 assert(DiagHandler && "Invalid diagnostic handler");
570 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
571}
572
573void
574LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
575 void *Ctxt) {
576 this->DiagHandler = DiagHandler;
577 this->DiagContext = Ctxt;
578 if (!DiagHandler)
579 return Context.setDiagnosticHandler(NULL, NULL);
580 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
581 // diagnostic to the external DiagHandler.
582 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
583}