blob: 188a0ff412c2990f8870d736902f5801b9b55cbe [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
17#define LOG_TAG "bcc"
18#include <cutils/log.h>
19
Logan1f028c02010-11-27 01:02:48 +080020#if defined(__arm__)
21# define DEFAULT_ARM_CODEGEN
22# define PROVIDE_ARM_CODEGEN
23#elif defined(__i386__)
24# define DEFAULT_X86_CODEGEN
25# define PROVIDE_X86_CODEGEN
26#elif defined(__x86_64__)
27# define DEFAULT_X64_CODEGEN
28# define PROVIDE_X64_CODEGEN
29#endif
30
31#if defined(FORCE_ARM_CODEGEN)
32# define DEFAULT_ARM_CODEGEN
33# undef DEFAULT_X86_CODEGEN
34# undef DEFAULT_X64_CODEGEN
35# define PROVIDE_ARM_CODEGEN
36# undef PROVIDE_X86_CODEGEN
37# undef PROVIDE_X64_CODEGEN
38#elif defined(FORCE_X86_CODEGEN)
39# undef DEFAULT_ARM_CODEGEN
40# define DEFAULT_X86_CODEGEN
41# undef DEFAULT_X64_CODEGEN
42# undef PROVIDE_ARM_CODEGEN
43# define PROVIDE_X86_CODEGEN
44# undef PROVIDE_X64_CODEGEN
45#elif defined(FORCE_X64_CODEGEN)
46# undef DEFAULT_ARM_CODEGEN
47# undef DEFAULT_X86_CODEGEN
48# define DEFAULT_X64_CODEGEN
49# undef PROVIDE_ARM_CODEGEN
50# undef PROVIDE_X86_CODEGEN
51# define PROVIDE_X64_CODEGEN
52#endif
53
54#if defined(DEFAULT_ARM_CODEGEN)
Logandf23afa2010-11-27 11:04:54 +080055# define TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi"
Logan1f028c02010-11-27 01:02:48 +080056#elif defined(DEFAULT_X86_CODEGEN)
Logandf23afa2010-11-27 11:04:54 +080057# define TARGET_TRIPLE_STRING "i686-unknown-linux"
Logan1f028c02010-11-27 01:02:48 +080058#elif defined(DEFAULT_X64_CODEGEN)
Logandf23afa2010-11-27 11:04:54 +080059# define TARGET_TRIPLE_STRING "x86_64-unknown-linux"
Logan1f028c02010-11-27 01:02:48 +080060#endif
61
62#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
63# define ARM_USE_VFP
64#endif
65
Loganc4395232010-11-27 18:54:17 +080066#include "Compiler.h"
Logan1f028c02010-11-27 01:02:48 +080067
Loganeb3d12b2010-12-16 06:20:18 +080068#include "ContextManager.h"
Logan2a6dc822011-01-06 04:05:20 +080069#include "ScriptCompiled.h"
Logan75cc8a52011-01-07 06:06:52 +080070#include "Sha1Helper.h"
Loganeb3d12b2010-12-16 06:20:18 +080071
Logandf23afa2010-11-27 11:04:54 +080072#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080073
Logandf23afa2010-11-27 11:04:54 +080074#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080075
Logan1f028c02010-11-27 01:02:48 +080076#include "llvm/Bitcode/ReaderWriter.h"
77
Logan1f028c02010-11-27 01:02:48 +080078#include "llvm/CodeGen/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080079#include "llvm/CodeGen/RegAllocRegistry.h"
80#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080081
Logandf23afa2010-11-27 11:04:54 +080082#include "llvm/Transforms/IPO.h"
83#include "llvm/Transforms/Scalar.h"
84
85#include "llvm/Target/SubtargetFeature.h"
86#include "llvm/Target/TargetData.h"
87#include "llvm/Target/TargetMachine.h"
88#include "llvm/Target/TargetOptions.h"
89#include "llvm/Target/TargetRegistry.h"
90#include "llvm/Target/TargetSelect.h"
91
92#include "llvm/Support/ErrorHandling.h"
93#include "llvm/Support/MemoryBuffer.h"
94
95#include "llvm/GlobalValue.h"
96#include "llvm/Linker.h"
97#include "llvm/LLVMContext.h"
98#include "llvm/Metadata.h"
99#include "llvm/Module.h"
100#include "llvm/PassManager.h"
101#include "llvm/Value.h"
102
103#include <errno.h>
104#include <sys/file.h>
Logandf23afa2010-11-27 11:04:54 +0800105#include <sys/stat.h>
106#include <sys/types.h>
107#include <unistd.h>
108
Logan75cc8a52011-01-07 06:06:52 +0800109#include <string.h>
Logan8b77a772010-12-21 09:11:01 +0800110
Logandf23afa2010-11-27 11:04:54 +0800111#include <string>
112#include <vector>
Logan1f028c02010-11-27 01:02:48 +0800113
Logan1f028c02010-11-27 01:02:48 +0800114namespace bcc {
115
116//////////////////////////////////////////////////////////////////////////////
117// BCC Compiler Static Variables
118//////////////////////////////////////////////////////////////////////////////
119
120bool Compiler::GlobalInitialized = false;
121
Logan1f028c02010-11-27 01:02:48 +0800122// Code generation optimization level for the compiler
123llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
124
125std::string Compiler::Triple;
126
127std::string Compiler::CPU;
128
129std::vector<std::string> Compiler::Features;
130
131// The named of metadata node that pragma resides (should be synced with
132// slang.cpp)
133const llvm::StringRef Compiler::PragmaMetadataName = "#pragma";
134
135// The named of metadata node that export variable name resides (should be
136// synced with slang_rs_metadata.h)
137const llvm::StringRef Compiler::ExportVarMetadataName = "#rs_export_var";
138
139// The named of metadata node that export function name resides (should be
140// synced with slang_rs_metadata.h)
141const llvm::StringRef Compiler::ExportFuncMetadataName = "#rs_export_func";
142
143
144//////////////////////////////////////////////////////////////////////////////
145// Compiler
146//////////////////////////////////////////////////////////////////////////////
147
148void Compiler::GlobalInitialization() {
149 if (GlobalInitialized)
150 return;
151
Logane1323992011-01-12 04:47:13 +0800152 LOGI("LIBBCC BUILD: %s\n", libbcc_build_time);
Logan87066272010-12-29 00:34:32 +0800153
Logan1f028c02010-11-27 01:02:48 +0800154 // if (!llvm::llvm_is_multithreaded())
155 // llvm::llvm_start_multithreaded();
156
157 // Set Triple, CPU and Features here
158 Triple = TARGET_TRIPLE_STRING;
159
160 // TODO(sliao): NEON for JIT
161 // Features.push_back("+neon");
162 // Features.push_back("+vmlx");
163 // Features.push_back("+neonfp");
164 Features.push_back("+vfp3");
165 Features.push_back("+d16");
166
167#if defined(DEFAULT_ARM_CODEGEN) || defined(PROVIDE_ARM_CODEGEN)
168 LLVMInitializeARMTargetInfo();
169 LLVMInitializeARMTarget();
170#if defined(USE_DISASSEMBLER)
171 LLVMInitializeARMDisassembler();
172 LLVMInitializeARMAsmPrinter();
173#endif
174#endif
175
176#if defined(DEFAULT_X86_CODEGEN) || defined(PROVIDE_X86_CODEGEN)
177 LLVMInitializeX86TargetInfo();
178 LLVMInitializeX86Target();
179#if defined(USE_DISASSEMBLER)
180 LLVMInitializeX86Disassembler();
181 LLVMInitializeX86AsmPrinter();
182#endif
183#endif
184
185#if defined(DEFAULT_X64_CODEGEN) || defined(PROVIDE_X64_CODEGEN)
186 LLVMInitializeX86TargetInfo();
187 LLVMInitializeX86Target();
188#if defined(USE_DISASSEMBLER)
189 LLVMInitializeX86Disassembler();
190 LLVMInitializeX86AsmPrinter();
191#endif
192#endif
193
194 // -O0: llvm::CodeGenOpt::None
195 // -O1: llvm::CodeGenOpt::Less
196 // -O2: llvm::CodeGenOpt::Default
197 // -O3: llvm::CodeGenOpt::Aggressive
Shih-wei Liao72f67a62010-12-14 13:36:15 -0800198 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
Logan1f028c02010-11-27 01:02:48 +0800199
200 // Below are the global settings to LLVM
201
202 // Disable frame pointer elimination optimization
203 llvm::NoFramePointerElim = false;
204
205 // Use hardfloat ABI
206 //
207 // TODO(all): Need to detect the CPU capability and decide whether to use
208 // softfp. To use softfp, change following 2 lines to
209 //
210 // llvm::FloatABIType = llvm::FloatABI::Soft;
211 // llvm::UseSoftFloat = true;
212 //
Shih-wei Liaoe728cb82010-12-15 15:20:47 -0800213 llvm::FloatABIType = llvm::FloatABI::Soft;
Logan1f028c02010-11-27 01:02:48 +0800214 llvm::UseSoftFloat = false;
215
216 // BCC needs all unknown symbols resolved at JIT/compilation time.
217 // So we don't need any dynamic relocation model.
218 llvm::TargetMachine::setRelocationModel(llvm::Reloc::Static);
219
220#if defined(DEFAULT_X64_CODEGEN)
221 // Data address in X86_64 architecture may reside in a far-away place
222 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Medium);
223#else
224 // This is set for the linker (specify how large of the virtual addresses
225 // we can access for all unknown symbols.)
226 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Small);
227#endif
228
229 // Register the scheduler
230 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
231
232 // Register allocation policy:
233 // createFastRegisterAllocator: fast but bad quality
234 // createLinearScanRegisterAllocator: not so fast but good quality
235 llvm::RegisterRegAlloc::setDefault
236 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
237 llvm::createFastRegisterAllocator :
238 llvm::createLinearScanRegisterAllocator);
239
Logan75cc8a52011-01-07 06:06:52 +0800240 // Calculate the SHA1 checksum of libbcc and libRS.
Logane1323992011-01-12 04:47:13 +0800241#if defined(USE_LIBBCC_SHA1SUM)
Logan75cc8a52011-01-07 06:06:52 +0800242 calcFileSHA1(sha1LibBCC, pathLibBCC);
Logane1323992011-01-12 04:47:13 +0800243#endif
Logan75cc8a52011-01-07 06:06:52 +0800244 calcFileSHA1(sha1LibRS, pathLibRS);
245
Logan1f028c02010-11-27 01:02:48 +0800246 GlobalInitialized = true;
247}
248
249
250void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
251 std::string *Error = static_cast<std::string*>(UserData);
252 Error->assign(Message);
253 LOGE("%s", Message.c_str());
254 exit(1);
255}
256
257
258CodeMemoryManager *Compiler::createCodeMemoryManager() {
259 mCodeMemMgr.reset(new CodeMemoryManager());
260 return mCodeMemMgr.get();
261}
262
263
264CodeEmitter *Compiler::createCodeEmitter() {
Logan7dcaac92011-01-06 04:26:23 +0800265 mCodeEmitter.reset(new CodeEmitter(mpResult, mCodeMemMgr.get()));
Logan1f028c02010-11-27 01:02:48 +0800266 return mCodeEmitter.get();
267}
268
269
Logan2a6dc822011-01-06 04:05:20 +0800270Compiler::Compiler(ScriptCompiled *result)
271 : mpResult(result),
Logan1f028c02010-11-27 01:02:48 +0800272 mpSymbolLookupFn(NULL),
273 mpSymbolLookupContext(NULL),
274 mContext(NULL),
275 mModule(NULL),
276 mHasLinked(false) /* Turn off linker */ {
277 llvm::remove_fatal_error_handler();
278 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
279 mContext = new llvm::LLVMContext();
280 return;
281}
282
Shih-wei Liaod1613092010-12-23 22:59:15 +0800283// Compiler::readBC
284// Parameters:
Shih-wei Liaod1613092010-12-23 22:59:15 +0800285//
Loganf340bf72011-01-14 17:51:40 +0800286int Compiler::readBC(const char *bitcode, size_t bitcodeSize) {
Logan1f028c02010-11-27 01:02:48 +0800287 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
288
289 if (bitcode == NULL || bitcodeSize <= 0)
Loganf340bf72011-01-14 17:51:40 +0800290 return 1;
Logan1f028c02010-11-27 01:02:48 +0800291
292 // Package input to object MemoryBuffer
293 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
294 llvm::StringRef(bitcode, bitcodeSize)));
295
296 if (MEM.get() == NULL) {
297 setError("Error reading input program bitcode into memory");
298 return hasError();
299 }
300
301 // Read the input Bitcode as a Module
302 mModule = llvm::ParseBitcodeFile(MEM.get(), *mContext, &mError);
303 MEM.reset();
304 return hasError();
305}
306
307
308int Compiler::linkBC(const char *bitcode, size_t bitcodeSize) {
309 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
310
Shih-wei Liao4ed0ce02011-01-13 01:46:38 -0800311 if (bitcode == NULL || bitcodeSize <= 0) {
Loganf340bf72011-01-14 17:51:40 +0800312 LOGE("Invalid bitcode for linkBC\n");
Shih-wei Liao4ed0ce02011-01-13 01:46:38 -0800313 return 1;
314 }
Logan1f028c02010-11-27 01:02:48 +0800315
316 if (mModule == NULL) {
317 setError("No module presents for linking");
318 return hasError();
319 }
320
Shih-wei Liao8b67c072011-01-13 01:51:57 -0800321#if 0
322 MEM.reset(llvm::MemoryBuffer::getFile("/system/lib/rslib.bc"));
323#endif
324
Logan1f028c02010-11-27 01:02:48 +0800325 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
326 llvm::StringRef(bitcode, bitcodeSize)));
327
328 if (MEM.get() == NULL) {
329 setError("Error reading input library bitcode into memory");
330 return hasError();
331 }
332
333 llvm::OwningPtr<llvm::Module> Lib(llvm::ParseBitcodeFile(MEM.get(),
334 *mContext,
335 &mError));
336 if (Lib.get() == NULL)
337 return hasError();
338
339 if (llvm::Linker::LinkModules(mModule, Lib.take(), &mError))
340 return hasError();
341
342 // Everything for linking should be settled down here with no error occurs
343 mHasLinked = true;
344 return hasError();
345}
346
347
Logan1f028c02010-11-27 01:02:48 +0800348int Compiler::compile() {
349 llvm::TargetData *TD = NULL;
350
351 llvm::TargetMachine *TM = NULL;
352 const llvm::Target *Target;
353 std::string FeaturesStr;
354
355 llvm::FunctionPassManager *CodeGenPasses = NULL;
356
357 const llvm::NamedMDNode *PragmaMetadata;
358 const llvm::NamedMDNode *ExportVarMetadata;
359 const llvm::NamedMDNode *ExportFuncMetadata;
360
361 if (mModule == NULL) // No module was loaded
362 return 0;
363
364 // Create TargetMachine
365 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
366 if (hasError())
367 goto on_bcc_compile_error;
368
369 if (!CPU.empty() || !Features.empty()) {
370 llvm::SubtargetFeatures F;
371 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800372
373 for (std::vector<std::string>::const_iterator
374 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800375 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800376 }
377
Logan1f028c02010-11-27 01:02:48 +0800378 FeaturesStr = F.getString();
379 }
380
381 TM = Target->createTargetMachine(Triple, FeaturesStr);
382 if (TM == NULL) {
383 setError("Failed to create target machine implementation for the"
384 " specified triple '" + Triple + "'");
385 goto on_bcc_compile_error;
386 }
387
388 // Create memory manager for creation of code emitter later.
389 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
390 setError("Failed to startup memory management for further compilation");
391 goto on_bcc_compile_error;
392 }
Logan02286cb2011-01-07 00:30:47 +0800393
394 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800395
396 // Create code emitter
397 if (!mCodeEmitter.get()) {
398 if (!createCodeEmitter()) {
399 setError("Failed to create machine code emitter to complete"
400 " the compilation");
401 goto on_bcc_compile_error;
402 }
403 } else {
404 // Reuse the code emitter
405 mCodeEmitter->reset();
406 }
407
408 mCodeEmitter->setTargetMachine(*TM);
409 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
410 mpSymbolLookupContext);
411
412 // Get target data from Module
413 TD = new llvm::TargetData(mModule);
414
415 // Load named metadata
416 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
417 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
418 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
419
420 // Create LTO passes and run them on the mModule
421 if (mHasLinked) {
422 llvm::TimePassesIsEnabled = true; // TODO(all)
423 llvm::PassManager LTOPasses;
424 LTOPasses.add(new llvm::TargetData(*TD));
425
426 std::vector<const char*> ExportSymbols;
427
428 // A workaround for getting export variable and function name. Will refine
429 // it soon.
430 if (ExportVarMetadata) {
431 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
432 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
433 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
434 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
435 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
436 llvm::StringRef ExportVarName =
437 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
438 ExportSymbols.push_back(ExportVarName.data());
439 }
440 }
441 }
442 }
443
444 if (ExportFuncMetadata) {
445 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
446 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
447 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
448 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
449 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
450 llvm::StringRef ExportFuncName =
451 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
452 ExportSymbols.push_back(ExportFuncName.data());
453 }
454 }
455 }
456 }
457 // root() and init() are born to be exported
458 ExportSymbols.push_back("root");
459 ExportSymbols.push_back("init");
460
461 // We now create passes list performing LTO. These are copied from
462 // (including comments) llvm::createStandardLTOPasses().
463
464 // Internalize all other symbols not listed in ExportSymbols
465 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
466
467 // Propagate constants at call sites into the functions they call. This
468 // opens opportunities for globalopt (and inlining) by substituting
469 // function pointers passed as arguments to direct uses of functions.
470 LTOPasses.add(llvm::createIPSCCPPass());
471
472 // Now that we internalized some globals, see if we can hack on them!
473 LTOPasses.add(llvm::createGlobalOptimizerPass());
474
475 // Linking modules together can lead to duplicated global constants, only
476 // keep one copy of each constant...
477 LTOPasses.add(llvm::createConstantMergePass());
478
479 // Remove unused arguments from functions...
480 LTOPasses.add(llvm::createDeadArgEliminationPass());
481
482 // Reduce the code after globalopt and ipsccp. Both can open up
483 // significant simplification opportunities, and both can propagate
484 // functions through function pointers. When this happens, we often have
485 // to resolve varargs calls, etc, so let instcombine do this.
486 LTOPasses.add(llvm::createInstructionCombiningPass());
487
488 // Inline small functions
489 LTOPasses.add(llvm::createFunctionInliningPass());
490
491 // Remove dead EH info.
492 LTOPasses.add(llvm::createPruneEHPass());
493
494 // Internalize the globals again after inlining
495 LTOPasses.add(llvm::createGlobalOptimizerPass());
496
497 // Remove dead functions.
498 LTOPasses.add(llvm::createGlobalDCEPass());
499
500 // If we didn't decide to inline a function, check to see if we can
501 // transform it to pass arguments by value instead of by reference.
502 LTOPasses.add(llvm::createArgumentPromotionPass());
503
504 // The IPO passes may leave cruft around. Clean up after them.
505 LTOPasses.add(llvm::createInstructionCombiningPass());
506 LTOPasses.add(llvm::createJumpThreadingPass());
507
508 // Break up allocas
509 LTOPasses.add(llvm::createScalarReplAggregatesPass());
510
511 // Run a few AA driven optimizations here and now, to cleanup the code.
512 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
513 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
514
515 // Hoist loop invariants.
516 LTOPasses.add(llvm::createLICMPass());
517
518 // Remove redundancies.
519 LTOPasses.add(llvm::createGVNPass());
520
521 // Remove dead memcpys.
522 LTOPasses.add(llvm::createMemCpyOptPass());
523
524 // Nuke dead stores.
525 LTOPasses.add(llvm::createDeadStoreEliminationPass());
526
527 // Cleanup and simplify the code after the scalar optimizations.
528 LTOPasses.add(llvm::createInstructionCombiningPass());
529
530 LTOPasses.add(llvm::createJumpThreadingPass());
531
532 // Delete basic blocks, which optimization passes may have killed.
533 LTOPasses.add(llvm::createCFGSimplificationPass());
534
535 // Now that we have optimized the program, discard unreachable functions.
536 LTOPasses.add(llvm::createGlobalDCEPass());
537
538 LTOPasses.run(*mModule);
539 }
540
541 // Create code-gen pass to run the code emitter
542 CodeGenPasses = new llvm::FunctionPassManager(mModule);
543 CodeGenPasses->add(TD); // Will take the ownership of TD
544
545 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
546 *mCodeEmitter,
547 CodeGenOptLevel)) {
548 setError("The machine code emission is not supported by BCC on target '"
549 + Triple + "'");
550 goto on_bcc_compile_error;
551 }
552
553 // Run the pass (the code emitter) on every non-declaration function in the
554 // module
555 CodeGenPasses->doInitialization();
556 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
557 I != E; I++) {
558 if (!I->isDeclaration()) {
559 CodeGenPasses->run(*I);
560 }
561 }
562
563 CodeGenPasses->doFinalization();
564
565 // Copy the global address mapping from code emitter and remapping
566 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800567 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
568
Logan1f028c02010-11-27 01:02:48 +0800569 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
570 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
571 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
572 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
573 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
574 llvm::StringRef ExportVarName =
575 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
576
577 CodeEmitter::global_addresses_const_iterator I, E;
578 for (I = mCodeEmitter->global_address_begin(),
579 E = mCodeEmitter->global_address_end();
580 I != E; I++) {
581 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
582 continue;
583 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800584 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800585 break;
586 }
587 }
588 if (I != mCodeEmitter->global_address_end())
589 continue; // found
590 }
591 }
592 // if reaching here, we know the global variable record in metadata is
593 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800594 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800595 }
Logan2a6dc822011-01-06 04:05:20 +0800596
597 assert((varList.size() == ExportVarMetadata->getNumOperands()) &&
Logan1f028c02010-11-27 01:02:48 +0800598 "Number of slots doesn't match the number of export variables!");
599 }
600
601 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800602 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
603
Logan1f028c02010-11-27 01:02:48 +0800604 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
605 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
606 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
607 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
608 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
609 llvm::StringRef ExportFuncName =
610 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800611 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800612 }
613 }
614 }
615 }
616
617 // Tell code emitter now can release the memory using during the JIT since
618 // we have done the code emission
619 mCodeEmitter->releaseUnnecessary();
620
621 // Finally, read pragma information from the metadata node of the @Module if
622 // any.
Logan2a6dc822011-01-06 04:05:20 +0800623 if (PragmaMetadata) {
624 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
625
Logan1f028c02010-11-27 01:02:48 +0800626 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
627 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
628 if (Pragma != NULL &&
629 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
630 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
631 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
632
633 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
634 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
635 llvm::StringRef PragmaName =
636 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
637 llvm::StringRef PragmaValue =
638 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
639
Logan2a6dc822011-01-06 04:05:20 +0800640 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800641 std::make_pair(std::string(PragmaName.data(),
642 PragmaName.size()),
643 std::string(PragmaValue.data(),
644 PragmaValue.size())));
645 }
646 }
647 }
Logan2a6dc822011-01-06 04:05:20 +0800648 }
Logan1f028c02010-11-27 01:02:48 +0800649
650on_bcc_compile_error:
651 // LOGE("on_bcc_compiler_error");
652 if (CodeGenPasses) {
653 delete CodeGenPasses;
654 } else if (TD) {
655 delete TD;
656 }
657 if (TM)
658 delete TM;
659
660 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800661 return 0;
Logan1f028c02010-11-27 01:02:48 +0800662 }
663
664 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800665 return 1;
Logan1f028c02010-11-27 01:02:48 +0800666}
667
668
Logan1f028c02010-11-27 01:02:48 +0800669Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800670 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800671 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800672
673 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800674}
675
Logan1f028c02010-11-27 01:02:48 +0800676} // namespace bcc