blob: 3abb6238b3e6a07d519d61dbc4a533a275f76da4 [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;
69 delete Linker.getModule();
Bill Wendlingcaf71d42012-03-31 10:49:43 +000070
Rafael Espindola66efc632013-09-04 17:44:24 +000071 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
72 E = CodegenOptions.end();
73 I != E; ++I)
Bill Wendlingcaf71d42012-03-31 10:49:43 +000074 free(*I);
Nick Kledzik77595fc2008-02-26 20:26:43 +000075}
76
Shuxin Yang8945f752013-07-22 18:40:34 +000077// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangc679d6b2013-07-23 06:44:34 +000078// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Shuxin Yang8945f752013-07-22 18:40:34 +000079// passes are initialized.
80//
81void LTOCodeGenerator::initializeLTOPasses() {
82 PassRegistry &R = *PassRegistry::getPassRegistry();
83
84 initializeInternalizePassPass(R);
85 initializeIPSCCPPass(R);
86 initializeGlobalOptPass(R);
87 initializeConstantMergePass(R);
88 initializeDAHPass(R);
89 initializeInstCombinerPass(R);
90 initializeSimpleInlinerPass(R);
91 initializePruneEHPass(R);
92 initializeGlobalDCEPass(R);
93 initializeArgPromotionPass(R);
94 initializeJumpThreadingPass(R);
95 initializeSROAPass(R);
96 initializeSROA_DTPass(R);
97 initializeSROA_SSAUpPass(R);
98 initializeFunctionAttrsPass(R);
99 initializeGlobalsModRefPass(R);
100 initializeLICMPass(R);
101 initializeGVNPass(R);
102 initializeMemCpyOptPass(R);
103 initializeDCEPass(R);
Tom Stellard01d72032013-08-06 02:43:45 +0000104 initializeCFGSimplifyPassPass(R);
Shuxin Yang8945f752013-07-22 18:40:34 +0000105}
106
Bill Wendlingc94c5622012-03-31 11:15:43 +0000107bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindola66efc632013-09-04 17:44:24 +0000108 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000109
110 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
111 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindola66efc632013-09-04 17:44:24 +0000112 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000113
Shuxin Yang235089b2013-08-07 05:19:23 +0000114 return !ret;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000115}
Bill Wendling76b13ed2012-03-31 10:50:14 +0000116
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000117void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
118 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
119 Options.NoFramePointerElim = options.NoFramePointerElim;
120 Options.AllowFPOpFusion = options.AllowFPOpFusion;
121 Options.UnsafeFPMath = options.UnsafeFPMath;
122 Options.NoInfsFPMath = options.NoInfsFPMath;
123 Options.NoNaNsFPMath = options.NoNaNsFPMath;
124 Options.HonorSignDependentRoundingFPMathOption =
125 options.HonorSignDependentRoundingFPMathOption;
126 Options.UseSoftFloat = options.UseSoftFloat;
127 Options.FloatABIType = options.FloatABIType;
128 Options.NoZerosInBSS = options.NoZerosInBSS;
129 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
130 Options.DisableTailCalls = options.DisableTailCalls;
131 Options.StackAlignmentOverride = options.StackAlignmentOverride;
132 Options.TrapFuncName = options.TrapFuncName;
133 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
134 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
135 Options.UseInitArray = options.UseInitArray;
136}
137
Shuxin Yang235089b2013-08-07 05:19:23 +0000138void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000139 switch (debug) {
140 case LTO_DEBUG_MODEL_NONE:
Rafael Espindola66efc632013-09-04 17:44:24 +0000141 EmitDwarfDebugInfo = false;
Shuxin Yang235089b2013-08-07 05:19:23 +0000142 return;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000143
Bill Wendlingc94c5622012-03-31 11:15:43 +0000144 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindola66efc632013-09-04 17:44:24 +0000145 EmitDwarfDebugInfo = true;
Shuxin Yang235089b2013-08-07 05:19:23 +0000146 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000147 }
148 llvm_unreachable("Unknown debug format!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000149}
150
Shuxin Yang235089b2013-08-07 05:19:23 +0000151void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000152 switch (model) {
153 case LTO_CODEGEN_PIC_MODEL_STATIC:
154 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
155 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
Rafael Espindola66efc632013-09-04 17:44:24 +0000156 CodeModel = model;
Shuxin Yang235089b2013-08-07 05:19:23 +0000157 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000158 }
159 llvm_unreachable("Unknown PIC model!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000160}
161
Chris Lattnerb515d752009-08-23 07:49:08 +0000162bool LTOCodeGenerator::writeMergedModules(const char *path,
163 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000164 if (!determineTarget(errMsg))
Shuxin Yang235089b2013-08-07 05:19:23 +0000165 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000166
Bill Wendling6ba2ed52013-08-08 23:51:04 +0000167 // mark which symbols can not be internalized
168 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000169
Chris Lattnerb515d752009-08-23 07:49:08 +0000170 // create output file
171 std::string ErrInfo;
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000172 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000173 if (!ErrInfo.empty()) {
174 errMsg = "could not open bitcode file for writing: ";
175 errMsg += path;
Shuxin Yang235089b2013-08-07 05:19:23 +0000176 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000177 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000178
Chris Lattnerb515d752009-08-23 07:49:08 +0000179 // write bitcode to it
Rafael Espindola66efc632013-09-04 17:44:24 +0000180 WriteBitcodeToFile(Linker.getModule(), Out.os());
Dan Gohmand4c45432010-09-01 14:20:41 +0000181 Out.os().close();
Dan Gohman4b7416b2010-05-27 20:19:47 +0000182
Dan Gohmand4c45432010-09-01 14:20:41 +0000183 if (Out.os().has_error()) {
Chris Lattnerb515d752009-08-23 07:49:08 +0000184 errMsg = "could not write bitcode file: ";
185 errMsg += path;
Dan Gohmand4c45432010-09-01 14:20:41 +0000186 Out.os().clear_error();
Shuxin Yang235089b2013-08-07 05:19:23 +0000187 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000188 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000189
Dan Gohmanf2914012010-08-20 16:59:15 +0000190 Out.keep();
Shuxin Yang235089b2013-08-07 05:19:23 +0000191 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000192}
193
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000194bool LTOCodeGenerator::compile_to_file(const char** name,
195 bool disableOpt,
196 bool disableInline,
197 bool disableGVNLoadPRE,
198 std::string& errMsg) {
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000199 // make unique temp .o file to put generated object file
200 SmallString<128> Filename;
201 int FD;
202 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
203 if (EC) {
204 errMsg = EC.message();
Shuxin Yang235089b2013-08-07 05:19:23 +0000205 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000206 }
Rafael Espindola6421a882011-03-22 20:57:13 +0000207
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000208 // generate object file
209 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendlingc94c5622012-03-31 11:15:43 +0000210
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000211 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
212 disableGVNLoadPRE, errMsg);
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000213 objFile.os().close();
214 if (objFile.os().has_error()) {
215 objFile.os().clear_error();
216 sys::fs::remove(Twine(Filename));
Shuxin Yang235089b2013-08-07 05:19:23 +0000217 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000218 }
Bill Wendlingc94c5622012-03-31 11:15:43 +0000219
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000220 objFile.keep();
221 if (!genResult) {
222 sys::fs::remove(Twine(Filename));
Shuxin Yang235089b2013-08-07 05:19:23 +0000223 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000224 }
Rafael Espindola6421a882011-03-22 20:57:13 +0000225
Rafael Espindola66efc632013-09-04 17:44:24 +0000226 NativeObjectPath = Filename.c_str();
227 *name = NativeObjectPath.c_str();
Shuxin Yang235089b2013-08-07 05:19:23 +0000228 return true;
Rafael Espindola6421a882011-03-22 20:57:13 +0000229}
230
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000231const void* LTOCodeGenerator::compile(size_t* length,
232 bool disableOpt,
233 bool disableInline,
234 bool disableGVNLoadPRE,
235 std::string& errMsg) {
Rafael Espindola6421a882011-03-22 20:57:13 +0000236 const char *name;
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000237 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
238 errMsg))
Rafael Espindola6421a882011-03-22 20:57:13 +0000239 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000240
Rafael Espindola6421a882011-03-22 20:57:13 +0000241 // remove old buffer if compile() called twice
Rafael Espindola66efc632013-09-04 17:44:24 +0000242 delete NativeObjectFile;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000243
Rafael Espindola6421a882011-03-22 20:57:13 +0000244 // read .o file into memory buffer
245 OwningPtr<MemoryBuffer> BuffPtr;
246 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
247 errMsg = ec.message();
Rafael Espindola66efc632013-09-04 17:44:24 +0000248 sys::fs::remove(NativeObjectPath);
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000249 return NULL;
Rafael Espindola6421a882011-03-22 20:57:13 +0000250 }
Rafael Espindola66efc632013-09-04 17:44:24 +0000251 NativeObjectFile = BuffPtr.take();
Rafael Espindolae9efea12011-02-24 21:04:06 +0000252
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000253 // remove temp files
Rafael Espindola66efc632013-09-04 17:44:24 +0000254 sys::fs::remove(NativeObjectPath);
Rafael Espindolae9efea12011-02-24 21:04:06 +0000255
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000256 // return buffer, unless error
Rafael Espindola66efc632013-09-04 17:44:24 +0000257 if (NativeObjectFile == NULL)
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000258 return NULL;
Rafael Espindola66efc632013-09-04 17:44:24 +0000259 *length = NativeObjectFile->getBufferSize();
260 return NativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000261}
262
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000263bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Rafael Espindola66efc632013-09-04 17:44:24 +0000264 if (TargetMach != NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000265 return true;
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000266
Rafael Espindola66efc632013-09-04 17:44:24 +0000267 std::string TripleStr = Linker.getModule()->getTargetTriple();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000268 if (TripleStr.empty())
269 TripleStr = sys::getDefaultTargetTriple();
270 llvm::Triple Triple(TripleStr);
Bill Wendling604a8182008-06-18 06:35:30 +0000271
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000272 // create target machine from info for merged modules
Bob Wilson47ed8a12012-10-12 17:39:25 +0000273 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling0ca36af2012-08-08 22:03:50 +0000274 if (march == NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000275 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000276
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000277 // The relocation model is actually a static member of TargetMachine and
278 // needs to be set before the TargetMachine is instantiated.
279 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindola66efc632013-09-04 17:44:24 +0000280 switch (CodeModel) {
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000281 case LTO_CODEGEN_PIC_MODEL_STATIC:
282 RelocModel = Reloc::Static;
283 break;
284 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
285 RelocModel = Reloc::PIC_;
286 break;
287 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
288 RelocModel = Reloc::DynamicNoPIC;
289 break;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000290 }
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000291
292 // construct LTOModule, hand over ownership of module and target
293 SubtargetFeatures Features;
Bob Wilson47ed8a12012-10-12 17:39:25 +0000294 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000295 std::string FeatureStr = Features.getString();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000296 // Set a default CPU for Darwin triples.
Rafael Espindola66efc632013-09-04 17:44:24 +0000297 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson47ed8a12012-10-12 17:39:25 +0000298 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindola66efc632013-09-04 17:44:24 +0000299 MCpu = "core2";
Bob Wilson47ed8a12012-10-12 17:39:25 +0000300 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindola66efc632013-09-04 17:44:24 +0000301 MCpu = "yonah";
Bob Wilson47ed8a12012-10-12 17:39:25 +0000302 }
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000303
Rafael Espindola66efc632013-09-04 17:44:24 +0000304 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
305 RelocModel, CodeModel::Default,
306 CodeGenOpt::Aggressive);
Shuxin Yang08809392013-08-06 21:51:21 +0000307 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000308}
309
Bill Wendlingc94c5622012-03-31 11:15:43 +0000310void LTOCodeGenerator::
311applyRestriction(GlobalValue &GV,
Rafael Espindola775079c2013-09-04 20:08:46 +0000312 std::vector<const char*> &MustPreserveList,
313 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
314 Mangler &Mangler) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000315 SmallString<64> Buffer;
Rafael Espindola775079c2013-09-04 20:08:46 +0000316 Mangler.getNameWithPrefix(Buffer, &GV, false);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000317
318 if (GV.isDeclaration())
319 return;
Rafael Espindola66efc632013-09-04 17:44:24 +0000320 if (MustPreserveSymbols.count(Buffer))
Rafael Espindola775079c2013-09-04 20:08:46 +0000321 MustPreserveList.push_back(GV.getName().data());
Rafael Espindola66efc632013-09-04 17:44:24 +0000322 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindola775079c2013-09-04 20:08:46 +0000323 AsmUsed.insert(&GV);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000324}
325
326static void findUsedValues(GlobalVariable *LLVMUsed,
327 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
328 if (LLVMUsed == 0) return;
329
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000330 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola38c4e532011-03-02 04:14:42 +0000331 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling76b13ed2012-03-31 10:50:14 +0000332 if (GlobalValue *GV =
Bill Wendlingc94c5622012-03-31 11:15:43 +0000333 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000334 UsedValues.insert(GV);
335}
336
Chris Lattner5ef31a02010-03-12 18:44:54 +0000337void LTOCodeGenerator::applyScopeRestrictions() {
Rafael Espindola66efc632013-09-04 17:44:24 +0000338 if (ScopeRestrictionsDone)
339 return;
340 Module *mergedModule = Linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000341
Chris Lattner5ef31a02010-03-12 18:44:54 +0000342 // Start off with a verification pass.
343 PassManager passes;
344 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000345
Bill Wendling76b13ed2012-03-31 10:50:14 +0000346 // mark which symbols can not be internalized
Rafael Espindola66efc632013-09-04 17:44:24 +0000347 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
348 NULL);
Rafael Espindola775079c2013-09-04 20:08:46 +0000349 Mangler Mangler(MContext, TargetMach);
350 std::vector<const char*> MustPreserveList;
351 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000352
353 for (Module::iterator f = mergedModule->begin(),
354 e = mergedModule->end(); f != e; ++f)
Rafael Espindola775079c2013-09-04 20:08:46 +0000355 applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000356 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola38c4e532011-03-02 04:14:42 +0000357 e = mergedModule->global_end(); v != e; ++v)
Rafael Espindola775079c2013-09-04 20:08:46 +0000358 applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000359 for (Module::alias_iterator a = mergedModule->alias_begin(),
360 e = mergedModule->alias_end(); a != e; ++a)
Rafael Espindola775079c2013-09-04 20:08:46 +0000361 applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000362
363 GlobalVariable *LLVMCompilerUsed =
364 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindola775079c2013-09-04 20:08:46 +0000365 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000366 if (LLVMCompilerUsed)
367 LLVMCompilerUsed->eraseFromParent();
368
Rafael Espindola775079c2013-09-04 20:08:46 +0000369 if (!AsmUsed.empty()) {
Rafael Espindola66efc632013-09-04 17:44:24 +0000370 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000371 std::vector<Constant*> asmUsed2;
Rafael Espindola775079c2013-09-04 20:08:46 +0000372 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
373 e = AsmUsed.end(); i !=e; ++i) {
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000374 GlobalValue *GV = *i;
375 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
376 asmUsed2.push_back(c);
377 }
378
379 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
380 LLVMCompilerUsed =
381 new llvm::GlobalVariable(*mergedModule, ATy, false,
382 llvm::GlobalValue::AppendingLinkage,
383 llvm::ConstantArray::get(ATy, asmUsed2),
384 "llvm.compiler.used");
385
386 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner5ef31a02010-03-12 18:44:54 +0000387 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000388
Rafael Espindola775079c2013-09-04 20:08:46 +0000389 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000390
Chris Lattner5ef31a02010-03-12 18:44:54 +0000391 // apply scope restrictions
392 passes.run(*mergedModule);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000393
Rafael Espindola66efc632013-09-04 17:44:24 +0000394 ScopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000395}
396
Nick Kledzik77595fc2008-02-26 20:26:43 +0000397/// Optimize merged modules using various IPO passes
Chris Lattner817a01f2011-05-22 00:20:07 +0000398bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000399 bool DisableOpt,
400 bool DisableInline,
401 bool DisableGVNLoadPRE,
Chris Lattner817a01f2011-05-22 00:20:07 +0000402 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000403 if (!this->determineTarget(errMsg))
404 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000405
Rafael Espindola66efc632013-09-04 17:44:24 +0000406 Module *mergedModule = Linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000407
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000408 // Mark which symbols can not be internalized
Bill Wendling64d5b282012-04-09 22:18:01 +0000409 this->applyScopeRestrictions();
410
Bill Wendlingc94c5622012-03-31 11:15:43 +0000411 // Instantiate the pass manager to organize the passes.
412 PassManager passes;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000413
Bill Wendlingc94c5622012-03-31 11:15:43 +0000414 // Start off with a verification pass.
415 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000416
Micah Villmow791cfc22012-10-08 16:39:34 +0000417 // Add an appropriate DataLayout instance for this module...
Rafael Espindola66efc632013-09-04 17:44:24 +0000418 passes.add(new DataLayout(*TargetMach->getDataLayout()));
419 TargetMach->addAnalysisPasses(passes);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000420
Rafael Espindola4d2e9d92012-04-16 10:58:38 +0000421 // Enabling internalize here would use its AllButMain variant. It
422 // keeps only main if it exists and does nothing for libraries. Instead
423 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000424 if (!DisableOpt)
Bill Wendling6303b662013-02-28 14:11:10 +0000425 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling50f31832012-12-10 21:33:45 +0000426 /*Internalize=*/false,
Bill Wendling3197b442012-04-02 22:16:50 +0000427 !DisableInline,
428 DisableGVNLoadPRE);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000429
Bill Wendlingc94c5622012-03-31 11:15:43 +0000430 // Make sure everything is still good.
431 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000432
Lang Hamesa991b252013-03-13 21:18:46 +0000433 PassManager codeGenPasses;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000434
Rafael Espindola66efc632013-09-04 17:44:24 +0000435 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
436 TargetMach->addAnalysisPasses(codeGenPasses);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000437
Bill Wendlingc94c5622012-03-31 11:15:43 +0000438 formatted_raw_ostream Out(out);
Dan Gohmand4c45432010-09-01 14:20:41 +0000439
Bob Wilsond6965442013-03-29 23:28:55 +0000440 // If the bitcode files contain ARC code and were compiled with optimization,
441 // the ObjCARCContractPass must be run, so do it unconditionally here.
442 codeGenPasses.add(createObjCARCContractPass());
443
Rafael Espindola66efc632013-09-04 17:44:24 +0000444 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
445 TargetMachine::CGFT_ObjectFile)) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000446 errMsg = "target file type not supported";
Shuxin Yang08809392013-08-06 21:51:21 +0000447 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000448 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000449
Bill Wendlingc94c5622012-03-31 11:15:43 +0000450 // Run our queue of passes all at once now, efficiently.
451 passes.run(*mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000452
Bill Wendlingc94c5622012-03-31 11:15:43 +0000453 // Run the code generator, and write assembly file
Lang Hamesa991b252013-03-13 21:18:46 +0000454 codeGenPasses.run(*mergedModule);
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000455
Shuxin Yang08809392013-08-06 21:51:21 +0000456 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000457}
458
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000459/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
460/// LTO problems.
461void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
462 for (std::pair<StringRef, StringRef> o = getToken(options);
463 !o.first.empty(); o = getToken(o.second)) {
464 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
465 // that.
Rafael Espindola66efc632013-09-04 17:44:24 +0000466 if (CodegenOptions.empty())
Peter Collingbournecc488542013-09-24 23:52:22 +0000467 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindola66efc632013-09-04 17:44:24 +0000468 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000469 }
Nick Kledzik920ae982008-07-08 21:14:10 +0000470}
Rafael Espindola0e95b3a2013-10-02 14:36:23 +0000471
472void LTOCodeGenerator::parseCodeGenDebugOptions() {
473 // if options were requested, set them
474 if (!CodegenOptions.empty())
475 cl::ParseCommandLineOptions(CodegenOptions.size(),
476 const_cast<char **>(&CodegenOptions[0]));
477}