blob: 68ca9852d23139097598407052f9b2f0ad0c8f5c [file] [log] [blame]
Logan1f028c02010-11-27 01:02:48 +08001/*
2 * Copyright 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Loganc4395232010-11-27 18:54:17 +080017#include "Compiler.h"
Logan1f028c02010-11-27 01:02:48 +080018
Logan35849002011-01-15 07:30:43 +080019#include "Config.h"
20
Loganeb3d12b2010-12-16 06:20:18 +080021#include "ContextManager.h"
Logan4dcd6792011-02-28 05:12:00 +080022#include "DebugHelper.h"
Logan2a6dc822011-01-06 04:05:20 +080023#include "ScriptCompiled.h"
Logan75cc8a52011-01-07 06:06:52 +080024#include "Sha1Helper.h"
Loganeb3d12b2010-12-16 06:20:18 +080025
Logandf23afa2010-11-27 11:04:54 +080026#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080027
Logandf23afa2010-11-27 11:04:54 +080028#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080029
Logan1f028c02010-11-27 01:02:48 +080030#include "llvm/Bitcode/ReaderWriter.h"
31
Logan1f028c02010-11-27 01:02:48 +080032#include "llvm/CodeGen/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080033#include "llvm/CodeGen/RegAllocRegistry.h"
34#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080035
Logandf23afa2010-11-27 11:04:54 +080036#include "llvm/Transforms/IPO.h"
37#include "llvm/Transforms/Scalar.h"
38
39#include "llvm/Target/SubtargetFeature.h"
40#include "llvm/Target/TargetData.h"
41#include "llvm/Target/TargetMachine.h"
42#include "llvm/Target/TargetOptions.h"
43#include "llvm/Target/TargetRegistry.h"
44#include "llvm/Target/TargetSelect.h"
45
46#include "llvm/Support/ErrorHandling.h"
Shih-wei Liao898c5a92011-05-18 07:02:39 -070047#include "llvm/Support/FormattedStream.h"
Logandf23afa2010-11-27 11:04:54 +080048#include "llvm/Support/MemoryBuffer.h"
49
50#include "llvm/GlobalValue.h"
51#include "llvm/Linker.h"
52#include "llvm/LLVMContext.h"
53#include "llvm/Metadata.h"
54#include "llvm/Module.h"
55#include "llvm/PassManager.h"
56#include "llvm/Value.h"
57
58#include <errno.h>
59#include <sys/file.h>
Logandf23afa2010-11-27 11:04:54 +080060#include <sys/stat.h>
61#include <sys/types.h>
62#include <unistd.h>
63
Logan75cc8a52011-01-07 06:06:52 +080064#include <string.h>
Logan8b77a772010-12-21 09:11:01 +080065
Logandf23afa2010-11-27 11:04:54 +080066#include <string>
67#include <vector>
Logan1f028c02010-11-27 01:02:48 +080068
Logan1f028c02010-11-27 01:02:48 +080069namespace bcc {
70
71//////////////////////////////////////////////////////////////////////////////
72// BCC Compiler Static Variables
73//////////////////////////////////////////////////////////////////////////////
74
75bool Compiler::GlobalInitialized = false;
76
Logan1f028c02010-11-27 01:02:48 +080077// Code generation optimization level for the compiler
78llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
79
80std::string Compiler::Triple;
81
82std::string Compiler::CPU;
83
84std::vector<std::string> Compiler::Features;
85
Stephen Hines071288a2011-01-27 14:38:26 -080086// Name of metadata node where pragma info resides (should be synced with
Logan1f028c02010-11-27 01:02:48 +080087// slang.cpp)
88const llvm::StringRef Compiler::PragmaMetadataName = "#pragma";
89
Stephen Hines071288a2011-01-27 14:38:26 -080090// Name of metadata node where exported variable names reside (should be
Logan1f028c02010-11-27 01:02:48 +080091// synced with slang_rs_metadata.h)
92const llvm::StringRef Compiler::ExportVarMetadataName = "#rs_export_var";
93
Stephen Hines071288a2011-01-27 14:38:26 -080094// Name of metadata node where exported function names reside (should be
Logan1f028c02010-11-27 01:02:48 +080095// synced with slang_rs_metadata.h)
96const llvm::StringRef Compiler::ExportFuncMetadataName = "#rs_export_func";
97
Stephen Hines071288a2011-01-27 14:38:26 -080098// Name of metadata node where RS object slot info resides (should be
99// synced with slang_rs_metadata.h)
100const llvm::StringRef Compiler::ObjectSlotMetadataName = "#rs_object_slots";
Logan1f028c02010-11-27 01:02:48 +0800101
102//////////////////////////////////////////////////////////////////////////////
103// Compiler
104//////////////////////////////////////////////////////////////////////////////
105
106void Compiler::GlobalInitialization() {
107 if (GlobalInitialized)
108 return;
109
Logane1323992011-01-12 04:47:13 +0800110 LOGI("LIBBCC BUILD: %s\n", libbcc_build_time);
Logan87066272010-12-29 00:34:32 +0800111
Logan1f028c02010-11-27 01:02:48 +0800112 // if (!llvm::llvm_is_multithreaded())
113 // llvm::llvm_start_multithreaded();
114
115 // Set Triple, CPU and Features here
116 Triple = TARGET_TRIPLE_STRING;
117
Logan1f028c02010-11-27 01:02:48 +0800118 Features.push_back("+vfp3");
119 Features.push_back("+d16");
120
Logan4fe966f2011-02-27 08:26:40 +0800121 // NOTE: Currently, we have to turn off the support for NEON explicitly.
122 // Since the ARMCodeEmitter.cpp is not ready for JITing NEON
123 // instructions.
124 Features.push_back("-neon"); // TODO(sliao): NEON for JIT
125 Features.push_back("-neonfp");
126 Features.push_back("-vmlx");
127
Logan1f028c02010-11-27 01:02:48 +0800128#if defined(DEFAULT_ARM_CODEGEN) || defined(PROVIDE_ARM_CODEGEN)
129 LLVMInitializeARMTargetInfo();
130 LLVMInitializeARMTarget();
Logan35849002011-01-15 07:30:43 +0800131#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800132 LLVMInitializeARMDisassembler();
133 LLVMInitializeARMAsmPrinter();
134#endif
135#endif
136
137#if defined(DEFAULT_X86_CODEGEN) || defined(PROVIDE_X86_CODEGEN)
138 LLVMInitializeX86TargetInfo();
139 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800140#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800141 LLVMInitializeX86Disassembler();
142 LLVMInitializeX86AsmPrinter();
143#endif
144#endif
145
146#if defined(DEFAULT_X64_CODEGEN) || defined(PROVIDE_X64_CODEGEN)
147 LLVMInitializeX86TargetInfo();
148 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800149#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800150 LLVMInitializeX86Disassembler();
151 LLVMInitializeX86AsmPrinter();
152#endif
153#endif
154
155 // -O0: llvm::CodeGenOpt::None
156 // -O1: llvm::CodeGenOpt::Less
157 // -O2: llvm::CodeGenOpt::Default
158 // -O3: llvm::CodeGenOpt::Aggressive
Shih-wei Liao72f67a62010-12-14 13:36:15 -0800159 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
Logan1f028c02010-11-27 01:02:48 +0800160
161 // Below are the global settings to LLVM
162
163 // Disable frame pointer elimination optimization
164 llvm::NoFramePointerElim = false;
165
166 // Use hardfloat ABI
167 //
168 // TODO(all): Need to detect the CPU capability and decide whether to use
169 // softfp. To use softfp, change following 2 lines to
170 //
171 // llvm::FloatABIType = llvm::FloatABI::Soft;
172 // llvm::UseSoftFloat = true;
173 //
Shih-wei Liaoe728cb82010-12-15 15:20:47 -0800174 llvm::FloatABIType = llvm::FloatABI::Soft;
Logan1f028c02010-11-27 01:02:48 +0800175 llvm::UseSoftFloat = false;
176
177 // BCC needs all unknown symbols resolved at JIT/compilation time.
178 // So we don't need any dynamic relocation model.
179 llvm::TargetMachine::setRelocationModel(llvm::Reloc::Static);
180
181#if defined(DEFAULT_X64_CODEGEN)
182 // Data address in X86_64 architecture may reside in a far-away place
183 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Medium);
184#else
185 // This is set for the linker (specify how large of the virtual addresses
186 // we can access for all unknown symbols.)
187 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Small);
188#endif
189
190 // Register the scheduler
191 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
192
193 // Register allocation policy:
194 // createFastRegisterAllocator: fast but bad quality
195 // createLinearScanRegisterAllocator: not so fast but good quality
196 llvm::RegisterRegAlloc::setDefault
197 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
198 llvm::createFastRegisterAllocator :
199 llvm::createLinearScanRegisterAllocator);
200
Logan35849002011-01-15 07:30:43 +0800201#if USE_CACHE
Logan75cc8a52011-01-07 06:06:52 +0800202 // Calculate the SHA1 checksum of libbcc and libRS.
Logan35849002011-01-15 07:30:43 +0800203#if USE_LIBBCC_SHA1SUM
Logan75cc8a52011-01-07 06:06:52 +0800204 calcFileSHA1(sha1LibBCC, pathLibBCC);
Logane1323992011-01-12 04:47:13 +0800205#endif
Logan75cc8a52011-01-07 06:06:52 +0800206 calcFileSHA1(sha1LibRS, pathLibRS);
Logan35849002011-01-15 07:30:43 +0800207#endif
Logan75cc8a52011-01-07 06:06:52 +0800208
Logan1f028c02010-11-27 01:02:48 +0800209 GlobalInitialized = true;
210}
211
212
213void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
214 std::string *Error = static_cast<std::string*>(UserData);
215 Error->assign(Message);
216 LOGE("%s", Message.c_str());
217 exit(1);
218}
219
220
221CodeMemoryManager *Compiler::createCodeMemoryManager() {
222 mCodeMemMgr.reset(new CodeMemoryManager());
223 return mCodeMemMgr.get();
224}
225
226
227CodeEmitter *Compiler::createCodeEmitter() {
Logan7dcaac92011-01-06 04:26:23 +0800228 mCodeEmitter.reset(new CodeEmitter(mpResult, mCodeMemMgr.get()));
Logan1f028c02010-11-27 01:02:48 +0800229 return mCodeEmitter.get();
230}
231
232
Logan2a6dc822011-01-06 04:05:20 +0800233Compiler::Compiler(ScriptCompiled *result)
234 : mpResult(result),
Logan1f028c02010-11-27 01:02:48 +0800235 mpSymbolLookupFn(NULL),
236 mpSymbolLookupContext(NULL),
237 mContext(NULL),
238 mModule(NULL),
239 mHasLinked(false) /* Turn off linker */ {
240 llvm::remove_fatal_error_handler();
241 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
242 mContext = new llvm::LLVMContext();
243 return;
244}
245
Logan1f028c02010-11-27 01:02:48 +0800246
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700247// input objPath: For example,
248// /data/user/0/com.example.android.rs.fountain/cache/
249// @com.example.android.rs.fountain:raw@fountain.oBCC
250// output objPath: /data/user/0/com.example.android.rs.fountain/cache/
251// fountain.o
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700252//
253bool Compiler::getObjPath(std::string &objPath) {
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700254 size_t found0 = objPath.find("@");
255 size_t found1 = objPath.rfind("@");
256
257 if (found0 == found1 ||
258 found0 == string::npos ||
259 found1 == string::npos) {
260 LOGE("Ill formatted resource name '%s'. The name should contain 2 @s",
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700261 objPath.c_str());
262 return false;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700263 }
264
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700265 objPath.replace(found0, found1 - found0 + 1, "", 0);
266 objPath.resize(objPath.length() - 3);
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700267
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700268 LOGV("objPath = %s", objPath.c_str());
269 return true;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700270}
271
272
Logan474cbd22011-01-31 01:47:44 +0800273llvm::Module *Compiler::parseBitcodeFile(llvm::MemoryBuffer *MEM) {
274 llvm::Module *result = llvm::ParseBitcodeFile(MEM, *mContext, &mError);
Logan1f028c02010-11-27 01:02:48 +0800275
Logan474cbd22011-01-31 01:47:44 +0800276 if (!result) {
277 LOGE("Unable to ParseBitcodeFile: %s\n", mError.c_str());
278 return NULL;
Logan1f028c02010-11-27 01:02:48 +0800279 }
280
Logan474cbd22011-01-31 01:47:44 +0800281 return result;
Logan1f028c02010-11-27 01:02:48 +0800282}
283
284
Logan474cbd22011-01-31 01:47:44 +0800285int Compiler::linkModule(llvm::Module *moduleWith) {
286 if (llvm::Linker::LinkModules(mModule, moduleWith, &mError) != 0) {
Logan1f028c02010-11-27 01:02:48 +0800287 return hasError();
288 }
289
Logan1f028c02010-11-27 01:02:48 +0800290 // Everything for linking should be settled down here with no error occurs
291 mHasLinked = true;
292 return hasError();
293}
294
295
Logan1f028c02010-11-27 01:02:48 +0800296int Compiler::compile() {
297 llvm::TargetData *TD = NULL;
298
299 llvm::TargetMachine *TM = NULL;
300 const llvm::Target *Target;
301 std::string FeaturesStr;
302
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700303#if CLASSIC_JIT
Logan1f028c02010-11-27 01:02:48 +0800304 llvm::FunctionPassManager *CodeGenPasses = NULL;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700305#endif
306
307#if MC_ASSEMBLER
308 bool RelaxAll = true;
309 llvm::PassManager MCCodeGenPasses;
310
Shih-wei Liao5c00f4f2011-05-20 04:14:54 -0700311 std::string objPath(mCachePath);
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700312
313 if (!getObjPath(objPath)) {
314 LOGE("Fail to create objPath");
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700315 return 1;
316 }
317
318 int Fd = -1;
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700319 Fd = open(objPath.c_str(), O_CREAT | O_RDWR | O_TRUNC,
Shih-wei Liao4fdaa3e2011-05-21 07:45:21 -0700320 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH /* 0644 */);
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700321
322 if (Fd < 0) {
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700323 LOGE("Fail to open file '%s'", objPath.c_str());
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700324 return 1;
325 }
326
327 llvm::raw_fd_ostream OutFdOS(Fd, /* shouldClose= */ false);
328 OutFdOS.seek(0);
329 llvm::formatted_raw_ostream OutFOS(OutFdOS);
330#endif
Logan1f028c02010-11-27 01:02:48 +0800331
332 const llvm::NamedMDNode *PragmaMetadata;
333 const llvm::NamedMDNode *ExportVarMetadata;
334 const llvm::NamedMDNode *ExportFuncMetadata;
Stephen Hines071288a2011-01-27 14:38:26 -0800335 const llvm::NamedMDNode *ObjectSlotMetadata;
Logan1f028c02010-11-27 01:02:48 +0800336
337 if (mModule == NULL) // No module was loaded
338 return 0;
339
340 // Create TargetMachine
341 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
342 if (hasError())
343 goto on_bcc_compile_error;
344
345 if (!CPU.empty() || !Features.empty()) {
346 llvm::SubtargetFeatures F;
347 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800348
349 for (std::vector<std::string>::const_iterator
350 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800351 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800352 }
353
Logan1f028c02010-11-27 01:02:48 +0800354 FeaturesStr = F.getString();
355 }
356
357 TM = Target->createTargetMachine(Triple, FeaturesStr);
358 if (TM == NULL) {
359 setError("Failed to create target machine implementation for the"
360 " specified triple '" + Triple + "'");
361 goto on_bcc_compile_error;
362 }
363
364 // Create memory manager for creation of code emitter later.
365 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
366 setError("Failed to startup memory management for further compilation");
367 goto on_bcc_compile_error;
368 }
Logan02286cb2011-01-07 00:30:47 +0800369
370 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800371
372 // Create code emitter
373 if (!mCodeEmitter.get()) {
374 if (!createCodeEmitter()) {
375 setError("Failed to create machine code emitter to complete"
376 " the compilation");
377 goto on_bcc_compile_error;
378 }
379 } else {
380 // Reuse the code emitter
381 mCodeEmitter->reset();
382 }
383
384 mCodeEmitter->setTargetMachine(*TM);
385 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
386 mpSymbolLookupContext);
387
388 // Get target data from Module
389 TD = new llvm::TargetData(mModule);
390
391 // Load named metadata
392 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
393 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
394 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
Stephen Hines071288a2011-01-27 14:38:26 -0800395 ObjectSlotMetadata = mModule->getNamedMetadata(ObjectSlotMetadataName);
Logan1f028c02010-11-27 01:02:48 +0800396
Shih-wei Liao644fcf22011-01-16 21:56:26 -0800397#if 0
398 mHasLinked = false;
399#endif
400
Logan1f028c02010-11-27 01:02:48 +0800401 // Create LTO passes and run them on the mModule
402 if (mHasLinked) {
403 llvm::TimePassesIsEnabled = true; // TODO(all)
404 llvm::PassManager LTOPasses;
405 LTOPasses.add(new llvm::TargetData(*TD));
406
407 std::vector<const char*> ExportSymbols;
408
409 // A workaround for getting export variable and function name. Will refine
410 // it soon.
411 if (ExportVarMetadata) {
412 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
413 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
414 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
415 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
416 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
417 llvm::StringRef ExportVarName =
418 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
419 ExportSymbols.push_back(ExportVarName.data());
420 }
421 }
422 }
423 }
424
425 if (ExportFuncMetadata) {
426 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
427 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
428 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
429 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
430 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
431 llvm::StringRef ExportFuncName =
432 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
433 ExportSymbols.push_back(ExportFuncName.data());
434 }
435 }
436 }
437 }
438 // root() and init() are born to be exported
439 ExportSymbols.push_back("root");
440 ExportSymbols.push_back("init");
441
442 // We now create passes list performing LTO. These are copied from
443 // (including comments) llvm::createStandardLTOPasses().
444
445 // Internalize all other symbols not listed in ExportSymbols
446 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
447
448 // Propagate constants at call sites into the functions they call. This
449 // opens opportunities for globalopt (and inlining) by substituting
450 // function pointers passed as arguments to direct uses of functions.
451 LTOPasses.add(llvm::createIPSCCPPass());
452
453 // Now that we internalized some globals, see if we can hack on them!
454 LTOPasses.add(llvm::createGlobalOptimizerPass());
455
456 // Linking modules together can lead to duplicated global constants, only
457 // keep one copy of each constant...
458 LTOPasses.add(llvm::createConstantMergePass());
459
460 // Remove unused arguments from functions...
461 LTOPasses.add(llvm::createDeadArgEliminationPass());
462
463 // Reduce the code after globalopt and ipsccp. Both can open up
464 // significant simplification opportunities, and both can propagate
465 // functions through function pointers. When this happens, we often have
466 // to resolve varargs calls, etc, so let instcombine do this.
467 LTOPasses.add(llvm::createInstructionCombiningPass());
468
469 // Inline small functions
470 LTOPasses.add(llvm::createFunctionInliningPass());
471
472 // Remove dead EH info.
473 LTOPasses.add(llvm::createPruneEHPass());
474
475 // Internalize the globals again after inlining
476 LTOPasses.add(llvm::createGlobalOptimizerPass());
477
478 // Remove dead functions.
479 LTOPasses.add(llvm::createGlobalDCEPass());
480
481 // If we didn't decide to inline a function, check to see if we can
482 // transform it to pass arguments by value instead of by reference.
483 LTOPasses.add(llvm::createArgumentPromotionPass());
484
485 // The IPO passes may leave cruft around. Clean up after them.
486 LTOPasses.add(llvm::createInstructionCombiningPass());
487 LTOPasses.add(llvm::createJumpThreadingPass());
488
489 // Break up allocas
490 LTOPasses.add(llvm::createScalarReplAggregatesPass());
491
492 // Run a few AA driven optimizations here and now, to cleanup the code.
493 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
494 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
495
496 // Hoist loop invariants.
497 LTOPasses.add(llvm::createLICMPass());
498
499 // Remove redundancies.
500 LTOPasses.add(llvm::createGVNPass());
501
502 // Remove dead memcpys.
503 LTOPasses.add(llvm::createMemCpyOptPass());
504
505 // Nuke dead stores.
506 LTOPasses.add(llvm::createDeadStoreEliminationPass());
507
508 // Cleanup and simplify the code after the scalar optimizations.
509 LTOPasses.add(llvm::createInstructionCombiningPass());
510
511 LTOPasses.add(llvm::createJumpThreadingPass());
512
513 // Delete basic blocks, which optimization passes may have killed.
514 LTOPasses.add(llvm::createCFGSimplificationPass());
515
516 // Now that we have optimized the program, discard unreachable functions.
517 LTOPasses.add(llvm::createGlobalDCEPass());
518
519 LTOPasses.run(*mModule);
520 }
521
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700522#if CLASSIC_JIT
Logan1f028c02010-11-27 01:02:48 +0800523 // Create code-gen pass to run the code emitter
524 CodeGenPasses = new llvm::FunctionPassManager(mModule);
525 CodeGenPasses->add(TD); // Will take the ownership of TD
526
527 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
528 *mCodeEmitter,
529 CodeGenOptLevel)) {
530 setError("The machine code emission is not supported by BCC on target '"
531 + Triple + "'");
532 goto on_bcc_compile_error;
533 }
534
535 // Run the pass (the code emitter) on every non-declaration function in the
536 // module
537 CodeGenPasses->doInitialization();
538 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
539 I != E; I++) {
540 if (!I->isDeclaration()) {
541 CodeGenPasses->run(*I);
542 }
543 }
544
545 CodeGenPasses->doFinalization();
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700546#endif
Logan1f028c02010-11-27 01:02:48 +0800547
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700548#if MC_ASSEMBLER
549 TM->setMCRelaxAll(RelaxAll);
550
551 MCCodeGenPasses.add(new llvm::TargetData(*TD));
552
553 if (TM->addPassesToEmitFile(MCCodeGenPasses, OutFOS,
554 llvm::TargetMachine::CGFT_ObjectFile,
555 CodeGenOptLevel)) {
556 setError("Fail to add passes to emit file");
557 goto on_bcc_compile_error;
558 }
559
560 MCCodeGenPasses.run(*mModule);
561#endif
Logan1f028c02010-11-27 01:02:48 +0800562 // Copy the global address mapping from code emitter and remapping
563 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800564 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
565
Logan1f028c02010-11-27 01:02:48 +0800566 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
567 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
568 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
569 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
570 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
571 llvm::StringRef ExportVarName =
572 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
573
574 CodeEmitter::global_addresses_const_iterator I, E;
575 for (I = mCodeEmitter->global_address_begin(),
576 E = mCodeEmitter->global_address_end();
577 I != E; I++) {
578 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
579 continue;
580 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800581 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800582 break;
583 }
584 }
585 if (I != mCodeEmitter->global_address_end())
586 continue; // found
587 }
588 }
589 // if reaching here, we know the global variable record in metadata is
590 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800591 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800592 }
Logan2a6dc822011-01-06 04:05:20 +0800593
Stephen Hinesbbcef8a2011-05-04 19:40:10 -0700594 bccAssert((varList.size() == ExportVarMetadata->getNumOperands()) &&
595 "Number of slots doesn't match the number of export variables!");
Logan1f028c02010-11-27 01:02:48 +0800596 }
597
598 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800599 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
600
Logan1f028c02010-11-27 01:02:48 +0800601 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
602 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
603 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
604 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
605 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
606 llvm::StringRef ExportFuncName =
607 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800608 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800609 }
610 }
611 }
612 }
613
614 // Tell code emitter now can release the memory using during the JIT since
615 // we have done the code emission
616 mCodeEmitter->releaseUnnecessary();
617
618 // Finally, read pragma information from the metadata node of the @Module if
619 // any.
Logan2a6dc822011-01-06 04:05:20 +0800620 if (PragmaMetadata) {
621 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
622
Logan1f028c02010-11-27 01:02:48 +0800623 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
624 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
625 if (Pragma != NULL &&
626 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
627 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
628 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
629
630 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
631 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
632 llvm::StringRef PragmaName =
633 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
634 llvm::StringRef PragmaValue =
635 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
636
Logan2a6dc822011-01-06 04:05:20 +0800637 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800638 std::make_pair(std::string(PragmaName.data(),
639 PragmaName.size()),
640 std::string(PragmaValue.data(),
641 PragmaValue.size())));
642 }
643 }
644 }
Logan2a6dc822011-01-06 04:05:20 +0800645 }
Logan1f028c02010-11-27 01:02:48 +0800646
Stephen Hines071288a2011-01-27 14:38:26 -0800647 if (ObjectSlotMetadata) {
648 ScriptCompiled::ObjectSlotList &objectSlotList = mpResult->mObjectSlots;
649
650 for (int i = 0, e = ObjectSlotMetadata->getNumOperands(); i != e; i++) {
651 llvm::MDNode *ObjectSlot = ObjectSlotMetadata->getOperand(i);
652 if (ObjectSlot != NULL &&
653 ObjectSlot->getNumOperands() == 1) {
654 llvm::Value *SlotMDS = ObjectSlot->getOperand(0);
655 if (SlotMDS->getValueID() == llvm::Value::MDStringVal) {
656 llvm::StringRef Slot =
657 static_cast<llvm::MDString*>(SlotMDS)->getString();
658 uint32_t USlot = 0;
659 if (Slot.getAsInteger(10, USlot)) {
660 setError("Non-integer object slot value '" + Slot.str() + "'");
661 goto on_bcc_compile_error;
662 }
663 objectSlotList.push_back(USlot);
664 }
665 }
666 }
667 }
668
Logan1f028c02010-11-27 01:02:48 +0800669on_bcc_compile_error:
670 // LOGE("on_bcc_compiler_error");
671 if (CodeGenPasses) {
672 delete CodeGenPasses;
673 } else if (TD) {
674 delete TD;
675 }
676 if (TM)
677 delete TM;
678
679 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800680 return 0;
Logan1f028c02010-11-27 01:02:48 +0800681 }
682
683 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800684 return 1;
Logan1f028c02010-11-27 01:02:48 +0800685}
686
687
Logan1f028c02010-11-27 01:02:48 +0800688Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800689 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800690 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800691
692 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800693}
694
Logan1f028c02010-11-27 01:02:48 +0800695} // namespace bcc