blob: 17a62906376aac6c9fd567ee989e4c39ca8d1d1c [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"
Rafael Espindola3ea478b2011-08-02 21:50:27 +000018#include "llvm/Analysis/Verifier.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000019#include "llvm/Bitcode/ReaderWriter.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000020#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000021#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/LLVMContext.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000026#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000028#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000029#include "llvm/LTO/LTOModule.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000030#include "llvm/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000031#include "llvm/MC/MCAsmInfo.h"
32#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000033#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000034#include "llvm/PassManager.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000035#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000036#include "llvm/Support/FileSystem.h"
David Greenea31f96c2009-07-14 20:18:05 +000037#include "llvm/Support/FormattedStream.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000038#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000040#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000041#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencerd4227232010-12-09 18:06:07 +000044#include "llvm/Support/system_error.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000045#include "llvm/Target/TargetLibraryInfo.h"
46#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000047#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000048#include "llvm/Target/TargetRegisterInfo.h"
49#include "llvm/Transforms/IPO.h"
50#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000051#include "llvm/Transforms/ObjCARC.h"
Shuxin Yang76d082b2013-08-12 18:29:43 +000052using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000053
Bill Wendling534a6582012-03-31 10:49:43 +000054const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000055#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000056 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000057#else
Bill Wendling534a6582012-03-31 10:49:43 +000058 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000059#endif
60}
61
Bill Wendling39d942b2012-03-31 10:50:14 +000062LTOCodeGenerator::LTOCodeGenerator()
Rafael Espindolac80c9692013-09-04 17:44:24 +000063 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
64 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
65 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000066 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000067}
68
Bill Wendling534a6582012-03-31 10:49:43 +000069LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000070 delete TargetMach;
71 delete NativeObjectFile;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000072 TargetMach = NULL;
73 NativeObjectFile = NULL;
74
75 Linker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000076
Rafael Espindolac80c9692013-09-04 17:44:24 +000077 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
78 E = CodegenOptions.end();
79 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000080 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000081}
82
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000083// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000084// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000085// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000086void LTOCodeGenerator::initializeLTOPasses() {
87 PassRegistry &R = *PassRegistry::getPassRegistry();
88
89 initializeInternalizePassPass(R);
90 initializeIPSCCPPass(R);
91 initializeGlobalOptPass(R);
92 initializeConstantMergePass(R);
93 initializeDAHPass(R);
94 initializeInstCombinerPass(R);
95 initializeSimpleInlinerPass(R);
96 initializePruneEHPass(R);
97 initializeGlobalDCEPass(R);
98 initializeArgPromotionPass(R);
99 initializeJumpThreadingPass(R);
100 initializeSROAPass(R);
101 initializeSROA_DTPass(R);
102 initializeSROA_SSAUpPass(R);
103 initializeFunctionAttrsPass(R);
104 initializeGlobalsModRefPass(R);
105 initializeLICMPass(R);
106 initializeGVNPass(R);
107 initializeMemCpyOptPass(R);
108 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000109 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000110}
111
Bill Wendling0e1824c2012-03-31 11:15:43 +0000112bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000113 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000114
115 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
116 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000117 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000118
Shuxin Yangb6696a92013-08-07 05:19:23 +0000119 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000120}
Bill Wendling39d942b2012-03-31 10:50:14 +0000121
Rafael Espindola0b385c72013-09-30 16:39:19 +0000122void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
123 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
124 Options.NoFramePointerElim = options.NoFramePointerElim;
125 Options.AllowFPOpFusion = options.AllowFPOpFusion;
126 Options.UnsafeFPMath = options.UnsafeFPMath;
127 Options.NoInfsFPMath = options.NoInfsFPMath;
128 Options.NoNaNsFPMath = options.NoNaNsFPMath;
129 Options.HonorSignDependentRoundingFPMathOption =
130 options.HonorSignDependentRoundingFPMathOption;
131 Options.UseSoftFloat = options.UseSoftFloat;
132 Options.FloatABIType = options.FloatABIType;
133 Options.NoZerosInBSS = options.NoZerosInBSS;
134 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
135 Options.DisableTailCalls = options.DisableTailCalls;
136 Options.StackAlignmentOverride = options.StackAlignmentOverride;
137 Options.TrapFuncName = options.TrapFuncName;
138 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
139 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
140 Options.UseInitArray = options.UseInitArray;
141}
142
Shuxin Yangb6696a92013-08-07 05:19:23 +0000143void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000144 switch (debug) {
145 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000146 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000147 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000148
Bill Wendling0e1824c2012-03-31 11:15:43 +0000149 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000150 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000151 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000152 }
153 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000154}
155
Shuxin Yangb6696a92013-08-07 05:19:23 +0000156void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000157 switch (model) {
158 case LTO_CODEGEN_PIC_MODEL_STATIC:
159 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
160 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000161 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000162 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000163 }
164 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000165}
166
Chris Lattner69733952009-08-23 07:49:08 +0000167bool LTOCodeGenerator::writeMergedModules(const char *path,
168 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000169 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000170 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000171
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000172 // mark which symbols can not be internalized
173 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000174
Chris Lattner69733952009-08-23 07:49:08 +0000175 // create output file
176 std::string ErrInfo;
Rafael Espindola6d354812013-07-16 19:44:17 +0000177 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
Chris Lattner69733952009-08-23 07:49:08 +0000178 if (!ErrInfo.empty()) {
179 errMsg = "could not open bitcode file for writing: ";
180 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000181 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000182 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000183
Chris Lattner69733952009-08-23 07:49:08 +0000184 // write bitcode to it
Rafael Espindolac80c9692013-09-04 17:44:24 +0000185 WriteBitcodeToFile(Linker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000186 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000187
Dan Gohmana2233f22010-09-01 14:20:41 +0000188 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000189 errMsg = "could not write bitcode file: ";
190 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000191 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000192 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000193 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000194
Dan Gohman8525fe72010-08-20 16:59:15 +0000195 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000196 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000197}
198
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000199bool LTOCodeGenerator::compile_to_file(const char** name,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000200 bool disableOpt,
201 bool disableInline,
202 bool disableGVNLoadPRE,
203 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000204 // make unique temp .o file to put generated object file
205 SmallString<128> Filename;
206 int FD;
207 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
208 if (EC) {
209 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000210 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000211 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000212
Shuxin Yang1826ae22013-08-12 21:07:31 +0000213 // generate object file
214 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000215
Rafael Espindola0b385c72013-09-30 16:39:19 +0000216 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
217 disableGVNLoadPRE, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000218 objFile.os().close();
219 if (objFile.os().has_error()) {
220 objFile.os().clear_error();
221 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000222 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000223 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000224
Shuxin Yang1826ae22013-08-12 21:07:31 +0000225 objFile.keep();
226 if (!genResult) {
227 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000228 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000229 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000230
Rafael Espindolac80c9692013-09-04 17:44:24 +0000231 NativeObjectPath = Filename.c_str();
232 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000233 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000234}
235
Rafael Espindola0b385c72013-09-30 16:39:19 +0000236const void* LTOCodeGenerator::compile(size_t* length,
237 bool disableOpt,
238 bool disableInline,
239 bool disableGVNLoadPRE,
240 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000241 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000242 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
243 errMsg))
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000244 return NULL;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000245
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000246 // remove old buffer if compile() called twice
Rafael Espindolac80c9692013-09-04 17:44:24 +0000247 delete NativeObjectFile;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000248
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000249 // read .o file into memory buffer
250 OwningPtr<MemoryBuffer> BuffPtr;
251 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
252 errMsg = ec.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000253 sys::fs::remove(NativeObjectPath);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000254 return NULL;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000255 }
Rafael Espindolac80c9692013-09-04 17:44:24 +0000256 NativeObjectFile = BuffPtr.take();
Rafael Espindolafac373c2011-02-24 21:04:06 +0000257
Shuxin Yang1826ae22013-08-12 21:07:31 +0000258 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000259 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000260
Shuxin Yang1826ae22013-08-12 21:07:31 +0000261 // return buffer, unless error
Rafael Espindolac80c9692013-09-04 17:44:24 +0000262 if (NativeObjectFile == NULL)
Shuxin Yang1826ae22013-08-12 21:07:31 +0000263 return NULL;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000264 *length = NativeObjectFile->getBufferSize();
265 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000266}
267
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000268bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000269 if (TargetMach != NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000270 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000271
Rafael Espindolac80c9692013-09-04 17:44:24 +0000272 std::string TripleStr = Linker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000273 if (TripleStr.empty())
274 TripleStr = sys::getDefaultTargetTriple();
275 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000276
Bill Wendling45f74e32012-08-06 22:52:45 +0000277 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000278 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling6a0abed2012-08-08 22:03:50 +0000279 if (march == NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000280 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000281
Bill Wendling45f74e32012-08-06 22:52:45 +0000282 // The relocation model is actually a static member of TargetMachine and
283 // needs to be set before the TargetMachine is instantiated.
284 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000285 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000286 case LTO_CODEGEN_PIC_MODEL_STATIC:
287 RelocModel = Reloc::Static;
288 break;
289 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
290 RelocModel = Reloc::PIC_;
291 break;
292 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
293 RelocModel = Reloc::DynamicNoPIC;
294 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000295 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000296
297 // construct LTOModule, hand over ownership of module and target
298 SubtargetFeatures Features;
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000299 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000300 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000301 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000302 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000303 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000304 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000305 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000306 MCpu = "yonah";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000307 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000308
Rafael Espindolac80c9692013-09-04 17:44:24 +0000309 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
310 RelocModel, CodeModel::Default,
311 CodeGenOpt::Aggressive);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000312 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000313}
314
Bill Wendling0e1824c2012-03-31 11:15:43 +0000315void LTOCodeGenerator::
316applyRestriction(GlobalValue &GV,
Justin Bognerb10a5202013-11-12 21:44:01 +0000317 const ArrayRef<StringRef> &Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000318 std::vector<const char*> &MustPreserveList,
319 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
320 Mangler &Mangler) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000321 SmallString<64> Buffer;
Rafael Espindola117b20c2013-12-05 05:53:12 +0000322 Mangler.getNameWithPrefix(Buffer, &GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000323
324 if (GV.isDeclaration())
325 return;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000326 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000327 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000328 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000329 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000330
331 // Conservatively append user-supplied runtime library functions to
332 // llvm.compiler.used. These could be internalized and deleted by
333 // optimizations like -globalopt, causing problems when later optimizations
334 // add new library calls (e.g., llvm.memset => memset and printf => puts).
335 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
336 if (isa<Function>(GV) &&
337 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
338 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000339}
340
341static void findUsedValues(GlobalVariable *LLVMUsed,
342 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
343 if (LLVMUsed == 0) return;
344
Rafael Espindolacc111b22013-04-24 17:54:35 +0000345 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000346 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000347 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000348 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000349 UsedValues.insert(GV);
350}
351
Justin Bognerb10a5202013-11-12 21:44:01 +0000352static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
353 const TargetLibraryInfo& TLI,
354 const TargetLowering *Lowering)
355{
356 // TargetLibraryInfo has info on C runtime library calls on the current
357 // target.
358 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
359 I != E; ++I) {
360 LibFunc::Func F = static_cast<LibFunc::Func>(I);
361 if (TLI.has(F))
362 Libcalls.push_back(TLI.getName(F));
363 }
364
365 // TargetLowering has info on library calls that CodeGen expects to be
366 // available, both from the C runtime and compiler-rt.
367 if (Lowering)
368 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
369 I != E; ++I)
370 if (const char *Name
371 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
372 Libcalls.push_back(Name);
373
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000374 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000375 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
376 Libcalls.end());
377}
378
Chris Lattner2eff5052010-03-12 18:44:54 +0000379void LTOCodeGenerator::applyScopeRestrictions() {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000380 if (ScopeRestrictionsDone)
381 return;
382 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000383
Chris Lattner2eff5052010-03-12 18:44:54 +0000384 // Start off with a verification pass.
385 PassManager passes;
386 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000387
Bill Wendling39d942b2012-03-31 10:50:14 +0000388 // mark which symbols can not be internalized
Rafael Espindola58873562014-01-03 19:21:54 +0000389 Mangler Mangler(TargetMach->getDataLayout());
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000390 std::vector<const char*> MustPreserveList;
391 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000392 std::vector<StringRef> Libcalls;
393 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
394 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000395
396 for (Module::iterator f = mergedModule->begin(),
397 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000398 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000399 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000400 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000401 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000402 for (Module::alias_iterator a = mergedModule->alias_begin(),
403 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000404 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000405
406 GlobalVariable *LLVMCompilerUsed =
407 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000408 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000409 if (LLVMCompilerUsed)
410 LLVMCompilerUsed->eraseFromParent();
411
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000412 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000413 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000414 std::vector<Constant*> asmUsed2;
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000415 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
416 e = AsmUsed.end(); i !=e; ++i) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000417 GlobalValue *GV = *i;
418 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
419 asmUsed2.push_back(c);
420 }
421
422 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
423 LLVMCompilerUsed =
424 new llvm::GlobalVariable(*mergedModule, ATy, false,
425 llvm::GlobalValue::AppendingLinkage,
426 llvm::ConstantArray::get(ATy, asmUsed2),
427 "llvm.compiler.used");
428
429 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000430 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000431
Rafael Espindola282a4702013-10-31 20:51:58 +0000432 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000433
Chris Lattner2eff5052010-03-12 18:44:54 +0000434 // apply scope restrictions
435 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000436
Rafael Espindolac80c9692013-09-04 17:44:24 +0000437 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000438}
439
Nick Kledzik07b4a622008-02-26 20:26:43 +0000440/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000441bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000442 bool DisableOpt,
443 bool DisableInline,
444 bool DisableGVNLoadPRE,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000445 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000446 if (!this->determineTarget(errMsg))
447 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000448
Rafael Espindolac80c9692013-09-04 17:44:24 +0000449 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000450
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000451 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000452 this->applyScopeRestrictions();
453
Bill Wendling0e1824c2012-03-31 11:15:43 +0000454 // Instantiate the pass manager to organize the passes.
455 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000456
Bill Wendling0e1824c2012-03-31 11:15:43 +0000457 // Start off with a verification pass.
458 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000459
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000460 // Add an appropriate DataLayout instance for this module...
Rafael Espindolac80c9692013-09-04 17:44:24 +0000461 passes.add(new DataLayout(*TargetMach->getDataLayout()));
Yi Jiang53823be2013-12-12 01:37:39 +0000462
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000463 // Add appropriate TargetLibraryInfo for this module.
Yi Jiang53823be2013-12-12 01:37:39 +0000464 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
465
Rafael Espindolac80c9692013-09-04 17:44:24 +0000466 TargetMach->addAnalysisPasses(passes);
Bill Wendling39d942b2012-03-31 10:50:14 +0000467
Rafael Espindola0ecb8fa2012-04-16 10:58:38 +0000468 // Enabling internalize here would use its AllButMain variant. It
469 // keeps only main if it exists and does nothing for libraries. Instead
470 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000471 if (!DisableOpt)
Bill Wendlingc7e0a042013-02-28 14:11:10 +0000472 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling4a8fc8f2012-12-10 21:33:45 +0000473 /*Internalize=*/false,
Bill Wendling932b9922012-04-02 22:16:50 +0000474 !DisableInline,
475 DisableGVNLoadPRE);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000476
Bill Wendling0e1824c2012-03-31 11:15:43 +0000477 // Make sure everything is still good.
478 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000479
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000480 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000481
Rafael Espindolac80c9692013-09-04 17:44:24 +0000482 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
483 TargetMach->addAnalysisPasses(codeGenPasses);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000484
Bill Wendling0e1824c2012-03-31 11:15:43 +0000485 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000486
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000487 // If the bitcode files contain ARC code and were compiled with optimization,
488 // the ObjCARCContractPass must be run, so do it unconditionally here.
489 codeGenPasses.add(createObjCARCContractPass());
490
Rafael Espindolac80c9692013-09-04 17:44:24 +0000491 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
492 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000493 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000494 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000495 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000496
Bill Wendling0e1824c2012-03-31 11:15:43 +0000497 // Run our queue of passes all at once now, efficiently.
498 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000499
Bill Wendling0e1824c2012-03-31 11:15:43 +0000500 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000501 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000502
Shuxin Yang95866fa2013-08-06 21:51:21 +0000503 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000504}
505
Bill Wendling534a6582012-03-31 10:49:43 +0000506/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
507/// LTO problems.
508void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
509 for (std::pair<StringRef, StringRef> o = getToken(options);
510 !o.first.empty(); o = getToken(o.second)) {
511 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
512 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000513 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000514 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000515 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000516 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000517}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000518
519void LTOCodeGenerator::parseCodeGenDebugOptions() {
520 // if options were requested, set them
521 if (!CodegenOptions.empty())
522 cl::ParseCommandLineOptions(CodegenOptions.size(),
523 const_cast<char **>(&CodegenOptions[0]));
524}