blob: 274f20b232473ea7d4d1ccfcc673232f880f2015 [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
Loganc4395232010-11-27 18:54:17 +080020#include "Compiler.h"
Logan1f028c02010-11-27 01:02:48 +080021
Logan35849002011-01-15 07:30:43 +080022#include "Config.h"
23
Loganeb3d12b2010-12-16 06:20:18 +080024#include "ContextManager.h"
Logan2a6dc822011-01-06 04:05:20 +080025#include "ScriptCompiled.h"
Logan75cc8a52011-01-07 06:06:52 +080026#include "Sha1Helper.h"
Loganeb3d12b2010-12-16 06:20:18 +080027
Logandf23afa2010-11-27 11:04:54 +080028#include "llvm/ADT/StringRef.h"
Logan1f028c02010-11-27 01:02:48 +080029
Logandf23afa2010-11-27 11:04:54 +080030#include "llvm/Analysis/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080031
Logan1f028c02010-11-27 01:02:48 +080032#include "llvm/Bitcode/ReaderWriter.h"
33
Logan1f028c02010-11-27 01:02:48 +080034#include "llvm/CodeGen/Passes.h"
Logan1f028c02010-11-27 01:02:48 +080035#include "llvm/CodeGen/RegAllocRegistry.h"
36#include "llvm/CodeGen/SchedulerRegistry.h"
Logan1f028c02010-11-27 01:02:48 +080037
Logandf23afa2010-11-27 11:04:54 +080038#include "llvm/Transforms/IPO.h"
39#include "llvm/Transforms/Scalar.h"
40
41#include "llvm/Target/SubtargetFeature.h"
42#include "llvm/Target/TargetData.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetOptions.h"
45#include "llvm/Target/TargetRegistry.h"
46#include "llvm/Target/TargetSelect.h"
47
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MemoryBuffer.h"
50
51#include "llvm/GlobalValue.h"
52#include "llvm/Linker.h"
53#include "llvm/LLVMContext.h"
54#include "llvm/Metadata.h"
55#include "llvm/Module.h"
56#include "llvm/PassManager.h"
57#include "llvm/Value.h"
58
59#include <errno.h>
60#include <sys/file.h>
Logandf23afa2010-11-27 11:04:54 +080061#include <sys/stat.h>
62#include <sys/types.h>
63#include <unistd.h>
64
Logan75cc8a52011-01-07 06:06:52 +080065#include <string.h>
Logan8b77a772010-12-21 09:11:01 +080066
Logandf23afa2010-11-27 11:04:54 +080067#include <string>
68#include <vector>
Logan1f028c02010-11-27 01:02:48 +080069
Logan1f028c02010-11-27 01:02:48 +080070namespace bcc {
71
72//////////////////////////////////////////////////////////////////////////////
73// BCC Compiler Static Variables
74//////////////////////////////////////////////////////////////////////////////
75
76bool Compiler::GlobalInitialized = false;
77
Logan1f028c02010-11-27 01:02:48 +080078// Code generation optimization level for the compiler
79llvm::CodeGenOpt::Level Compiler::CodeGenOptLevel;
80
81std::string Compiler::Triple;
82
83std::string Compiler::CPU;
84
85std::vector<std::string> Compiler::Features;
86
87// The named of metadata node that pragma resides (should be synced with
88// slang.cpp)
89const llvm::StringRef Compiler::PragmaMetadataName = "#pragma";
90
91// The named of metadata node that export variable name resides (should be
92// synced with slang_rs_metadata.h)
93const llvm::StringRef Compiler::ExportVarMetadataName = "#rs_export_var";
94
95// The named of metadata node that export function name resides (should be
96// synced with slang_rs_metadata.h)
97const llvm::StringRef Compiler::ExportFuncMetadataName = "#rs_export_func";
98
99
100//////////////////////////////////////////////////////////////////////////////
101// Compiler
102//////////////////////////////////////////////////////////////////////////////
103
104void Compiler::GlobalInitialization() {
105 if (GlobalInitialized)
106 return;
107
Logane1323992011-01-12 04:47:13 +0800108 LOGI("LIBBCC BUILD: %s\n", libbcc_build_time);
Logan87066272010-12-29 00:34:32 +0800109
Logan1f028c02010-11-27 01:02:48 +0800110 // if (!llvm::llvm_is_multithreaded())
111 // llvm::llvm_start_multithreaded();
112
113 // Set Triple, CPU and Features here
114 Triple = TARGET_TRIPLE_STRING;
115
116 // TODO(sliao): NEON for JIT
117 // Features.push_back("+neon");
118 // Features.push_back("+vmlx");
119 // Features.push_back("+neonfp");
120 Features.push_back("+vfp3");
121 Features.push_back("+d16");
122
123#if defined(DEFAULT_ARM_CODEGEN) || defined(PROVIDE_ARM_CODEGEN)
124 LLVMInitializeARMTargetInfo();
125 LLVMInitializeARMTarget();
Logan35849002011-01-15 07:30:43 +0800126#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800127 LLVMInitializeARMDisassembler();
128 LLVMInitializeARMAsmPrinter();
129#endif
130#endif
131
132#if defined(DEFAULT_X86_CODEGEN) || defined(PROVIDE_X86_CODEGEN)
133 LLVMInitializeX86TargetInfo();
134 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800135#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800136 LLVMInitializeX86Disassembler();
137 LLVMInitializeX86AsmPrinter();
138#endif
139#endif
140
141#if defined(DEFAULT_X64_CODEGEN) || defined(PROVIDE_X64_CODEGEN)
142 LLVMInitializeX86TargetInfo();
143 LLVMInitializeX86Target();
Logan35849002011-01-15 07:30:43 +0800144#if USE_DISASSEMBLER
Logan1f028c02010-11-27 01:02:48 +0800145 LLVMInitializeX86Disassembler();
146 LLVMInitializeX86AsmPrinter();
147#endif
148#endif
149
150 // -O0: llvm::CodeGenOpt::None
151 // -O1: llvm::CodeGenOpt::Less
152 // -O2: llvm::CodeGenOpt::Default
153 // -O3: llvm::CodeGenOpt::Aggressive
Shih-wei Liao72f67a62010-12-14 13:36:15 -0800154 CodeGenOptLevel = llvm::CodeGenOpt::Aggressive;
Logan1f028c02010-11-27 01:02:48 +0800155
156 // Below are the global settings to LLVM
157
158 // Disable frame pointer elimination optimization
159 llvm::NoFramePointerElim = false;
160
161 // Use hardfloat ABI
162 //
163 // TODO(all): Need to detect the CPU capability and decide whether to use
164 // softfp. To use softfp, change following 2 lines to
165 //
166 // llvm::FloatABIType = llvm::FloatABI::Soft;
167 // llvm::UseSoftFloat = true;
168 //
Shih-wei Liaoe728cb82010-12-15 15:20:47 -0800169 llvm::FloatABIType = llvm::FloatABI::Soft;
Logan1f028c02010-11-27 01:02:48 +0800170 llvm::UseSoftFloat = false;
171
172 // BCC needs all unknown symbols resolved at JIT/compilation time.
173 // So we don't need any dynamic relocation model.
174 llvm::TargetMachine::setRelocationModel(llvm::Reloc::Static);
175
176#if defined(DEFAULT_X64_CODEGEN)
177 // Data address in X86_64 architecture may reside in a far-away place
178 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Medium);
179#else
180 // This is set for the linker (specify how large of the virtual addresses
181 // we can access for all unknown symbols.)
182 llvm::TargetMachine::setCodeModel(llvm::CodeModel::Small);
183#endif
184
185 // Register the scheduler
186 llvm::RegisterScheduler::setDefault(llvm::createDefaultScheduler);
187
188 // Register allocation policy:
189 // createFastRegisterAllocator: fast but bad quality
190 // createLinearScanRegisterAllocator: not so fast but good quality
191 llvm::RegisterRegAlloc::setDefault
192 ((CodeGenOptLevel == llvm::CodeGenOpt::None) ?
193 llvm::createFastRegisterAllocator :
194 llvm::createLinearScanRegisterAllocator);
195
Logan35849002011-01-15 07:30:43 +0800196#if USE_CACHE
Logan75cc8a52011-01-07 06:06:52 +0800197 // Calculate the SHA1 checksum of libbcc and libRS.
Logan35849002011-01-15 07:30:43 +0800198#if USE_LIBBCC_SHA1SUM
Logan75cc8a52011-01-07 06:06:52 +0800199 calcFileSHA1(sha1LibBCC, pathLibBCC);
Logane1323992011-01-12 04:47:13 +0800200#endif
Logan75cc8a52011-01-07 06:06:52 +0800201 calcFileSHA1(sha1LibRS, pathLibRS);
Logan35849002011-01-15 07:30:43 +0800202#endif
Logan75cc8a52011-01-07 06:06:52 +0800203
Logan1f028c02010-11-27 01:02:48 +0800204 GlobalInitialized = true;
205}
206
207
208void Compiler::LLVMErrorHandler(void *UserData, const std::string &Message) {
209 std::string *Error = static_cast<std::string*>(UserData);
210 Error->assign(Message);
211 LOGE("%s", Message.c_str());
212 exit(1);
213}
214
215
216CodeMemoryManager *Compiler::createCodeMemoryManager() {
217 mCodeMemMgr.reset(new CodeMemoryManager());
218 return mCodeMemMgr.get();
219}
220
221
222CodeEmitter *Compiler::createCodeEmitter() {
Logan7dcaac92011-01-06 04:26:23 +0800223 mCodeEmitter.reset(new CodeEmitter(mpResult, mCodeMemMgr.get()));
Logan1f028c02010-11-27 01:02:48 +0800224 return mCodeEmitter.get();
225}
226
227
Logan2a6dc822011-01-06 04:05:20 +0800228Compiler::Compiler(ScriptCompiled *result)
229 : mpResult(result),
Logan1f028c02010-11-27 01:02:48 +0800230 mpSymbolLookupFn(NULL),
231 mpSymbolLookupContext(NULL),
232 mContext(NULL),
233 mModule(NULL),
234 mHasLinked(false) /* Turn off linker */ {
235 llvm::remove_fatal_error_handler();
236 llvm::install_fatal_error_handler(LLVMErrorHandler, &mError);
237 mContext = new llvm::LLVMContext();
238 return;
239}
240
Shih-wei Liaod1613092010-12-23 22:59:15 +0800241// Compiler::readBC
242// Parameters:
Shih-wei Liaod1613092010-12-23 22:59:15 +0800243//
Loganf340bf72011-01-14 17:51:40 +0800244int Compiler::readBC(const char *bitcode, size_t bitcodeSize) {
Logan1f028c02010-11-27 01:02:48 +0800245 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
246
247 if (bitcode == NULL || bitcodeSize <= 0)
Loganf340bf72011-01-14 17:51:40 +0800248 return 1;
Logan1f028c02010-11-27 01:02:48 +0800249
250 // Package input to object MemoryBuffer
251 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
252 llvm::StringRef(bitcode, bitcodeSize)));
253
254 if (MEM.get() == NULL) {
255 setError("Error reading input program bitcode into memory");
256 return hasError();
257 }
258
259 // Read the input Bitcode as a Module
260 mModule = llvm::ParseBitcodeFile(MEM.get(), *mContext, &mError);
261 MEM.reset();
262 return hasError();
263}
264
265
Shih-wei Liao74fbea72011-01-16 15:38:59 -0800266// bitcodeSize == 1: Link against file
267// bitcodeSize > 1: Link against buffer
Logan1f028c02010-11-27 01:02:48 +0800268int Compiler::linkBC(const char *bitcode, size_t bitcodeSize) {
269 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
270
Shih-wei Liao3ec1d0f2011-01-16 16:39:03 -0800271 if (bitcodeSize == 1) { // link against file
Shih-wei Liao74fbea72011-01-16 15:38:59 -0800272 } else if (bitcode == NULL || bitcodeSize <= 0) {
Loganf340bf72011-01-14 17:51:40 +0800273 LOGE("Invalid bitcode for linkBC\n");
Shih-wei Liao4ed0ce02011-01-13 01:46:38 -0800274 return 1;
275 }
Logan1f028c02010-11-27 01:02:48 +0800276
277 if (mModule == NULL) {
278 setError("No module presents for linking");
279 return hasError();
280 }
281
Shih-wei Liao847181c2011-01-16 03:36:07 -0800282#if 1
Shih-wei Liao8b67c072011-01-13 01:51:57 -0800283 MEM.reset(llvm::MemoryBuffer::getFile("/system/lib/rslib.bc"));
Shih-wei Liao8b67c072011-01-13 01:51:57 -0800284
Shih-wei Liao847181c2011-01-16 03:36:07 -0800285#else
Logan1f028c02010-11-27 01:02:48 +0800286 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
287 llvm::StringRef(bitcode, bitcodeSize)));
Shih-wei Liao847181c2011-01-16 03:36:07 -0800288#endif
Logan1f028c02010-11-27 01:02:48 +0800289
290 if (MEM.get() == NULL) {
291 setError("Error reading input library bitcode into memory");
292 return hasError();
293 }
294
295 llvm::OwningPtr<llvm::Module> Lib(llvm::ParseBitcodeFile(MEM.get(),
296 *mContext,
297 &mError));
298 if (Lib.get() == NULL)
299 return hasError();
300
301 if (llvm::Linker::LinkModules(mModule, Lib.take(), &mError))
302 return hasError();
303
304 // Everything for linking should be settled down here with no error occurs
305 mHasLinked = true;
306 return hasError();
307}
308
309
Logan1f028c02010-11-27 01:02:48 +0800310int Compiler::compile() {
311 llvm::TargetData *TD = NULL;
312
313 llvm::TargetMachine *TM = NULL;
314 const llvm::Target *Target;
315 std::string FeaturesStr;
316
317 llvm::FunctionPassManager *CodeGenPasses = NULL;
318
319 const llvm::NamedMDNode *PragmaMetadata;
320 const llvm::NamedMDNode *ExportVarMetadata;
321 const llvm::NamedMDNode *ExportFuncMetadata;
322
323 if (mModule == NULL) // No module was loaded
324 return 0;
325
326 // Create TargetMachine
327 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
328 if (hasError())
329 goto on_bcc_compile_error;
330
331 if (!CPU.empty() || !Features.empty()) {
332 llvm::SubtargetFeatures F;
333 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800334
335 for (std::vector<std::string>::const_iterator
336 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800337 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800338 }
339
Logan1f028c02010-11-27 01:02:48 +0800340 FeaturesStr = F.getString();
341 }
342
343 TM = Target->createTargetMachine(Triple, FeaturesStr);
344 if (TM == NULL) {
345 setError("Failed to create target machine implementation for the"
346 " specified triple '" + Triple + "'");
347 goto on_bcc_compile_error;
348 }
349
350 // Create memory manager for creation of code emitter later.
351 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
352 setError("Failed to startup memory management for further compilation");
353 goto on_bcc_compile_error;
354 }
Logan02286cb2011-01-07 00:30:47 +0800355
356 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800357
358 // Create code emitter
359 if (!mCodeEmitter.get()) {
360 if (!createCodeEmitter()) {
361 setError("Failed to create machine code emitter to complete"
362 " the compilation");
363 goto on_bcc_compile_error;
364 }
365 } else {
366 // Reuse the code emitter
367 mCodeEmitter->reset();
368 }
369
370 mCodeEmitter->setTargetMachine(*TM);
371 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
372 mpSymbolLookupContext);
373
374 // Get target data from Module
375 TD = new llvm::TargetData(mModule);
376
377 // Load named metadata
378 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
379 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
380 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
381
382 // Create LTO passes and run them on the mModule
383 if (mHasLinked) {
384 llvm::TimePassesIsEnabled = true; // TODO(all)
385 llvm::PassManager LTOPasses;
386 LTOPasses.add(new llvm::TargetData(*TD));
387
388 std::vector<const char*> ExportSymbols;
389
390 // A workaround for getting export variable and function name. Will refine
391 // it soon.
392 if (ExportVarMetadata) {
393 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
394 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
395 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
396 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
397 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
398 llvm::StringRef ExportVarName =
399 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
400 ExportSymbols.push_back(ExportVarName.data());
401 }
402 }
403 }
404 }
405
406 if (ExportFuncMetadata) {
407 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
408 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
409 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
410 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
411 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
412 llvm::StringRef ExportFuncName =
413 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
414 ExportSymbols.push_back(ExportFuncName.data());
415 }
416 }
417 }
418 }
419 // root() and init() are born to be exported
420 ExportSymbols.push_back("root");
421 ExportSymbols.push_back("init");
422
423 // We now create passes list performing LTO. These are copied from
424 // (including comments) llvm::createStandardLTOPasses().
425
426 // Internalize all other symbols not listed in ExportSymbols
427 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
428
429 // Propagate constants at call sites into the functions they call. This
430 // opens opportunities for globalopt (and inlining) by substituting
431 // function pointers passed as arguments to direct uses of functions.
432 LTOPasses.add(llvm::createIPSCCPPass());
433
434 // Now that we internalized some globals, see if we can hack on them!
435 LTOPasses.add(llvm::createGlobalOptimizerPass());
436
437 // Linking modules together can lead to duplicated global constants, only
438 // keep one copy of each constant...
439 LTOPasses.add(llvm::createConstantMergePass());
440
441 // Remove unused arguments from functions...
442 LTOPasses.add(llvm::createDeadArgEliminationPass());
443
444 // Reduce the code after globalopt and ipsccp. Both can open up
445 // significant simplification opportunities, and both can propagate
446 // functions through function pointers. When this happens, we often have
447 // to resolve varargs calls, etc, so let instcombine do this.
448 LTOPasses.add(llvm::createInstructionCombiningPass());
449
450 // Inline small functions
451 LTOPasses.add(llvm::createFunctionInliningPass());
452
453 // Remove dead EH info.
454 LTOPasses.add(llvm::createPruneEHPass());
455
456 // Internalize the globals again after inlining
457 LTOPasses.add(llvm::createGlobalOptimizerPass());
458
459 // Remove dead functions.
460 LTOPasses.add(llvm::createGlobalDCEPass());
461
462 // If we didn't decide to inline a function, check to see if we can
463 // transform it to pass arguments by value instead of by reference.
464 LTOPasses.add(llvm::createArgumentPromotionPass());
465
466 // The IPO passes may leave cruft around. Clean up after them.
467 LTOPasses.add(llvm::createInstructionCombiningPass());
468 LTOPasses.add(llvm::createJumpThreadingPass());
469
470 // Break up allocas
471 LTOPasses.add(llvm::createScalarReplAggregatesPass());
472
473 // Run a few AA driven optimizations here and now, to cleanup the code.
474 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
475 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
476
477 // Hoist loop invariants.
478 LTOPasses.add(llvm::createLICMPass());
479
480 // Remove redundancies.
481 LTOPasses.add(llvm::createGVNPass());
482
483 // Remove dead memcpys.
484 LTOPasses.add(llvm::createMemCpyOptPass());
485
486 // Nuke dead stores.
487 LTOPasses.add(llvm::createDeadStoreEliminationPass());
488
489 // Cleanup and simplify the code after the scalar optimizations.
490 LTOPasses.add(llvm::createInstructionCombiningPass());
491
492 LTOPasses.add(llvm::createJumpThreadingPass());
493
494 // Delete basic blocks, which optimization passes may have killed.
495 LTOPasses.add(llvm::createCFGSimplificationPass());
496
497 // Now that we have optimized the program, discard unreachable functions.
498 LTOPasses.add(llvm::createGlobalDCEPass());
499
500 LTOPasses.run(*mModule);
501 }
502
503 // Create code-gen pass to run the code emitter
504 CodeGenPasses = new llvm::FunctionPassManager(mModule);
505 CodeGenPasses->add(TD); // Will take the ownership of TD
506
507 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
508 *mCodeEmitter,
509 CodeGenOptLevel)) {
510 setError("The machine code emission is not supported by BCC on target '"
511 + Triple + "'");
512 goto on_bcc_compile_error;
513 }
514
515 // Run the pass (the code emitter) on every non-declaration function in the
516 // module
517 CodeGenPasses->doInitialization();
518 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
519 I != E; I++) {
520 if (!I->isDeclaration()) {
521 CodeGenPasses->run(*I);
522 }
523 }
524
525 CodeGenPasses->doFinalization();
526
527 // Copy the global address mapping from code emitter and remapping
528 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800529 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
530
Logan1f028c02010-11-27 01:02:48 +0800531 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
532 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
533 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
534 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
535 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
536 llvm::StringRef ExportVarName =
537 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
538
539 CodeEmitter::global_addresses_const_iterator I, E;
540 for (I = mCodeEmitter->global_address_begin(),
541 E = mCodeEmitter->global_address_end();
542 I != E; I++) {
543 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
544 continue;
545 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800546 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800547 break;
548 }
549 }
550 if (I != mCodeEmitter->global_address_end())
551 continue; // found
552 }
553 }
554 // if reaching here, we know the global variable record in metadata is
555 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800556 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800557 }
Logan2a6dc822011-01-06 04:05:20 +0800558
559 assert((varList.size() == ExportVarMetadata->getNumOperands()) &&
Logan1f028c02010-11-27 01:02:48 +0800560 "Number of slots doesn't match the number of export variables!");
561 }
562
563 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800564 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
565
Logan1f028c02010-11-27 01:02:48 +0800566 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
567 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
568 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
569 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
570 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
571 llvm::StringRef ExportFuncName =
572 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800573 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800574 }
575 }
576 }
577 }
578
579 // Tell code emitter now can release the memory using during the JIT since
580 // we have done the code emission
581 mCodeEmitter->releaseUnnecessary();
582
583 // Finally, read pragma information from the metadata node of the @Module if
584 // any.
Logan2a6dc822011-01-06 04:05:20 +0800585 if (PragmaMetadata) {
586 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
587
Logan1f028c02010-11-27 01:02:48 +0800588 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
589 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
590 if (Pragma != NULL &&
591 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
592 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
593 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
594
595 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
596 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
597 llvm::StringRef PragmaName =
598 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
599 llvm::StringRef PragmaValue =
600 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
601
Logan2a6dc822011-01-06 04:05:20 +0800602 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800603 std::make_pair(std::string(PragmaName.data(),
604 PragmaName.size()),
605 std::string(PragmaValue.data(),
606 PragmaValue.size())));
607 }
608 }
609 }
Logan2a6dc822011-01-06 04:05:20 +0800610 }
Logan1f028c02010-11-27 01:02:48 +0800611
612on_bcc_compile_error:
613 // LOGE("on_bcc_compiler_error");
614 if (CodeGenPasses) {
615 delete CodeGenPasses;
616 } else if (TD) {
617 delete TD;
618 }
619 if (TM)
620 delete TM;
621
622 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800623 return 0;
Logan1f028c02010-11-27 01:02:48 +0800624 }
625
626 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800627 return 1;
Logan1f028c02010-11-27 01:02:48 +0800628}
629
630
Logan1f028c02010-11-27 01:02:48 +0800631Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800632 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800633 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800634
635 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800636}
637
Logan1f028c02010-11-27 01:02:48 +0800638} // namespace bcc