blob: 073947055ace16f0b5b96c9257f736f707611f26 [file] [log] [blame]
Nick Kledzik07b4a622008-02-26 20:26:43 +00001//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling39d942b2012-03-31 10:50:14 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling39d942b2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000015#include "llvm/LTO/LTOCodeGenerator.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000017#include "llvm/Analysis/Passes.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000018#include "llvm/Bitcode/ReaderWriter.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000019#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000020#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000024#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/LLVMContext.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000027#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000030#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000031#include "llvm/LTO/LTOModule.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000032#include "llvm/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000033#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000035#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/PassManager.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000037#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000038#include "llvm/Support/FileSystem.h"
David Greenea31f96c2009-07-14 20:18:05 +000039#include "llvm/Support/FormattedStream.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000040#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/MemoryBuffer.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000042#include "llvm/Support/raw_ostream.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000043#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000046#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencerd4227232010-12-09 18:06:07 +000047#include "llvm/Support/system_error.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000048#include "llvm/Target/TargetLibraryInfo.h"
49#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000050#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000051#include "llvm/Target/TargetRegisterInfo.h"
52#include "llvm/Transforms/IPO.h"
53#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000054#include "llvm/Transforms/ObjCARC.h"
Shuxin Yang76d082b2013-08-12 18:29:43 +000055using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000056
Bill Wendling534a6582012-03-31 10:49:43 +000057const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000058#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000059 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000060#else
Bill Wendling534a6582012-03-31 10:49:43 +000061 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000062#endif
63}
64
Bill Wendling39d942b2012-03-31 10:50:14 +000065LTOCodeGenerator::LTOCodeGenerator()
Rafael Espindolac80c9692013-09-04 17:44:24 +000066 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
67 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
Duncan P. N. Exon Smith93be7c42014-01-14 18:52:17 +000068 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000069 InternalizeStrategy(LTO_INTERNALIZE_FULL), NativeObjectFile(NULL),
70 DiagHandler(NULL), DiagContext(NULL) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000071 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000072}
73
Bill Wendling534a6582012-03-31 10:49:43 +000074LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000075 delete TargetMach;
76 delete NativeObjectFile;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000077 TargetMach = NULL;
78 NativeObjectFile = NULL;
79
80 Linker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000081
Rafael Espindolac80c9692013-09-04 17:44:24 +000082 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
83 E = CodegenOptions.end();
84 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000085 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000086}
87
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000088// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000089// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000090// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000091void LTOCodeGenerator::initializeLTOPasses() {
92 PassRegistry &R = *PassRegistry::getPassRegistry();
93
94 initializeInternalizePassPass(R);
95 initializeIPSCCPPass(R);
96 initializeGlobalOptPass(R);
97 initializeConstantMergePass(R);
98 initializeDAHPass(R);
99 initializeInstCombinerPass(R);
100 initializeSimpleInlinerPass(R);
101 initializePruneEHPass(R);
102 initializeGlobalDCEPass(R);
103 initializeArgPromotionPass(R);
104 initializeJumpThreadingPass(R);
105 initializeSROAPass(R);
106 initializeSROA_DTPass(R);
107 initializeSROA_SSAUpPass(R);
108 initializeFunctionAttrsPass(R);
109 initializeGlobalsModRefPass(R);
110 initializeLICMPass(R);
111 initializeGVNPass(R);
112 initializeMemCpyOptPass(R);
113 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000114 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000115}
116
Bill Wendling0e1824c2012-03-31 11:15:43 +0000117bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000118 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000119
120 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
121 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000122 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000123
Shuxin Yangb6696a92013-08-07 05:19:23 +0000124 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000125}
Bill Wendling39d942b2012-03-31 10:50:14 +0000126
Rafael Espindola0b385c72013-09-30 16:39:19 +0000127void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
128 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
129 Options.NoFramePointerElim = options.NoFramePointerElim;
130 Options.AllowFPOpFusion = options.AllowFPOpFusion;
131 Options.UnsafeFPMath = options.UnsafeFPMath;
132 Options.NoInfsFPMath = options.NoInfsFPMath;
133 Options.NoNaNsFPMath = options.NoNaNsFPMath;
134 Options.HonorSignDependentRoundingFPMathOption =
135 options.HonorSignDependentRoundingFPMathOption;
136 Options.UseSoftFloat = options.UseSoftFloat;
137 Options.FloatABIType = options.FloatABIType;
138 Options.NoZerosInBSS = options.NoZerosInBSS;
139 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
140 Options.DisableTailCalls = options.DisableTailCalls;
141 Options.StackAlignmentOverride = options.StackAlignmentOverride;
142 Options.TrapFuncName = options.TrapFuncName;
143 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
144 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
145 Options.UseInitArray = options.UseInitArray;
146}
147
Shuxin Yangb6696a92013-08-07 05:19:23 +0000148void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000149 switch (debug) {
150 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000151 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000152 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000153
Bill Wendling0e1824c2012-03-31 11:15:43 +0000154 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000155 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000156 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000157 }
158 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000159}
160
Shuxin Yangb6696a92013-08-07 05:19:23 +0000161void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000162 switch (model) {
163 case LTO_CODEGEN_PIC_MODEL_STATIC:
164 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
165 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000166 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000167 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000168 }
169 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000170}
171
Duncan P. N. Exon Smith93be7c42014-01-14 18:52:17 +0000172void
173LTOCodeGenerator::setInternalizeStrategy(lto_internalize_strategy Strategy) {
174 switch (Strategy) {
175 case LTO_INTERNALIZE_FULL:
176 case LTO_INTERNALIZE_NONE:
177 case LTO_INTERNALIZE_HIDDEN:
178 InternalizeStrategy = Strategy;
179 return;
180 }
181 llvm_unreachable("Unknown internalize strategy!");
182}
183
Chris Lattner69733952009-08-23 07:49:08 +0000184bool LTOCodeGenerator::writeMergedModules(const char *path,
185 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000186 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000187 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000188
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000189 // mark which symbols can not be internalized
190 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000191
Chris Lattner69733952009-08-23 07:49:08 +0000192 // create output file
193 std::string ErrInfo;
Rafael Espindola6d354812013-07-16 19:44:17 +0000194 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
Chris Lattner69733952009-08-23 07:49:08 +0000195 if (!ErrInfo.empty()) {
196 errMsg = "could not open bitcode file for writing: ";
197 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000198 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000199 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000200
Chris Lattner69733952009-08-23 07:49:08 +0000201 // write bitcode to it
Rafael Espindolac80c9692013-09-04 17:44:24 +0000202 WriteBitcodeToFile(Linker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000203 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000204
Dan Gohmana2233f22010-09-01 14:20:41 +0000205 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000206 errMsg = "could not write bitcode file: ";
207 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000208 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000209 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000210 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000211
Dan Gohman8525fe72010-08-20 16:59:15 +0000212 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000213 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000214}
215
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000216bool LTOCodeGenerator::compile_to_file(const char** name,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000217 bool disableOpt,
218 bool disableInline,
219 bool disableGVNLoadPRE,
220 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000221 // make unique temp .o file to put generated object file
222 SmallString<128> Filename;
223 int FD;
224 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
225 if (EC) {
226 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000227 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000228 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000229
Shuxin Yang1826ae22013-08-12 21:07:31 +0000230 // generate object file
231 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000232
Rafael Espindola0b385c72013-09-30 16:39:19 +0000233 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
234 disableGVNLoadPRE, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000235 objFile.os().close();
236 if (objFile.os().has_error()) {
237 objFile.os().clear_error();
238 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000239 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000240 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000241
Shuxin Yang1826ae22013-08-12 21:07:31 +0000242 objFile.keep();
243 if (!genResult) {
244 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000245 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000246 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000247
Rafael Espindolac80c9692013-09-04 17:44:24 +0000248 NativeObjectPath = Filename.c_str();
249 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000250 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000251}
252
Rafael Espindola0b385c72013-09-30 16:39:19 +0000253const void* LTOCodeGenerator::compile(size_t* length,
254 bool disableOpt,
255 bool disableInline,
256 bool disableGVNLoadPRE,
257 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000258 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000259 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
260 errMsg))
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000261 return NULL;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000262
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000263 // remove old buffer if compile() called twice
Rafael Espindolac80c9692013-09-04 17:44:24 +0000264 delete NativeObjectFile;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000265
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000266 // read .o file into memory buffer
267 OwningPtr<MemoryBuffer> BuffPtr;
268 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
269 errMsg = ec.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000270 sys::fs::remove(NativeObjectPath);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000271 return NULL;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000272 }
Rafael Espindolac80c9692013-09-04 17:44:24 +0000273 NativeObjectFile = BuffPtr.take();
Rafael Espindolafac373c2011-02-24 21:04:06 +0000274
Shuxin Yang1826ae22013-08-12 21:07:31 +0000275 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000276 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000277
Shuxin Yang1826ae22013-08-12 21:07:31 +0000278 // return buffer, unless error
Rafael Espindolac80c9692013-09-04 17:44:24 +0000279 if (NativeObjectFile == NULL)
Shuxin Yang1826ae22013-08-12 21:07:31 +0000280 return NULL;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000281 *length = NativeObjectFile->getBufferSize();
282 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000283}
284
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000285bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000286 if (TargetMach != NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000287 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000288
Rafael Espindolac80c9692013-09-04 17:44:24 +0000289 std::string TripleStr = Linker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000290 if (TripleStr.empty())
291 TripleStr = sys::getDefaultTargetTriple();
292 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000293
Bill Wendling45f74e32012-08-06 22:52:45 +0000294 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000295 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling6a0abed2012-08-08 22:03:50 +0000296 if (march == NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000297 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000298
Bill Wendling45f74e32012-08-06 22:52:45 +0000299 // The relocation model is actually a static member of TargetMachine and
300 // needs to be set before the TargetMachine is instantiated.
301 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000302 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000303 case LTO_CODEGEN_PIC_MODEL_STATIC:
304 RelocModel = Reloc::Static;
305 break;
306 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
307 RelocModel = Reloc::PIC_;
308 break;
309 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
310 RelocModel = Reloc::DynamicNoPIC;
311 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000312 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000313
314 // construct LTOModule, hand over ownership of module and target
315 SubtargetFeatures Features;
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000316 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000317 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000318 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000319 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000320 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000321 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000322 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000323 MCpu = "yonah";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000324 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000325
Rafael Espindolac80c9692013-09-04 17:44:24 +0000326 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
327 RelocModel, CodeModel::Default,
328 CodeGenOpt::Aggressive);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000329 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000330}
331
Bill Wendling0e1824c2012-03-31 11:15:43 +0000332void LTOCodeGenerator::
333applyRestriction(GlobalValue &GV,
Justin Bognerb10a5202013-11-12 21:44:01 +0000334 const ArrayRef<StringRef> &Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000335 std::vector<const char*> &MustPreserveList,
336 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
337 Mangler &Mangler) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000338 SmallString<64> Buffer;
Daniel Jasper7e198ad2014-02-19 12:26:01 +0000339 Mangler.getNameWithPrefix(Buffer, &GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000340
341 if (GV.isDeclaration())
342 return;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000343 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000344 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000345 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000346 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000347
348 // Conservatively append user-supplied runtime library functions to
349 // llvm.compiler.used. These could be internalized and deleted by
350 // optimizations like -globalopt, causing problems when later optimizations
351 // add new library calls (e.g., llvm.memset => memset and printf => puts).
352 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
353 if (isa<Function>(GV) &&
354 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
355 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000356}
357
358static void findUsedValues(GlobalVariable *LLVMUsed,
359 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
360 if (LLVMUsed == 0) return;
361
Rafael Espindolacc111b22013-04-24 17:54:35 +0000362 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000363 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000364 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000365 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000366 UsedValues.insert(GV);
367}
368
Justin Bognerb10a5202013-11-12 21:44:01 +0000369static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
370 const TargetLibraryInfo& TLI,
371 const TargetLowering *Lowering)
372{
373 // TargetLibraryInfo has info on C runtime library calls on the current
374 // target.
375 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
376 I != E; ++I) {
377 LibFunc::Func F = static_cast<LibFunc::Func>(I);
378 if (TLI.has(F))
379 Libcalls.push_back(TLI.getName(F));
380 }
381
382 // TargetLowering has info on library calls that CodeGen expects to be
383 // available, both from the C runtime and compiler-rt.
384 if (Lowering)
385 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
386 I != E; ++I)
387 if (const char *Name
388 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
389 Libcalls.push_back(Name);
390
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000391 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000392 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
393 Libcalls.end());
394}
395
Chris Lattner2eff5052010-03-12 18:44:54 +0000396void LTOCodeGenerator::applyScopeRestrictions() {
Duncan P. N. Exon Smith93be7c42014-01-14 18:52:17 +0000397 if (ScopeRestrictionsDone || !shouldInternalize())
Rafael Espindolac80c9692013-09-04 17:44:24 +0000398 return;
399 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000400
Chris Lattner2eff5052010-03-12 18:44:54 +0000401 // Start off with a verification pass.
402 PassManager passes;
403 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000404
Bill Wendling39d942b2012-03-31 10:50:14 +0000405 // mark which symbols can not be internalized
Rafael Espindola58873562014-01-03 19:21:54 +0000406 Mangler Mangler(TargetMach->getDataLayout());
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000407 std::vector<const char*> MustPreserveList;
408 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000409 std::vector<StringRef> Libcalls;
410 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
411 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000412
413 for (Module::iterator f = mergedModule->begin(),
414 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000415 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000416 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000417 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000418 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000419 for (Module::alias_iterator a = mergedModule->alias_begin(),
420 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000421 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000422
423 GlobalVariable *LLVMCompilerUsed =
424 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000425 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000426 if (LLVMCompilerUsed)
427 LLVMCompilerUsed->eraseFromParent();
428
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000429 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000430 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000431 std::vector<Constant*> asmUsed2;
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000432 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
433 e = AsmUsed.end(); i !=e; ++i) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000434 GlobalValue *GV = *i;
435 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
436 asmUsed2.push_back(c);
437 }
438
439 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
440 LLVMCompilerUsed =
441 new llvm::GlobalVariable(*mergedModule, ATy, false,
442 llvm::GlobalValue::AppendingLinkage,
443 llvm::ConstantArray::get(ATy, asmUsed2),
444 "llvm.compiler.used");
445
446 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000447 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000448
Duncan P. N. Exon Smith93be7c42014-01-14 18:52:17 +0000449 passes.add(
450 createInternalizePass(MustPreserveList, shouldOnlyInternalizeHidden()));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000451
Chris Lattner2eff5052010-03-12 18:44:54 +0000452 // apply scope restrictions
453 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000454
Rafael Espindolac80c9692013-09-04 17:44:24 +0000455 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000456}
457
Nick Kledzik07b4a622008-02-26 20:26:43 +0000458/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000459bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000460 bool DisableOpt,
461 bool DisableInline,
462 bool DisableGVNLoadPRE,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000463 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000464 if (!this->determineTarget(errMsg))
465 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000466
Rafael Espindolac80c9692013-09-04 17:44:24 +0000467 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000468
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000469 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000470 this->applyScopeRestrictions();
471
Bill Wendling0e1824c2012-03-31 11:15:43 +0000472 // Instantiate the pass manager to organize the passes.
473 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000474
Bill Wendling0e1824c2012-03-31 11:15:43 +0000475 // Start off with a verification pass.
476 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000477
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000478 // Add an appropriate DataLayout instance for this module...
Rafael Espindolac80c9692013-09-04 17:44:24 +0000479 passes.add(new DataLayout(*TargetMach->getDataLayout()));
Yi Jiang53823be2013-12-12 01:37:39 +0000480
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000481 // Add appropriate TargetLibraryInfo for this module.
Yi Jiang53823be2013-12-12 01:37:39 +0000482 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
483
Rafael Espindolac80c9692013-09-04 17:44:24 +0000484 TargetMach->addAnalysisPasses(passes);
Bill Wendling39d942b2012-03-31 10:50:14 +0000485
Rafael Espindola0ecb8fa2012-04-16 10:58:38 +0000486 // Enabling internalize here would use its AllButMain variant. It
487 // keeps only main if it exists and does nothing for libraries. Instead
488 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000489 if (!DisableOpt)
Bill Wendlingc7e0a042013-02-28 14:11:10 +0000490 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling4a8fc8f2012-12-10 21:33:45 +0000491 /*Internalize=*/false,
Bill Wendling932b9922012-04-02 22:16:50 +0000492 !DisableInline,
493 DisableGVNLoadPRE);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000494
Bill Wendling0e1824c2012-03-31 11:15:43 +0000495 // Make sure everything is still good.
496 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000497
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000498 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000499
Rafael Espindolac80c9692013-09-04 17:44:24 +0000500 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
Nick Kledzik07b4a622008-02-26 20:26:43 +0000501
Bill Wendling0e1824c2012-03-31 11:15:43 +0000502 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000503
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000504 // If the bitcode files contain ARC code and were compiled with optimization,
505 // the ObjCARCContractPass must be run, so do it unconditionally here.
506 codeGenPasses.add(createObjCARCContractPass());
507
Rafael Espindolac80c9692013-09-04 17:44:24 +0000508 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
509 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000510 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000511 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000512 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000513
Bill Wendling0e1824c2012-03-31 11:15:43 +0000514 // Run our queue of passes all at once now, efficiently.
515 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000516
Bill Wendling0e1824c2012-03-31 11:15:43 +0000517 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000518 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000519
Shuxin Yang95866fa2013-08-06 21:51:21 +0000520 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000521}
522
Bill Wendling534a6582012-03-31 10:49:43 +0000523/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
524/// LTO problems.
525void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
526 for (std::pair<StringRef, StringRef> o = getToken(options);
527 !o.first.empty(); o = getToken(o.second)) {
528 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
529 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000530 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000531 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000532 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000533 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000534}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000535
536void LTOCodeGenerator::parseCodeGenDebugOptions() {
537 // if options were requested, set them
538 if (!CodegenOptions.empty())
539 cl::ParseCommandLineOptions(CodegenOptions.size(),
540 const_cast<char **>(&CodegenOptions[0]));
541}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000542
543void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
544 void *Context) {
545 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
546}
547
548void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
549 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
550 lto_codegen_diagnostic_severity_t Severity;
551 switch (DI.getSeverity()) {
552 case DS_Error:
553 Severity = LTO_DS_ERROR;
554 break;
555 case DS_Warning:
556 Severity = LTO_DS_WARNING;
557 break;
558 case DS_Note:
559 Severity = LTO_DS_NOTE;
560 break;
561 }
562 // Create the string that will be reported to the external diagnostic handler.
563 std::string MsgStorage;
564 raw_string_ostream Stream(MsgStorage);
565 DiagnosticPrinterRawOStream DP(Stream);
566 DI.print(DP);
567 Stream.flush();
568
569 // If this method has been called it means someone has set up an external
570 // diagnostic handler. Assert on that.
571 assert(DiagHandler && "Invalid diagnostic handler");
572 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
573}
574
575void
576LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
577 void *Ctxt) {
578 this->DiagHandler = DiagHandler;
579 this->DiagContext = Ctxt;
580 if (!DiagHandler)
581 return Context.setDiagnosticHandler(NULL, NULL);
582 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
583 // diagnostic to the external DiagHandler.
584 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
585}