blob: 2fafa3d24da3dfe924b31f3ee1cbd045c7568ca4 [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 Liao898c5a92011-05-18 07:02:39 -0700247int Compiler::getFilePath(char *filePath) {
248 char outStr[256];
249 char *replaceStr;
250
251 strcpy(outStr, mResName);
252 LOGE("outStr = %s\n", outStr);
253
254 // For example, if mResName is "com.android.balls:raw/balls",
255 // filePath will be "/data/data/com.android.balls/ELF_balls.o".
256 //
257 replaceStr = strstr(outStr, ":raw/");
258 if (replaceStr) {
259 strncpy(replaceStr, "_ELF_", 5);
260 } else {
261 LOGE("Ill formatted resource name\n");
262 return 1;
263 }
264
265 strcpy(filePath, "/data/local/tmp/");
266 strcat(filePath, outStr);
267 strcat(filePath, ".o");
268
269 return 0;
270}
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
311 char ObjectPath[512];
312 if (getFilePath(ObjectPath)) {
313 LOGE("Fail to create ObjectPath");
314 return 1;
315 }
316
317 int Fd = -1;
318 Fd = open(ObjectPath, O_CREAT | O_RDWR | O_TRUNC);
319 // S_IRUSR , S_IWUSR , S_IRGRP , S_IROTH /* 0644 */);
320
321 if (Fd < 0) {
322 LOGE("Fail to open file '%s'", ObjectPath);
323 return 1;
324 }
325
326 llvm::raw_fd_ostream OutFdOS(Fd, /* shouldClose= */ false);
327 OutFdOS.seek(0);
328 llvm::formatted_raw_ostream OutFOS(OutFdOS);
329#endif
Logan1f028c02010-11-27 01:02:48 +0800330
331 const llvm::NamedMDNode *PragmaMetadata;
332 const llvm::NamedMDNode *ExportVarMetadata;
333 const llvm::NamedMDNode *ExportFuncMetadata;
Stephen Hines071288a2011-01-27 14:38:26 -0800334 const llvm::NamedMDNode *ObjectSlotMetadata;
Logan1f028c02010-11-27 01:02:48 +0800335
336 if (mModule == NULL) // No module was loaded
337 return 0;
338
339 // Create TargetMachine
340 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
341 if (hasError())
342 goto on_bcc_compile_error;
343
344 if (!CPU.empty() || !Features.empty()) {
345 llvm::SubtargetFeatures F;
346 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800347
348 for (std::vector<std::string>::const_iterator
349 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800350 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800351 }
352
Logan1f028c02010-11-27 01:02:48 +0800353 FeaturesStr = F.getString();
354 }
355
356 TM = Target->createTargetMachine(Triple, FeaturesStr);
357 if (TM == NULL) {
358 setError("Failed to create target machine implementation for the"
359 " specified triple '" + Triple + "'");
360 goto on_bcc_compile_error;
361 }
362
363 // Create memory manager for creation of code emitter later.
364 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
365 setError("Failed to startup memory management for further compilation");
366 goto on_bcc_compile_error;
367 }
Logan02286cb2011-01-07 00:30:47 +0800368
369 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800370
371 // Create code emitter
372 if (!mCodeEmitter.get()) {
373 if (!createCodeEmitter()) {
374 setError("Failed to create machine code emitter to complete"
375 " the compilation");
376 goto on_bcc_compile_error;
377 }
378 } else {
379 // Reuse the code emitter
380 mCodeEmitter->reset();
381 }
382
383 mCodeEmitter->setTargetMachine(*TM);
384 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
385 mpSymbolLookupContext);
386
387 // Get target data from Module
388 TD = new llvm::TargetData(mModule);
389
390 // Load named metadata
391 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
392 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
393 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
Stephen Hines071288a2011-01-27 14:38:26 -0800394 ObjectSlotMetadata = mModule->getNamedMetadata(ObjectSlotMetadataName);
Logan1f028c02010-11-27 01:02:48 +0800395
Shih-wei Liao644fcf22011-01-16 21:56:26 -0800396#if 0
397 mHasLinked = false;
398#endif
399
Logan1f028c02010-11-27 01:02:48 +0800400 // Create LTO passes and run them on the mModule
401 if (mHasLinked) {
402 llvm::TimePassesIsEnabled = true; // TODO(all)
403 llvm::PassManager LTOPasses;
404 LTOPasses.add(new llvm::TargetData(*TD));
405
406 std::vector<const char*> ExportSymbols;
407
408 // A workaround for getting export variable and function name. Will refine
409 // it soon.
410 if (ExportVarMetadata) {
411 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
412 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
413 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
414 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
415 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
416 llvm::StringRef ExportVarName =
417 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
418 ExportSymbols.push_back(ExportVarName.data());
419 }
420 }
421 }
422 }
423
424 if (ExportFuncMetadata) {
425 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
426 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
427 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
428 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
429 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
430 llvm::StringRef ExportFuncName =
431 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
432 ExportSymbols.push_back(ExportFuncName.data());
433 }
434 }
435 }
436 }
437 // root() and init() are born to be exported
438 ExportSymbols.push_back("root");
439 ExportSymbols.push_back("init");
440
441 // We now create passes list performing LTO. These are copied from
442 // (including comments) llvm::createStandardLTOPasses().
443
444 // Internalize all other symbols not listed in ExportSymbols
445 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
446
447 // Propagate constants at call sites into the functions they call. This
448 // opens opportunities for globalopt (and inlining) by substituting
449 // function pointers passed as arguments to direct uses of functions.
450 LTOPasses.add(llvm::createIPSCCPPass());
451
452 // Now that we internalized some globals, see if we can hack on them!
453 LTOPasses.add(llvm::createGlobalOptimizerPass());
454
455 // Linking modules together can lead to duplicated global constants, only
456 // keep one copy of each constant...
457 LTOPasses.add(llvm::createConstantMergePass());
458
459 // Remove unused arguments from functions...
460 LTOPasses.add(llvm::createDeadArgEliminationPass());
461
462 // Reduce the code after globalopt and ipsccp. Both can open up
463 // significant simplification opportunities, and both can propagate
464 // functions through function pointers. When this happens, we often have
465 // to resolve varargs calls, etc, so let instcombine do this.
466 LTOPasses.add(llvm::createInstructionCombiningPass());
467
468 // Inline small functions
469 LTOPasses.add(llvm::createFunctionInliningPass());
470
471 // Remove dead EH info.
472 LTOPasses.add(llvm::createPruneEHPass());
473
474 // Internalize the globals again after inlining
475 LTOPasses.add(llvm::createGlobalOptimizerPass());
476
477 // Remove dead functions.
478 LTOPasses.add(llvm::createGlobalDCEPass());
479
480 // If we didn't decide to inline a function, check to see if we can
481 // transform it to pass arguments by value instead of by reference.
482 LTOPasses.add(llvm::createArgumentPromotionPass());
483
484 // The IPO passes may leave cruft around. Clean up after them.
485 LTOPasses.add(llvm::createInstructionCombiningPass());
486 LTOPasses.add(llvm::createJumpThreadingPass());
487
488 // Break up allocas
489 LTOPasses.add(llvm::createScalarReplAggregatesPass());
490
491 // Run a few AA driven optimizations here and now, to cleanup the code.
492 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
493 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
494
495 // Hoist loop invariants.
496 LTOPasses.add(llvm::createLICMPass());
497
498 // Remove redundancies.
499 LTOPasses.add(llvm::createGVNPass());
500
501 // Remove dead memcpys.
502 LTOPasses.add(llvm::createMemCpyOptPass());
503
504 // Nuke dead stores.
505 LTOPasses.add(llvm::createDeadStoreEliminationPass());
506
507 // Cleanup and simplify the code after the scalar optimizations.
508 LTOPasses.add(llvm::createInstructionCombiningPass());
509
510 LTOPasses.add(llvm::createJumpThreadingPass());
511
512 // Delete basic blocks, which optimization passes may have killed.
513 LTOPasses.add(llvm::createCFGSimplificationPass());
514
515 // Now that we have optimized the program, discard unreachable functions.
516 LTOPasses.add(llvm::createGlobalDCEPass());
517
518 LTOPasses.run(*mModule);
519 }
520
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700521#if CLASSIC_JIT
Logan1f028c02010-11-27 01:02:48 +0800522 // Create code-gen pass to run the code emitter
523 CodeGenPasses = new llvm::FunctionPassManager(mModule);
524 CodeGenPasses->add(TD); // Will take the ownership of TD
525
526 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
527 *mCodeEmitter,
528 CodeGenOptLevel)) {
529 setError("The machine code emission is not supported by BCC on target '"
530 + Triple + "'");
531 goto on_bcc_compile_error;
532 }
533
534 // Run the pass (the code emitter) on every non-declaration function in the
535 // module
536 CodeGenPasses->doInitialization();
537 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
538 I != E; I++) {
539 if (!I->isDeclaration()) {
540 CodeGenPasses->run(*I);
541 }
542 }
543
544 CodeGenPasses->doFinalization();
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700545#endif
Logan1f028c02010-11-27 01:02:48 +0800546
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700547#if MC_ASSEMBLER
548 TM->setMCRelaxAll(RelaxAll);
549
550 MCCodeGenPasses.add(new llvm::TargetData(*TD));
551
552 if (TM->addPassesToEmitFile(MCCodeGenPasses, OutFOS,
553 llvm::TargetMachine::CGFT_ObjectFile,
554 CodeGenOptLevel)) {
555 setError("Fail to add passes to emit file");
556 goto on_bcc_compile_error;
557 }
558
559 MCCodeGenPasses.run(*mModule);
560#endif
Logan1f028c02010-11-27 01:02:48 +0800561 // Copy the global address mapping from code emitter and remapping
562 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800563 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
564
Logan1f028c02010-11-27 01:02:48 +0800565 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
566 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
567 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
568 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
569 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
570 llvm::StringRef ExportVarName =
571 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
572
573 CodeEmitter::global_addresses_const_iterator I, E;
574 for (I = mCodeEmitter->global_address_begin(),
575 E = mCodeEmitter->global_address_end();
576 I != E; I++) {
577 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
578 continue;
579 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800580 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800581 break;
582 }
583 }
584 if (I != mCodeEmitter->global_address_end())
585 continue; // found
586 }
587 }
588 // if reaching here, we know the global variable record in metadata is
589 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800590 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800591 }
Logan2a6dc822011-01-06 04:05:20 +0800592
Stephen Hinesbbcef8a2011-05-04 19:40:10 -0700593 bccAssert((varList.size() == ExportVarMetadata->getNumOperands()) &&
594 "Number of slots doesn't match the number of export variables!");
Logan1f028c02010-11-27 01:02:48 +0800595 }
596
597 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800598 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
599
Logan1f028c02010-11-27 01:02:48 +0800600 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
601 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
602 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
603 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
604 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
605 llvm::StringRef ExportFuncName =
606 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800607 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800608 }
609 }
610 }
611 }
612
613 // Tell code emitter now can release the memory using during the JIT since
614 // we have done the code emission
615 mCodeEmitter->releaseUnnecessary();
616
617 // Finally, read pragma information from the metadata node of the @Module if
618 // any.
Logan2a6dc822011-01-06 04:05:20 +0800619 if (PragmaMetadata) {
620 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
621
Logan1f028c02010-11-27 01:02:48 +0800622 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
623 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
624 if (Pragma != NULL &&
625 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
626 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
627 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
628
629 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
630 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
631 llvm::StringRef PragmaName =
632 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
633 llvm::StringRef PragmaValue =
634 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
635
Logan2a6dc822011-01-06 04:05:20 +0800636 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800637 std::make_pair(std::string(PragmaName.data(),
638 PragmaName.size()),
639 std::string(PragmaValue.data(),
640 PragmaValue.size())));
641 }
642 }
643 }
Logan2a6dc822011-01-06 04:05:20 +0800644 }
Logan1f028c02010-11-27 01:02:48 +0800645
Stephen Hines071288a2011-01-27 14:38:26 -0800646 if (ObjectSlotMetadata) {
647 ScriptCompiled::ObjectSlotList &objectSlotList = mpResult->mObjectSlots;
648
649 for (int i = 0, e = ObjectSlotMetadata->getNumOperands(); i != e; i++) {
650 llvm::MDNode *ObjectSlot = ObjectSlotMetadata->getOperand(i);
651 if (ObjectSlot != NULL &&
652 ObjectSlot->getNumOperands() == 1) {
653 llvm::Value *SlotMDS = ObjectSlot->getOperand(0);
654 if (SlotMDS->getValueID() == llvm::Value::MDStringVal) {
655 llvm::StringRef Slot =
656 static_cast<llvm::MDString*>(SlotMDS)->getString();
657 uint32_t USlot = 0;
658 if (Slot.getAsInteger(10, USlot)) {
659 setError("Non-integer object slot value '" + Slot.str() + "'");
660 goto on_bcc_compile_error;
661 }
662 objectSlotList.push_back(USlot);
663 }
664 }
665 }
666 }
667
Logan1f028c02010-11-27 01:02:48 +0800668on_bcc_compile_error:
669 // LOGE("on_bcc_compiler_error");
670 if (CodeGenPasses) {
671 delete CodeGenPasses;
672 } else if (TD) {
673 delete TD;
674 }
675 if (TM)
676 delete TM;
677
678 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800679 return 0;
Logan1f028c02010-11-27 01:02:48 +0800680 }
681
682 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800683 return 1;
Logan1f028c02010-11-27 01:02:48 +0800684}
685
686
Logan1f028c02010-11-27 01:02:48 +0800687Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800688 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800689 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800690
691 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800692}
693
Logan1f028c02010-11-27 01:02:48 +0800694} // namespace bcc