blob: 88f606160d8d949ed43f9bb0bed3166a110bbbcf [file] [log] [blame]
Nick Kledzik77595fc2008-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 Wendling76b13ed2012-03-31 10:50:14 +00007//
Nick Kledzik77595fc2008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling76b13ed2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik77595fc2008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbournecc488542013-09-24 23:52:22 +000015#include "llvm/LTO/LTOCodeGenerator.h"
16#include "llvm/LTO/LTOModule.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000017#include "llvm/ADT/StringExtras.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000018#include "llvm/Analysis/Passes.h"
Rafael Espindolac684e832011-08-02 21:50:27 +000019#include "llvm/Analysis/Verifier.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000020#include "llvm/Bitcode/ReaderWriter.h"
Bill Wendlingc94c5622012-03-31 11:15:43 +000021#include "llvm/Config/config.h"
Chandler Carruth0b8c9a82013-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"
26#include "llvm/IR/Module.h"
Shuxin Yang8945f752013-07-22 18:40:34 +000027#include "llvm/InitializePasses.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000028#include "llvm/Linker.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000029#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCContext.h"
Evan Chengab8be962011-06-29 01:14:12 +000031#include "llvm/MC/SubtargetFeature.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000032#include "llvm/PassManager.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000033#include "llvm/Support/CommandLine.h"
Rafael Espindola68c0efa2013-06-17 18:05:35 +000034#include "llvm/Support/FileSystem.h"
David Greene71847812009-07-14 20:18:05 +000035#include "llvm/Support/FormattedStream.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000036#include "llvm/Support/Host.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000038#include "llvm/Support/Signals.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000039#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000041#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000042#include "llvm/Support/system_error.h"
Rafael Espindolac13c9e52013-09-30 16:39:19 +000043#include "llvm/Target/TargetOptions.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000044#include "llvm/Target/TargetRegisterInfo.h"
Peter Collingbournecc488542013-09-24 23:52:22 +000045#include "llvm/Target/Mangler.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000046#include "llvm/Transforms/IPO.h"
47#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsond6965442013-03-29 23:28:55 +000048#include "llvm/Transforms/ObjCARC.h"
Shuxin Yang67d135a2013-08-12 18:29:43 +000049using namespace llvm;
Shuxin Yang67d135a2013-08-12 18:29:43 +000050
Bill Wendlingcaf71d42012-03-31 10:49:43 +000051const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik77595fc2008-02-26 20:26:43 +000052#ifdef LLVM_VERSION_INFO
Bill Wendlingcaf71d42012-03-31 10:49:43 +000053 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik77595fc2008-02-26 20:26:43 +000054#else
Bill Wendlingcaf71d42012-03-31 10:49:43 +000055 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik77595fc2008-02-26 20:26:43 +000056#endif
57}
58
Bill Wendling76b13ed2012-03-31 10:50:14 +000059LTOCodeGenerator::LTOCodeGenerator()
Rafael Espindola66efc632013-09-04 17:44:24 +000060 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
61 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
62 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
Shuxin Yang8945f752013-07-22 18:40:34 +000063 initializeLTOPasses();
Nick Kledzik77595fc2008-02-26 20:26:43 +000064}
65
Bill Wendlingcaf71d42012-03-31 10:49:43 +000066LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindola66efc632013-09-04 17:44:24 +000067 delete TargetMach;
68 delete NativeObjectFile;
Bill Wendlingb4a0ba12013-10-16 08:59:57 +000069 TargetMach = NULL;
70 NativeObjectFile = NULL;
71
72 Linker.deleteModule();
Bill Wendlingcaf71d42012-03-31 10:49:43 +000073
Rafael Espindola66efc632013-09-04 17:44:24 +000074 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
75 E = CodegenOptions.end();
76 I != E; ++I)
Bill Wendlingcaf71d42012-03-31 10:49:43 +000077 free(*I);
Nick Kledzik77595fc2008-02-26 20:26:43 +000078}
79
Shuxin Yang8945f752013-07-22 18:40:34 +000080// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangc679d6b2013-07-23 06:44:34 +000081// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Shuxin Yang8945f752013-07-22 18:40:34 +000082// passes are initialized.
83//
84void LTOCodeGenerator::initializeLTOPasses() {
85 PassRegistry &R = *PassRegistry::getPassRegistry();
86
87 initializeInternalizePassPass(R);
88 initializeIPSCCPPass(R);
89 initializeGlobalOptPass(R);
90 initializeConstantMergePass(R);
91 initializeDAHPass(R);
92 initializeInstCombinerPass(R);
93 initializeSimpleInlinerPass(R);
94 initializePruneEHPass(R);
95 initializeGlobalDCEPass(R);
96 initializeArgPromotionPass(R);
97 initializeJumpThreadingPass(R);
98 initializeSROAPass(R);
99 initializeSROA_DTPass(R);
100 initializeSROA_SSAUpPass(R);
101 initializeFunctionAttrsPass(R);
102 initializeGlobalsModRefPass(R);
103 initializeLICMPass(R);
104 initializeGVNPass(R);
105 initializeMemCpyOptPass(R);
106 initializeDCEPass(R);
Tom Stellard01d72032013-08-06 02:43:45 +0000107 initializeCFGSimplifyPassPass(R);
Shuxin Yang8945f752013-07-22 18:40:34 +0000108}
109
Bill Wendlingc94c5622012-03-31 11:15:43 +0000110bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindola66efc632013-09-04 17:44:24 +0000111 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000112
113 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
114 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindola66efc632013-09-04 17:44:24 +0000115 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000116
Shuxin Yang235089b2013-08-07 05:19:23 +0000117 return !ret;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000118}
Bill Wendling76b13ed2012-03-31 10:50:14 +0000119
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000120void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
121 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
122 Options.NoFramePointerElim = options.NoFramePointerElim;
123 Options.AllowFPOpFusion = options.AllowFPOpFusion;
124 Options.UnsafeFPMath = options.UnsafeFPMath;
125 Options.NoInfsFPMath = options.NoInfsFPMath;
126 Options.NoNaNsFPMath = options.NoNaNsFPMath;
127 Options.HonorSignDependentRoundingFPMathOption =
128 options.HonorSignDependentRoundingFPMathOption;
129 Options.UseSoftFloat = options.UseSoftFloat;
130 Options.FloatABIType = options.FloatABIType;
131 Options.NoZerosInBSS = options.NoZerosInBSS;
132 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
133 Options.DisableTailCalls = options.DisableTailCalls;
134 Options.StackAlignmentOverride = options.StackAlignmentOverride;
135 Options.TrapFuncName = options.TrapFuncName;
136 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
137 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
138 Options.UseInitArray = options.UseInitArray;
139}
140
Shuxin Yang235089b2013-08-07 05:19:23 +0000141void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000142 switch (debug) {
143 case LTO_DEBUG_MODEL_NONE:
Rafael Espindola66efc632013-09-04 17:44:24 +0000144 EmitDwarfDebugInfo = false;
Shuxin Yang235089b2013-08-07 05:19:23 +0000145 return;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000146
Bill Wendlingc94c5622012-03-31 11:15:43 +0000147 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindola66efc632013-09-04 17:44:24 +0000148 EmitDwarfDebugInfo = true;
Shuxin Yang235089b2013-08-07 05:19:23 +0000149 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000150 }
151 llvm_unreachable("Unknown debug format!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000152}
153
Shuxin Yang235089b2013-08-07 05:19:23 +0000154void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000155 switch (model) {
156 case LTO_CODEGEN_PIC_MODEL_STATIC:
157 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
158 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
Rafael Espindola66efc632013-09-04 17:44:24 +0000159 CodeModel = model;
Shuxin Yang235089b2013-08-07 05:19:23 +0000160 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000161 }
162 llvm_unreachable("Unknown PIC model!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000163}
164
Chris Lattnerb515d752009-08-23 07:49:08 +0000165bool LTOCodeGenerator::writeMergedModules(const char *path,
166 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000167 if (!determineTarget(errMsg))
Shuxin Yang235089b2013-08-07 05:19:23 +0000168 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000169
Bill Wendling6ba2ed52013-08-08 23:51:04 +0000170 // mark which symbols can not be internalized
171 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000172
Chris Lattnerb515d752009-08-23 07:49:08 +0000173 // create output file
174 std::string ErrInfo;
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000175 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000176 if (!ErrInfo.empty()) {
177 errMsg = "could not open bitcode file for writing: ";
178 errMsg += path;
Shuxin Yang235089b2013-08-07 05:19:23 +0000179 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000180 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000181
Chris Lattnerb515d752009-08-23 07:49:08 +0000182 // write bitcode to it
Rafael Espindola66efc632013-09-04 17:44:24 +0000183 WriteBitcodeToFile(Linker.getModule(), Out.os());
Dan Gohmand4c45432010-09-01 14:20:41 +0000184 Out.os().close();
Dan Gohman4b7416b2010-05-27 20:19:47 +0000185
Dan Gohmand4c45432010-09-01 14:20:41 +0000186 if (Out.os().has_error()) {
Chris Lattnerb515d752009-08-23 07:49:08 +0000187 errMsg = "could not write bitcode file: ";
188 errMsg += path;
Dan Gohmand4c45432010-09-01 14:20:41 +0000189 Out.os().clear_error();
Shuxin Yang235089b2013-08-07 05:19:23 +0000190 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000191 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000192
Dan Gohmanf2914012010-08-20 16:59:15 +0000193 Out.keep();
Shuxin Yang235089b2013-08-07 05:19:23 +0000194 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000195}
196
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000197bool LTOCodeGenerator::compile_to_file(const char** name,
198 bool disableOpt,
199 bool disableInline,
200 bool disableGVNLoadPRE,
201 std::string& errMsg) {
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000202 // make unique temp .o file to put generated object file
203 SmallString<128> Filename;
204 int FD;
205 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
206 if (EC) {
207 errMsg = EC.message();
Shuxin Yang235089b2013-08-07 05:19:23 +0000208 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000209 }
Rafael Espindola6421a882011-03-22 20:57:13 +0000210
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000211 // generate object file
212 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendlingc94c5622012-03-31 11:15:43 +0000213
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000214 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
215 disableGVNLoadPRE, errMsg);
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000216 objFile.os().close();
217 if (objFile.os().has_error()) {
218 objFile.os().clear_error();
219 sys::fs::remove(Twine(Filename));
Shuxin Yang235089b2013-08-07 05:19:23 +0000220 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000221 }
Bill Wendlingc94c5622012-03-31 11:15:43 +0000222
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000223 objFile.keep();
224 if (!genResult) {
225 sys::fs::remove(Twine(Filename));
Shuxin Yang235089b2013-08-07 05:19:23 +0000226 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000227 }
Rafael Espindola6421a882011-03-22 20:57:13 +0000228
Rafael Espindola66efc632013-09-04 17:44:24 +0000229 NativeObjectPath = Filename.c_str();
230 *name = NativeObjectPath.c_str();
Shuxin Yang235089b2013-08-07 05:19:23 +0000231 return true;
Rafael Espindola6421a882011-03-22 20:57:13 +0000232}
233
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000234const void* LTOCodeGenerator::compile(size_t* length,
235 bool disableOpt,
236 bool disableInline,
237 bool disableGVNLoadPRE,
238 std::string& errMsg) {
Rafael Espindola6421a882011-03-22 20:57:13 +0000239 const char *name;
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000240 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
241 errMsg))
Rafael Espindola6421a882011-03-22 20:57:13 +0000242 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000243
Rafael Espindola6421a882011-03-22 20:57:13 +0000244 // remove old buffer if compile() called twice
Rafael Espindola66efc632013-09-04 17:44:24 +0000245 delete NativeObjectFile;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000246
Rafael Espindola6421a882011-03-22 20:57:13 +0000247 // read .o file into memory buffer
248 OwningPtr<MemoryBuffer> BuffPtr;
249 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
250 errMsg = ec.message();
Rafael Espindola66efc632013-09-04 17:44:24 +0000251 sys::fs::remove(NativeObjectPath);
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000252 return NULL;
Rafael Espindola6421a882011-03-22 20:57:13 +0000253 }
Rafael Espindola66efc632013-09-04 17:44:24 +0000254 NativeObjectFile = BuffPtr.take();
Rafael Espindolae9efea12011-02-24 21:04:06 +0000255
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000256 // remove temp files
Rafael Espindola66efc632013-09-04 17:44:24 +0000257 sys::fs::remove(NativeObjectPath);
Rafael Espindolae9efea12011-02-24 21:04:06 +0000258
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000259 // return buffer, unless error
Rafael Espindola66efc632013-09-04 17:44:24 +0000260 if (NativeObjectFile == NULL)
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000261 return NULL;
Rafael Espindola66efc632013-09-04 17:44:24 +0000262 *length = NativeObjectFile->getBufferSize();
263 return NativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000264}
265
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000266bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Rafael Espindola66efc632013-09-04 17:44:24 +0000267 if (TargetMach != NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000268 return true;
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000269
Rafael Espindola66efc632013-09-04 17:44:24 +0000270 std::string TripleStr = Linker.getModule()->getTargetTriple();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000271 if (TripleStr.empty())
272 TripleStr = sys::getDefaultTargetTriple();
273 llvm::Triple Triple(TripleStr);
Bill Wendling604a8182008-06-18 06:35:30 +0000274
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000275 // create target machine from info for merged modules
Bob Wilson47ed8a12012-10-12 17:39:25 +0000276 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling0ca36af2012-08-08 22:03:50 +0000277 if (march == NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000278 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000279
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000280 // The relocation model is actually a static member of TargetMachine and
281 // needs to be set before the TargetMachine is instantiated.
282 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindola66efc632013-09-04 17:44:24 +0000283 switch (CodeModel) {
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000284 case LTO_CODEGEN_PIC_MODEL_STATIC:
285 RelocModel = Reloc::Static;
286 break;
287 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
288 RelocModel = Reloc::PIC_;
289 break;
290 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
291 RelocModel = Reloc::DynamicNoPIC;
292 break;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000293 }
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000294
295 // construct LTOModule, hand over ownership of module and target
296 SubtargetFeatures Features;
Bob Wilson47ed8a12012-10-12 17:39:25 +0000297 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000298 std::string FeatureStr = Features.getString();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000299 // Set a default CPU for Darwin triples.
Rafael Espindola66efc632013-09-04 17:44:24 +0000300 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson47ed8a12012-10-12 17:39:25 +0000301 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindola66efc632013-09-04 17:44:24 +0000302 MCpu = "core2";
Bob Wilson47ed8a12012-10-12 17:39:25 +0000303 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindola66efc632013-09-04 17:44:24 +0000304 MCpu = "yonah";
Bob Wilson47ed8a12012-10-12 17:39:25 +0000305 }
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000306
Rafael Espindola66efc632013-09-04 17:44:24 +0000307 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
308 RelocModel, CodeModel::Default,
309 CodeGenOpt::Aggressive);
Shuxin Yang08809392013-08-06 21:51:21 +0000310 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000311}
312
Bill Wendlingc94c5622012-03-31 11:15:43 +0000313void LTOCodeGenerator::
314applyRestriction(GlobalValue &GV,
Rafael Espindola775079c2013-09-04 20:08:46 +0000315 std::vector<const char*> &MustPreserveList,
Rafael Espindola43890092013-10-03 18:29:09 +0000316 std::vector<const char*> &DSOList,
Rafael Espindola775079c2013-09-04 20:08:46 +0000317 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
318 Mangler &Mangler) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000319 SmallString<64> Buffer;
Rafael Espindola775079c2013-09-04 20:08:46 +0000320 Mangler.getNameWithPrefix(Buffer, &GV, false);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000321
322 if (GV.isDeclaration())
323 return;
Rafael Espindola66efc632013-09-04 17:44:24 +0000324 if (MustPreserveSymbols.count(Buffer))
Rafael Espindola775079c2013-09-04 20:08:46 +0000325 MustPreserveList.push_back(GV.getName().data());
Rafael Espindola43890092013-10-03 18:29:09 +0000326 if (DSOSymbols.count(Buffer))
327 DSOList.push_back(GV.getName().data());
Rafael Espindola66efc632013-09-04 17:44:24 +0000328 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindola775079c2013-09-04 20:08:46 +0000329 AsmUsed.insert(&GV);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000330}
331
332static void findUsedValues(GlobalVariable *LLVMUsed,
333 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
334 if (LLVMUsed == 0) return;
335
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000336 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola38c4e532011-03-02 04:14:42 +0000337 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling76b13ed2012-03-31 10:50:14 +0000338 if (GlobalValue *GV =
Bill Wendlingc94c5622012-03-31 11:15:43 +0000339 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000340 UsedValues.insert(GV);
341}
342
Chris Lattner5ef31a02010-03-12 18:44:54 +0000343void LTOCodeGenerator::applyScopeRestrictions() {
Rafael Espindola66efc632013-09-04 17:44:24 +0000344 if (ScopeRestrictionsDone)
345 return;
346 Module *mergedModule = Linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000347
Chris Lattner5ef31a02010-03-12 18:44:54 +0000348 // Start off with a verification pass.
349 PassManager passes;
350 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000351
Bill Wendling76b13ed2012-03-31 10:50:14 +0000352 // mark which symbols can not be internalized
Rafael Espindola66efc632013-09-04 17:44:24 +0000353 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
354 NULL);
Rafael Espindola775079c2013-09-04 20:08:46 +0000355 Mangler Mangler(MContext, TargetMach);
356 std::vector<const char*> MustPreserveList;
Rafael Espindola43890092013-10-03 18:29:09 +0000357 std::vector<const char*> DSOList;
Rafael Espindola775079c2013-09-04 20:08:46 +0000358 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000359
360 for (Module::iterator f = mergedModule->begin(),
361 e = mergedModule->end(); f != e; ++f)
Rafael Espindola43890092013-10-03 18:29:09 +0000362 applyRestriction(*f, MustPreserveList, DSOList, AsmUsed, Mangler);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000363 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola38c4e532011-03-02 04:14:42 +0000364 e = mergedModule->global_end(); v != e; ++v)
Rafael Espindola43890092013-10-03 18:29:09 +0000365 applyRestriction(*v, MustPreserveList, DSOList, AsmUsed, Mangler);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000366 for (Module::alias_iterator a = mergedModule->alias_begin(),
367 e = mergedModule->alias_end(); a != e; ++a)
Rafael Espindola43890092013-10-03 18:29:09 +0000368 applyRestriction(*a, MustPreserveList, DSOList, AsmUsed, Mangler);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000369
370 GlobalVariable *LLVMCompilerUsed =
371 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindola775079c2013-09-04 20:08:46 +0000372 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000373 if (LLVMCompilerUsed)
374 LLVMCompilerUsed->eraseFromParent();
375
Rafael Espindola775079c2013-09-04 20:08:46 +0000376 if (!AsmUsed.empty()) {
Rafael Espindola66efc632013-09-04 17:44:24 +0000377 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000378 std::vector<Constant*> asmUsed2;
Rafael Espindola775079c2013-09-04 20:08:46 +0000379 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
380 e = AsmUsed.end(); i !=e; ++i) {
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000381 GlobalValue *GV = *i;
382 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
383 asmUsed2.push_back(c);
384 }
385
386 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
387 LLVMCompilerUsed =
388 new llvm::GlobalVariable(*mergedModule, ATy, false,
389 llvm::GlobalValue::AppendingLinkage,
390 llvm::ConstantArray::get(ATy, asmUsed2),
391 "llvm.compiler.used");
392
393 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner5ef31a02010-03-12 18:44:54 +0000394 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000395
Rafael Espindola43890092013-10-03 18:29:09 +0000396 passes.add(createInternalizePass(MustPreserveList, DSOList));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000397
Chris Lattner5ef31a02010-03-12 18:44:54 +0000398 // apply scope restrictions
399 passes.run(*mergedModule);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000400
Rafael Espindola66efc632013-09-04 17:44:24 +0000401 ScopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000402}
403
Nick Kledzik77595fc2008-02-26 20:26:43 +0000404/// Optimize merged modules using various IPO passes
Chris Lattner817a01f2011-05-22 00:20:07 +0000405bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000406 bool DisableOpt,
407 bool DisableInline,
408 bool DisableGVNLoadPRE,
Chris Lattner817a01f2011-05-22 00:20:07 +0000409 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000410 if (!this->determineTarget(errMsg))
411 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000412
Rafael Espindola66efc632013-09-04 17:44:24 +0000413 Module *mergedModule = Linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000414
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000415 // Mark which symbols can not be internalized
Bill Wendling64d5b282012-04-09 22:18:01 +0000416 this->applyScopeRestrictions();
417
Bill Wendlingc94c5622012-03-31 11:15:43 +0000418 // Instantiate the pass manager to organize the passes.
419 PassManager passes;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000420
Bill Wendlingc94c5622012-03-31 11:15:43 +0000421 // Start off with a verification pass.
422 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000423
Micah Villmow791cfc22012-10-08 16:39:34 +0000424 // Add an appropriate DataLayout instance for this module...
Rafael Espindola66efc632013-09-04 17:44:24 +0000425 passes.add(new DataLayout(*TargetMach->getDataLayout()));
426 TargetMach->addAnalysisPasses(passes);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000427
Rafael Espindola4d2e9d92012-04-16 10:58:38 +0000428 // Enabling internalize here would use its AllButMain variant. It
429 // keeps only main if it exists and does nothing for libraries. Instead
430 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000431 if (!DisableOpt)
Bill Wendling6303b662013-02-28 14:11:10 +0000432 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling50f31832012-12-10 21:33:45 +0000433 /*Internalize=*/false,
Bill Wendling3197b442012-04-02 22:16:50 +0000434 !DisableInline,
435 DisableGVNLoadPRE);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000436
Bill Wendlingc94c5622012-03-31 11:15:43 +0000437 // Make sure everything is still good.
438 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000439
Lang Hamesa991b252013-03-13 21:18:46 +0000440 PassManager codeGenPasses;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000441
Rafael Espindola66efc632013-09-04 17:44:24 +0000442 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
443 TargetMach->addAnalysisPasses(codeGenPasses);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000444
Bill Wendlingc94c5622012-03-31 11:15:43 +0000445 formatted_raw_ostream Out(out);
Dan Gohmand4c45432010-09-01 14:20:41 +0000446
Bob Wilsond6965442013-03-29 23:28:55 +0000447 // If the bitcode files contain ARC code and were compiled with optimization,
448 // the ObjCARCContractPass must be run, so do it unconditionally here.
449 codeGenPasses.add(createObjCARCContractPass());
450
Rafael Espindola66efc632013-09-04 17:44:24 +0000451 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
452 TargetMachine::CGFT_ObjectFile)) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000453 errMsg = "target file type not supported";
Shuxin Yang08809392013-08-06 21:51:21 +0000454 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000455 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000456
Bill Wendlingc94c5622012-03-31 11:15:43 +0000457 // Run our queue of passes all at once now, efficiently.
458 passes.run(*mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000459
Bill Wendlingc94c5622012-03-31 11:15:43 +0000460 // Run the code generator, and write assembly file
Lang Hamesa991b252013-03-13 21:18:46 +0000461 codeGenPasses.run(*mergedModule);
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000462
Shuxin Yang08809392013-08-06 21:51:21 +0000463 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000464}
465
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000466/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
467/// LTO problems.
468void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
469 for (std::pair<StringRef, StringRef> o = getToken(options);
470 !o.first.empty(); o = getToken(o.second)) {
471 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
472 // that.
Rafael Espindola66efc632013-09-04 17:44:24 +0000473 if (CodegenOptions.empty())
Peter Collingbournecc488542013-09-24 23:52:22 +0000474 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindola66efc632013-09-04 17:44:24 +0000475 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000476 }
Nick Kledzik920ae982008-07-08 21:14:10 +0000477}
Rafael Espindola0e95b3a2013-10-02 14:36:23 +0000478
479void LTOCodeGenerator::parseCodeGenDebugOptions() {
480 // if options were requested, set them
481 if (!CodegenOptions.empty())
482 cl::ParseCommandLineOptions(CodegenOptions.size(),
483 const_cast<char **>(&CodegenOptions[0]));
484}