blob: faa55bbf2ba7ab0a39f7db5518aaa86e463d8186 [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
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000267 // if options were requested, set them
Rafael Espindola66efc632013-09-04 17:44:24 +0000268 if (!CodegenOptions.empty())
269 cl::ParseCommandLineOptions(CodegenOptions.size(),
270 const_cast<char **>(&CodegenOptions[0]));
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000271
Rafael Espindola66efc632013-09-04 17:44:24 +0000272 std::string TripleStr = Linker.getModule()->getTargetTriple();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000273 if (TripleStr.empty())
274 TripleStr = sys::getDefaultTargetTriple();
275 llvm::Triple Triple(TripleStr);
Bill Wendling604a8182008-06-18 06:35:30 +0000276
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000277 // create target machine from info for merged modules
Bob Wilson47ed8a12012-10-12 17:39:25 +0000278 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling0ca36af2012-08-08 22:03:50 +0000279 if (march == NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000280 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000281
Bill Wendlingeda3fc62012-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 Espindola66efc632013-09-04 17:44:24 +0000285 switch (CodeModel) {
Bill Wendlingeda3fc62012-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 Wendlingc94c5622012-03-31 11:15:43 +0000295 }
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000296
297 // construct LTOModule, hand over ownership of module and target
298 SubtargetFeatures Features;
Bob Wilson47ed8a12012-10-12 17:39:25 +0000299 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000300 std::string FeatureStr = Features.getString();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000301 // Set a default CPU for Darwin triples.
Rafael Espindola66efc632013-09-04 17:44:24 +0000302 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson47ed8a12012-10-12 17:39:25 +0000303 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindola66efc632013-09-04 17:44:24 +0000304 MCpu = "core2";
Bob Wilson47ed8a12012-10-12 17:39:25 +0000305 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindola66efc632013-09-04 17:44:24 +0000306 MCpu = "yonah";
Bob Wilson47ed8a12012-10-12 17:39:25 +0000307 }
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000308
Rafael Espindola66efc632013-09-04 17:44:24 +0000309 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
310 RelocModel, CodeModel::Default,
311 CodeGenOpt::Aggressive);
Shuxin Yang08809392013-08-06 21:51:21 +0000312 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000313}
314
Bill Wendlingc94c5622012-03-31 11:15:43 +0000315void LTOCodeGenerator::
316applyRestriction(GlobalValue &GV,
Rafael Espindola775079c2013-09-04 20:08:46 +0000317 std::vector<const char*> &MustPreserveList,
318 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
319 Mangler &Mangler) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000320 SmallString<64> Buffer;
Rafael Espindola775079c2013-09-04 20:08:46 +0000321 Mangler.getNameWithPrefix(Buffer, &GV, false);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000322
323 if (GV.isDeclaration())
324 return;
Rafael Espindola66efc632013-09-04 17:44:24 +0000325 if (MustPreserveSymbols.count(Buffer))
Rafael Espindola775079c2013-09-04 20:08:46 +0000326 MustPreserveList.push_back(GV.getName().data());
Rafael Espindola66efc632013-09-04 17:44:24 +0000327 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindola775079c2013-09-04 20:08:46 +0000328 AsmUsed.insert(&GV);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000329}
330
331static void findUsedValues(GlobalVariable *LLVMUsed,
332 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
333 if (LLVMUsed == 0) return;
334
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000335 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola38c4e532011-03-02 04:14:42 +0000336 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling76b13ed2012-03-31 10:50:14 +0000337 if (GlobalValue *GV =
Bill Wendlingc94c5622012-03-31 11:15:43 +0000338 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000339 UsedValues.insert(GV);
340}
341
Chris Lattner5ef31a02010-03-12 18:44:54 +0000342void LTOCodeGenerator::applyScopeRestrictions() {
Rafael Espindola66efc632013-09-04 17:44:24 +0000343 if (ScopeRestrictionsDone)
344 return;
345 Module *mergedModule = Linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000346
Chris Lattner5ef31a02010-03-12 18:44:54 +0000347 // Start off with a verification pass.
348 PassManager passes;
349 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000350
Bill Wendling76b13ed2012-03-31 10:50:14 +0000351 // mark which symbols can not be internalized
Rafael Espindola66efc632013-09-04 17:44:24 +0000352 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
353 NULL);
Rafael Espindola775079c2013-09-04 20:08:46 +0000354 Mangler Mangler(MContext, TargetMach);
355 std::vector<const char*> MustPreserveList;
356 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000357
358 for (Module::iterator f = mergedModule->begin(),
359 e = mergedModule->end(); f != e; ++f)
Rafael Espindola775079c2013-09-04 20:08:46 +0000360 applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000361 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola38c4e532011-03-02 04:14:42 +0000362 e = mergedModule->global_end(); v != e; ++v)
Rafael Espindola775079c2013-09-04 20:08:46 +0000363 applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000364 for (Module::alias_iterator a = mergedModule->alias_begin(),
365 e = mergedModule->alias_end(); a != e; ++a)
Rafael Espindola775079c2013-09-04 20:08:46 +0000366 applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000367
368 GlobalVariable *LLVMCompilerUsed =
369 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindola775079c2013-09-04 20:08:46 +0000370 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000371 if (LLVMCompilerUsed)
372 LLVMCompilerUsed->eraseFromParent();
373
Rafael Espindola775079c2013-09-04 20:08:46 +0000374 if (!AsmUsed.empty()) {
Rafael Espindola66efc632013-09-04 17:44:24 +0000375 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000376 std::vector<Constant*> asmUsed2;
Rafael Espindola775079c2013-09-04 20:08:46 +0000377 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
378 e = AsmUsed.end(); i !=e; ++i) {
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000379 GlobalValue *GV = *i;
380 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
381 asmUsed2.push_back(c);
382 }
383
384 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
385 LLVMCompilerUsed =
386 new llvm::GlobalVariable(*mergedModule, ATy, false,
387 llvm::GlobalValue::AppendingLinkage,
388 llvm::ConstantArray::get(ATy, asmUsed2),
389 "llvm.compiler.used");
390
391 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner5ef31a02010-03-12 18:44:54 +0000392 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000393
Rafael Espindola775079c2013-09-04 20:08:46 +0000394 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000395
Chris Lattner5ef31a02010-03-12 18:44:54 +0000396 // apply scope restrictions
397 passes.run(*mergedModule);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000398
Rafael Espindola66efc632013-09-04 17:44:24 +0000399 ScopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000400}
401
Nick Kledzik77595fc2008-02-26 20:26:43 +0000402/// Optimize merged modules using various IPO passes
Chris Lattner817a01f2011-05-22 00:20:07 +0000403bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindolac13c9e52013-09-30 16:39:19 +0000404 bool DisableOpt,
405 bool DisableInline,
406 bool DisableGVNLoadPRE,
Chris Lattner817a01f2011-05-22 00:20:07 +0000407 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000408 if (!this->determineTarget(errMsg))
409 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000410
Rafael Espindola66efc632013-09-04 17:44:24 +0000411 Module *mergedModule = Linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000412
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000413 // Mark which symbols can not be internalized
Bill Wendling64d5b282012-04-09 22:18:01 +0000414 this->applyScopeRestrictions();
415
Bill Wendlingc94c5622012-03-31 11:15:43 +0000416 // Instantiate the pass manager to organize the passes.
417 PassManager passes;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000418
Bill Wendlingc94c5622012-03-31 11:15:43 +0000419 // Start off with a verification pass.
420 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000421
Micah Villmow791cfc22012-10-08 16:39:34 +0000422 // Add an appropriate DataLayout instance for this module...
Rafael Espindola66efc632013-09-04 17:44:24 +0000423 passes.add(new DataLayout(*TargetMach->getDataLayout()));
424 TargetMach->addAnalysisPasses(passes);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000425
Rafael Espindola4d2e9d92012-04-16 10:58:38 +0000426 // Enabling internalize here would use its AllButMain variant. It
427 // keeps only main if it exists and does nothing for libraries. Instead
428 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000429 if (!DisableOpt)
Bill Wendling6303b662013-02-28 14:11:10 +0000430 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling50f31832012-12-10 21:33:45 +0000431 /*Internalize=*/false,
Bill Wendling3197b442012-04-02 22:16:50 +0000432 !DisableInline,
433 DisableGVNLoadPRE);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000434
Bill Wendlingc94c5622012-03-31 11:15:43 +0000435 // Make sure everything is still good.
436 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000437
Lang Hamesa991b252013-03-13 21:18:46 +0000438 PassManager codeGenPasses;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000439
Rafael Espindola66efc632013-09-04 17:44:24 +0000440 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
441 TargetMach->addAnalysisPasses(codeGenPasses);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000442
Bill Wendlingc94c5622012-03-31 11:15:43 +0000443 formatted_raw_ostream Out(out);
Dan Gohmand4c45432010-09-01 14:20:41 +0000444
Bob Wilsond6965442013-03-29 23:28:55 +0000445 // If the bitcode files contain ARC code and were compiled with optimization,
446 // the ObjCARCContractPass must be run, so do it unconditionally here.
447 codeGenPasses.add(createObjCARCContractPass());
448
Rafael Espindola66efc632013-09-04 17:44:24 +0000449 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
450 TargetMachine::CGFT_ObjectFile)) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000451 errMsg = "target file type not supported";
Shuxin Yang08809392013-08-06 21:51:21 +0000452 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000453 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000454
Bill Wendlingc94c5622012-03-31 11:15:43 +0000455 // Run our queue of passes all at once now, efficiently.
456 passes.run(*mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000457
Bill Wendlingc94c5622012-03-31 11:15:43 +0000458 // Run the code generator, and write assembly file
Lang Hamesa991b252013-03-13 21:18:46 +0000459 codeGenPasses.run(*mergedModule);
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000460
Shuxin Yang08809392013-08-06 21:51:21 +0000461 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000462}
463
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000464/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
465/// LTO problems.
466void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
467 for (std::pair<StringRef, StringRef> o = getToken(options);
468 !o.first.empty(); o = getToken(o.second)) {
469 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
470 // that.
Rafael Espindola66efc632013-09-04 17:44:24 +0000471 if (CodegenOptions.empty())
Peter Collingbournecc488542013-09-24 23:52:22 +0000472 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindola66efc632013-09-04 17:44:24 +0000473 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000474 }
Nick Kledzik920ae982008-07-08 21:14:10 +0000475}