blob: 3e075db689561fba0f870717e279dec6efbe1f92 [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//
Logan1f028c02010-11-27 01:02:48 +0800286int Compiler::readBC(const char *bitcode,
287 size_t bitcodeSize,
Shih-wei Liao25e7da42011-01-07 23:55:33 -0800288 const BCCchar *resName /* Deprecated */,
289 const BCCchar *cacheDir /* Deprecated */) {
Logan1f028c02010-11-27 01:02:48 +0800290 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
291
292 if (bitcode == NULL || bitcodeSize <= 0)
293 return 0;
294
295 // Package input to object MemoryBuffer
296 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
297 llvm::StringRef(bitcode, bitcodeSize)));
298
299 if (MEM.get() == NULL) {
300 setError("Error reading input program bitcode into memory");
301 return hasError();
302 }
303
304 // Read the input Bitcode as a Module
305 mModule = llvm::ParseBitcodeFile(MEM.get(), *mContext, &mError);
306 MEM.reset();
307 return hasError();
308}
309
310
311int Compiler::linkBC(const char *bitcode, size_t bitcodeSize) {
312 llvm::OwningPtr<llvm::MemoryBuffer> MEM;
313
314 if (bitcode == NULL || bitcodeSize <= 0)
315 return 0;
316
317 if (mModule == NULL) {
318 setError("No module presents for linking");
319 return hasError();
320 }
321
322 MEM.reset(llvm::MemoryBuffer::getMemBuffer(
323 llvm::StringRef(bitcode, bitcodeSize)));
324
325 if (MEM.get() == NULL) {
326 setError("Error reading input library bitcode into memory");
327 return hasError();
328 }
329
330 llvm::OwningPtr<llvm::Module> Lib(llvm::ParseBitcodeFile(MEM.get(),
331 *mContext,
332 &mError));
333 if (Lib.get() == NULL)
334 return hasError();
335
336 if (llvm::Linker::LinkModules(mModule, Lib.take(), &mError))
337 return hasError();
338
339 // Everything for linking should be settled down here with no error occurs
340 mHasLinked = true;
341 return hasError();
342}
343
344
Logan1f028c02010-11-27 01:02:48 +0800345int Compiler::compile() {
346 llvm::TargetData *TD = NULL;
347
348 llvm::TargetMachine *TM = NULL;
349 const llvm::Target *Target;
350 std::string FeaturesStr;
351
352 llvm::FunctionPassManager *CodeGenPasses = NULL;
353
354 const llvm::NamedMDNode *PragmaMetadata;
355 const llvm::NamedMDNode *ExportVarMetadata;
356 const llvm::NamedMDNode *ExportFuncMetadata;
357
358 if (mModule == NULL) // No module was loaded
359 return 0;
360
361 // Create TargetMachine
362 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
363 if (hasError())
364 goto on_bcc_compile_error;
365
366 if (!CPU.empty() || !Features.empty()) {
367 llvm::SubtargetFeatures F;
368 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800369
370 for (std::vector<std::string>::const_iterator
371 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800372 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800373 }
374
Logan1f028c02010-11-27 01:02:48 +0800375 FeaturesStr = F.getString();
376 }
377
378 TM = Target->createTargetMachine(Triple, FeaturesStr);
379 if (TM == NULL) {
380 setError("Failed to create target machine implementation for the"
381 " specified triple '" + Triple + "'");
382 goto on_bcc_compile_error;
383 }
384
385 // Create memory manager for creation of code emitter later.
386 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
387 setError("Failed to startup memory management for further compilation");
388 goto on_bcc_compile_error;
389 }
Logan02286cb2011-01-07 00:30:47 +0800390
391 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800392
393 // Create code emitter
394 if (!mCodeEmitter.get()) {
395 if (!createCodeEmitter()) {
396 setError("Failed to create machine code emitter to complete"
397 " the compilation");
398 goto on_bcc_compile_error;
399 }
400 } else {
401 // Reuse the code emitter
402 mCodeEmitter->reset();
403 }
404
405 mCodeEmitter->setTargetMachine(*TM);
406 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
407 mpSymbolLookupContext);
408
409 // Get target data from Module
410 TD = new llvm::TargetData(mModule);
411
412 // Load named metadata
413 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
414 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
415 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
416
417 // Create LTO passes and run them on the mModule
418 if (mHasLinked) {
419 llvm::TimePassesIsEnabled = true; // TODO(all)
420 llvm::PassManager LTOPasses;
421 LTOPasses.add(new llvm::TargetData(*TD));
422
423 std::vector<const char*> ExportSymbols;
424
425 // A workaround for getting export variable and function name. Will refine
426 // it soon.
427 if (ExportVarMetadata) {
428 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
429 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
430 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
431 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
432 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
433 llvm::StringRef ExportVarName =
434 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
435 ExportSymbols.push_back(ExportVarName.data());
436 }
437 }
438 }
439 }
440
441 if (ExportFuncMetadata) {
442 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
443 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
444 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
445 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
446 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
447 llvm::StringRef ExportFuncName =
448 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
449 ExportSymbols.push_back(ExportFuncName.data());
450 }
451 }
452 }
453 }
454 // root() and init() are born to be exported
455 ExportSymbols.push_back("root");
456 ExportSymbols.push_back("init");
457
458 // We now create passes list performing LTO. These are copied from
459 // (including comments) llvm::createStandardLTOPasses().
460
461 // Internalize all other symbols not listed in ExportSymbols
462 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
463
464 // Propagate constants at call sites into the functions they call. This
465 // opens opportunities for globalopt (and inlining) by substituting
466 // function pointers passed as arguments to direct uses of functions.
467 LTOPasses.add(llvm::createIPSCCPPass());
468
469 // Now that we internalized some globals, see if we can hack on them!
470 LTOPasses.add(llvm::createGlobalOptimizerPass());
471
472 // Linking modules together can lead to duplicated global constants, only
473 // keep one copy of each constant...
474 LTOPasses.add(llvm::createConstantMergePass());
475
476 // Remove unused arguments from functions...
477 LTOPasses.add(llvm::createDeadArgEliminationPass());
478
479 // Reduce the code after globalopt and ipsccp. Both can open up
480 // significant simplification opportunities, and both can propagate
481 // functions through function pointers. When this happens, we often have
482 // to resolve varargs calls, etc, so let instcombine do this.
483 LTOPasses.add(llvm::createInstructionCombiningPass());
484
485 // Inline small functions
486 LTOPasses.add(llvm::createFunctionInliningPass());
487
488 // Remove dead EH info.
489 LTOPasses.add(llvm::createPruneEHPass());
490
491 // Internalize the globals again after inlining
492 LTOPasses.add(llvm::createGlobalOptimizerPass());
493
494 // Remove dead functions.
495 LTOPasses.add(llvm::createGlobalDCEPass());
496
497 // If we didn't decide to inline a function, check to see if we can
498 // transform it to pass arguments by value instead of by reference.
499 LTOPasses.add(llvm::createArgumentPromotionPass());
500
501 // The IPO passes may leave cruft around. Clean up after them.
502 LTOPasses.add(llvm::createInstructionCombiningPass());
503 LTOPasses.add(llvm::createJumpThreadingPass());
504
505 // Break up allocas
506 LTOPasses.add(llvm::createScalarReplAggregatesPass());
507
508 // Run a few AA driven optimizations here and now, to cleanup the code.
509 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
510 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
511
512 // Hoist loop invariants.
513 LTOPasses.add(llvm::createLICMPass());
514
515 // Remove redundancies.
516 LTOPasses.add(llvm::createGVNPass());
517
518 // Remove dead memcpys.
519 LTOPasses.add(llvm::createMemCpyOptPass());
520
521 // Nuke dead stores.
522 LTOPasses.add(llvm::createDeadStoreEliminationPass());
523
524 // Cleanup and simplify the code after the scalar optimizations.
525 LTOPasses.add(llvm::createInstructionCombiningPass());
526
527 LTOPasses.add(llvm::createJumpThreadingPass());
528
529 // Delete basic blocks, which optimization passes may have killed.
530 LTOPasses.add(llvm::createCFGSimplificationPass());
531
532 // Now that we have optimized the program, discard unreachable functions.
533 LTOPasses.add(llvm::createGlobalDCEPass());
534
535 LTOPasses.run(*mModule);
536 }
537
538 // Create code-gen pass to run the code emitter
539 CodeGenPasses = new llvm::FunctionPassManager(mModule);
540 CodeGenPasses->add(TD); // Will take the ownership of TD
541
542 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
543 *mCodeEmitter,
544 CodeGenOptLevel)) {
545 setError("The machine code emission is not supported by BCC on target '"
546 + Triple + "'");
547 goto on_bcc_compile_error;
548 }
549
550 // Run the pass (the code emitter) on every non-declaration function in the
551 // module
552 CodeGenPasses->doInitialization();
553 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
554 I != E; I++) {
555 if (!I->isDeclaration()) {
556 CodeGenPasses->run(*I);
557 }
558 }
559
560 CodeGenPasses->doFinalization();
561
562 // 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
594 assert((varList.size() == ExportVarMetadata->getNumOperands()) &&
Logan1f028c02010-11-27 01:02:48 +0800595 "Number of slots doesn't match the number of export variables!");
596 }
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
647on_bcc_compile_error:
648 // LOGE("on_bcc_compiler_error");
649 if (CodeGenPasses) {
650 delete CodeGenPasses;
651 } else if (TD) {
652 delete TD;
653 }
654 if (TM)
655 delete TM;
656
657 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800658 return 0;
Logan1f028c02010-11-27 01:02:48 +0800659 }
660
661 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800662 return 1;
Logan1f028c02010-11-27 01:02:48 +0800663}
664
665
Logan1f028c02010-11-27 01:02:48 +0800666Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800667 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800668 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800669
670 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800671}
672
Logan1f028c02010-11-27 01:02:48 +0800673} // namespace bcc