blob: 461f48828ada56107655bdab5c5e038012447b7b [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 Liaode0ba062011-05-19 03:16:33 -0700247#define TOKEN_RAW ":raw"
248#define TOKEN_RAW_LEN 4
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700249
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700250// input objPath: For example, com.example.android.rs.fountain:raw/fountain
251// output objPath: /data/data/com.example.android.rs.fountain/cache/fountain.o
252//
253bool Compiler::getObjPath(std::string &objPath) {
254 size_t found = objPath.find(TOKEN_RAW);
255 if (found == string::npos) {
256 LOGE("Ill formatted resource name '%s'. The name should contain :raw/",
257 objPath.c_str());
258 return false;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700259 }
260
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700261 objPath.replace(found, TOKEN_RAW_LEN, "/cache");
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700262
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700263 objPath.append(".o");
264 objPath.insert(0, "/data/data/");
265 LOGV("objPath = %s", objPath.c_str());
266 return true;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700267}
268
269
Logan474cbd22011-01-31 01:47:44 +0800270llvm::Module *Compiler::parseBitcodeFile(llvm::MemoryBuffer *MEM) {
271 llvm::Module *result = llvm::ParseBitcodeFile(MEM, *mContext, &mError);
Logan1f028c02010-11-27 01:02:48 +0800272
Logan474cbd22011-01-31 01:47:44 +0800273 if (!result) {
274 LOGE("Unable to ParseBitcodeFile: %s\n", mError.c_str());
275 return NULL;
Logan1f028c02010-11-27 01:02:48 +0800276 }
277
Logan474cbd22011-01-31 01:47:44 +0800278 return result;
Logan1f028c02010-11-27 01:02:48 +0800279}
280
281
Logan474cbd22011-01-31 01:47:44 +0800282int Compiler::linkModule(llvm::Module *moduleWith) {
283 if (llvm::Linker::LinkModules(mModule, moduleWith, &mError) != 0) {
Logan1f028c02010-11-27 01:02:48 +0800284 return hasError();
285 }
286
Logan1f028c02010-11-27 01:02:48 +0800287 // Everything for linking should be settled down here with no error occurs
288 mHasLinked = true;
289 return hasError();
290}
291
292
Logan1f028c02010-11-27 01:02:48 +0800293int Compiler::compile() {
294 llvm::TargetData *TD = NULL;
295
296 llvm::TargetMachine *TM = NULL;
297 const llvm::Target *Target;
298 std::string FeaturesStr;
299
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700300#if CLASSIC_JIT
Logan1f028c02010-11-27 01:02:48 +0800301 llvm::FunctionPassManager *CodeGenPasses = NULL;
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700302#endif
303
304#if MC_ASSEMBLER
305 bool RelaxAll = true;
306 llvm::PassManager MCCodeGenPasses;
307
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700308 std::string objPath(mResName);
309
310 if (!getObjPath(objPath)) {
311 LOGE("Fail to create objPath");
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700312 return 1;
313 }
314
315 int Fd = -1;
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700316 Fd = open(objPath.c_str(), O_CREAT | O_RDWR | O_TRUNC,
317 S_IRUSR , S_IWUSR , S_IRGRP , S_IROTH /* 0644 */);
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700318
319 if (Fd < 0) {
Shih-wei Liaode0ba062011-05-19 03:16:33 -0700320 LOGE("Fail to open file '%s'", objPath.c_str());
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700321 return 1;
322 }
323
324 llvm::raw_fd_ostream OutFdOS(Fd, /* shouldClose= */ false);
325 OutFdOS.seek(0);
326 llvm::formatted_raw_ostream OutFOS(OutFdOS);
327#endif
Logan1f028c02010-11-27 01:02:48 +0800328
329 const llvm::NamedMDNode *PragmaMetadata;
330 const llvm::NamedMDNode *ExportVarMetadata;
331 const llvm::NamedMDNode *ExportFuncMetadata;
Stephen Hines071288a2011-01-27 14:38:26 -0800332 const llvm::NamedMDNode *ObjectSlotMetadata;
Logan1f028c02010-11-27 01:02:48 +0800333
334 if (mModule == NULL) // No module was loaded
335 return 0;
336
337 // Create TargetMachine
338 Target = llvm::TargetRegistry::lookupTarget(Triple, mError);
339 if (hasError())
340 goto on_bcc_compile_error;
341
342 if (!CPU.empty() || !Features.empty()) {
343 llvm::SubtargetFeatures F;
344 F.setCPU(CPU);
Logana4994f52010-11-27 14:06:02 +0800345
346 for (std::vector<std::string>::const_iterator
347 I = Features.begin(), E = Features.end(); I != E; I++) {
Logan1f028c02010-11-27 01:02:48 +0800348 F.AddFeature(*I);
Logana4994f52010-11-27 14:06:02 +0800349 }
350
Logan1f028c02010-11-27 01:02:48 +0800351 FeaturesStr = F.getString();
352 }
353
354 TM = Target->createTargetMachine(Triple, FeaturesStr);
355 if (TM == NULL) {
356 setError("Failed to create target machine implementation for the"
357 " specified triple '" + Triple + "'");
358 goto on_bcc_compile_error;
359 }
360
361 // Create memory manager for creation of code emitter later.
362 if (!mCodeMemMgr.get() && !createCodeMemoryManager()) {
363 setError("Failed to startup memory management for further compilation");
364 goto on_bcc_compile_error;
365 }
Logan02286cb2011-01-07 00:30:47 +0800366
367 mpResult->mContext = (char *) (mCodeMemMgr.get()->getCodeMemBase());
Logan1f028c02010-11-27 01:02:48 +0800368
369 // Create code emitter
370 if (!mCodeEmitter.get()) {
371 if (!createCodeEmitter()) {
372 setError("Failed to create machine code emitter to complete"
373 " the compilation");
374 goto on_bcc_compile_error;
375 }
376 } else {
377 // Reuse the code emitter
378 mCodeEmitter->reset();
379 }
380
381 mCodeEmitter->setTargetMachine(*TM);
382 mCodeEmitter->registerSymbolCallback(mpSymbolLookupFn,
383 mpSymbolLookupContext);
384
385 // Get target data from Module
386 TD = new llvm::TargetData(mModule);
387
388 // Load named metadata
389 ExportVarMetadata = mModule->getNamedMetadata(ExportVarMetadataName);
390 ExportFuncMetadata = mModule->getNamedMetadata(ExportFuncMetadataName);
391 PragmaMetadata = mModule->getNamedMetadata(PragmaMetadataName);
Stephen Hines071288a2011-01-27 14:38:26 -0800392 ObjectSlotMetadata = mModule->getNamedMetadata(ObjectSlotMetadataName);
Logan1f028c02010-11-27 01:02:48 +0800393
Shih-wei Liao644fcf22011-01-16 21:56:26 -0800394#if 0
395 mHasLinked = false;
396#endif
397
Logan1f028c02010-11-27 01:02:48 +0800398 // Create LTO passes and run them on the mModule
399 if (mHasLinked) {
400 llvm::TimePassesIsEnabled = true; // TODO(all)
401 llvm::PassManager LTOPasses;
402 LTOPasses.add(new llvm::TargetData(*TD));
403
404 std::vector<const char*> ExportSymbols;
405
406 // A workaround for getting export variable and function name. Will refine
407 // it soon.
408 if (ExportVarMetadata) {
409 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
410 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
411 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
412 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
413 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
414 llvm::StringRef ExportVarName =
415 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
416 ExportSymbols.push_back(ExportVarName.data());
417 }
418 }
419 }
420 }
421
422 if (ExportFuncMetadata) {
423 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
424 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
425 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
426 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
427 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
428 llvm::StringRef ExportFuncName =
429 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
430 ExportSymbols.push_back(ExportFuncName.data());
431 }
432 }
433 }
434 }
435 // root() and init() are born to be exported
436 ExportSymbols.push_back("root");
437 ExportSymbols.push_back("init");
438
439 // We now create passes list performing LTO. These are copied from
440 // (including comments) llvm::createStandardLTOPasses().
441
442 // Internalize all other symbols not listed in ExportSymbols
443 LTOPasses.add(llvm::createInternalizePass(ExportSymbols));
444
445 // Propagate constants at call sites into the functions they call. This
446 // opens opportunities for globalopt (and inlining) by substituting
447 // function pointers passed as arguments to direct uses of functions.
448 LTOPasses.add(llvm::createIPSCCPPass());
449
450 // Now that we internalized some globals, see if we can hack on them!
451 LTOPasses.add(llvm::createGlobalOptimizerPass());
452
453 // Linking modules together can lead to duplicated global constants, only
454 // keep one copy of each constant...
455 LTOPasses.add(llvm::createConstantMergePass());
456
457 // Remove unused arguments from functions...
458 LTOPasses.add(llvm::createDeadArgEliminationPass());
459
460 // Reduce the code after globalopt and ipsccp. Both can open up
461 // significant simplification opportunities, and both can propagate
462 // functions through function pointers. When this happens, we often have
463 // to resolve varargs calls, etc, so let instcombine do this.
464 LTOPasses.add(llvm::createInstructionCombiningPass());
465
466 // Inline small functions
467 LTOPasses.add(llvm::createFunctionInliningPass());
468
469 // Remove dead EH info.
470 LTOPasses.add(llvm::createPruneEHPass());
471
472 // Internalize the globals again after inlining
473 LTOPasses.add(llvm::createGlobalOptimizerPass());
474
475 // Remove dead functions.
476 LTOPasses.add(llvm::createGlobalDCEPass());
477
478 // If we didn't decide to inline a function, check to see if we can
479 // transform it to pass arguments by value instead of by reference.
480 LTOPasses.add(llvm::createArgumentPromotionPass());
481
482 // The IPO passes may leave cruft around. Clean up after them.
483 LTOPasses.add(llvm::createInstructionCombiningPass());
484 LTOPasses.add(llvm::createJumpThreadingPass());
485
486 // Break up allocas
487 LTOPasses.add(llvm::createScalarReplAggregatesPass());
488
489 // Run a few AA driven optimizations here and now, to cleanup the code.
490 LTOPasses.add(llvm::createFunctionAttrsPass()); // Add nocapture.
491 LTOPasses.add(llvm::createGlobalsModRefPass()); // IP alias analysis.
492
493 // Hoist loop invariants.
494 LTOPasses.add(llvm::createLICMPass());
495
496 // Remove redundancies.
497 LTOPasses.add(llvm::createGVNPass());
498
499 // Remove dead memcpys.
500 LTOPasses.add(llvm::createMemCpyOptPass());
501
502 // Nuke dead stores.
503 LTOPasses.add(llvm::createDeadStoreEliminationPass());
504
505 // Cleanup and simplify the code after the scalar optimizations.
506 LTOPasses.add(llvm::createInstructionCombiningPass());
507
508 LTOPasses.add(llvm::createJumpThreadingPass());
509
510 // Delete basic blocks, which optimization passes may have killed.
511 LTOPasses.add(llvm::createCFGSimplificationPass());
512
513 // Now that we have optimized the program, discard unreachable functions.
514 LTOPasses.add(llvm::createGlobalDCEPass());
515
516 LTOPasses.run(*mModule);
517 }
518
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700519#if CLASSIC_JIT
Logan1f028c02010-11-27 01:02:48 +0800520 // Create code-gen pass to run the code emitter
521 CodeGenPasses = new llvm::FunctionPassManager(mModule);
522 CodeGenPasses->add(TD); // Will take the ownership of TD
523
524 if (TM->addPassesToEmitMachineCode(*CodeGenPasses,
525 *mCodeEmitter,
526 CodeGenOptLevel)) {
527 setError("The machine code emission is not supported by BCC on target '"
528 + Triple + "'");
529 goto on_bcc_compile_error;
530 }
531
532 // Run the pass (the code emitter) on every non-declaration function in the
533 // module
534 CodeGenPasses->doInitialization();
535 for (llvm::Module::iterator I = mModule->begin(), E = mModule->end();
536 I != E; I++) {
537 if (!I->isDeclaration()) {
538 CodeGenPasses->run(*I);
539 }
540 }
541
542 CodeGenPasses->doFinalization();
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700543#endif
Logan1f028c02010-11-27 01:02:48 +0800544
Shih-wei Liao898c5a92011-05-18 07:02:39 -0700545#if MC_ASSEMBLER
546 TM->setMCRelaxAll(RelaxAll);
547
548 MCCodeGenPasses.add(new llvm::TargetData(*TD));
549
550 if (TM->addPassesToEmitFile(MCCodeGenPasses, OutFOS,
551 llvm::TargetMachine::CGFT_ObjectFile,
552 CodeGenOptLevel)) {
553 setError("Fail to add passes to emit file");
554 goto on_bcc_compile_error;
555 }
556
557 MCCodeGenPasses.run(*mModule);
558#endif
Logan1f028c02010-11-27 01:02:48 +0800559 // Copy the global address mapping from code emitter and remapping
560 if (ExportVarMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800561 ScriptCompiled::ExportVarList &varList = mpResult->mExportVars;
562
Logan1f028c02010-11-27 01:02:48 +0800563 for (int i = 0, e = ExportVarMetadata->getNumOperands(); i != e; i++) {
564 llvm::MDNode *ExportVar = ExportVarMetadata->getOperand(i);
565 if (ExportVar != NULL && ExportVar->getNumOperands() > 1) {
566 llvm::Value *ExportVarNameMDS = ExportVar->getOperand(0);
567 if (ExportVarNameMDS->getValueID() == llvm::Value::MDStringVal) {
568 llvm::StringRef ExportVarName =
569 static_cast<llvm::MDString*>(ExportVarNameMDS)->getString();
570
571 CodeEmitter::global_addresses_const_iterator I, E;
572 for (I = mCodeEmitter->global_address_begin(),
573 E = mCodeEmitter->global_address_end();
574 I != E; I++) {
575 if (I->first->getValueID() != llvm::Value::GlobalVariableVal)
576 continue;
577 if (ExportVarName == I->first->getName()) {
Logan2a6dc822011-01-06 04:05:20 +0800578 varList.push_back(I->second);
Logan1f028c02010-11-27 01:02:48 +0800579 break;
580 }
581 }
582 if (I != mCodeEmitter->global_address_end())
583 continue; // found
584 }
585 }
586 // if reaching here, we know the global variable record in metadata is
587 // not found. So we make an empty slot
Logan2a6dc822011-01-06 04:05:20 +0800588 varList.push_back(NULL);
Logan1f028c02010-11-27 01:02:48 +0800589 }
Logan2a6dc822011-01-06 04:05:20 +0800590
Stephen Hinesbbcef8a2011-05-04 19:40:10 -0700591 bccAssert((varList.size() == ExportVarMetadata->getNumOperands()) &&
592 "Number of slots doesn't match the number of export variables!");
Logan1f028c02010-11-27 01:02:48 +0800593 }
594
595 if (ExportFuncMetadata) {
Logan2a6dc822011-01-06 04:05:20 +0800596 ScriptCompiled::ExportFuncList &funcList = mpResult->mExportFuncs;
597
Logan1f028c02010-11-27 01:02:48 +0800598 for (int i = 0, e = ExportFuncMetadata->getNumOperands(); i != e; i++) {
599 llvm::MDNode *ExportFunc = ExportFuncMetadata->getOperand(i);
600 if (ExportFunc != NULL && ExportFunc->getNumOperands() > 0) {
601 llvm::Value *ExportFuncNameMDS = ExportFunc->getOperand(0);
602 if (ExportFuncNameMDS->getValueID() == llvm::Value::MDStringVal) {
603 llvm::StringRef ExportFuncName =
604 static_cast<llvm::MDString*>(ExportFuncNameMDS)->getString();
Logan7dcaac92011-01-06 04:26:23 +0800605 funcList.push_back(mpResult->lookup(ExportFuncName.str().c_str()));
Logan1f028c02010-11-27 01:02:48 +0800606 }
607 }
608 }
609 }
610
611 // Tell code emitter now can release the memory using during the JIT since
612 // we have done the code emission
613 mCodeEmitter->releaseUnnecessary();
614
615 // Finally, read pragma information from the metadata node of the @Module if
616 // any.
Logan2a6dc822011-01-06 04:05:20 +0800617 if (PragmaMetadata) {
618 ScriptCompiled::PragmaList &pragmaList = mpResult->mPragmas;
619
Logan1f028c02010-11-27 01:02:48 +0800620 for (int i = 0, e = PragmaMetadata->getNumOperands(); i != e; i++) {
621 llvm::MDNode *Pragma = PragmaMetadata->getOperand(i);
622 if (Pragma != NULL &&
623 Pragma->getNumOperands() == 2 /* should have exactly 2 operands */) {
624 llvm::Value *PragmaNameMDS = Pragma->getOperand(0);
625 llvm::Value *PragmaValueMDS = Pragma->getOperand(1);
626
627 if ((PragmaNameMDS->getValueID() == llvm::Value::MDStringVal) &&
628 (PragmaValueMDS->getValueID() == llvm::Value::MDStringVal)) {
629 llvm::StringRef PragmaName =
630 static_cast<llvm::MDString*>(PragmaNameMDS)->getString();
631 llvm::StringRef PragmaValue =
632 static_cast<llvm::MDString*>(PragmaValueMDS)->getString();
633
Logan2a6dc822011-01-06 04:05:20 +0800634 pragmaList.push_back(
Logan1f028c02010-11-27 01:02:48 +0800635 std::make_pair(std::string(PragmaName.data(),
636 PragmaName.size()),
637 std::string(PragmaValue.data(),
638 PragmaValue.size())));
639 }
640 }
641 }
Logan2a6dc822011-01-06 04:05:20 +0800642 }
Logan1f028c02010-11-27 01:02:48 +0800643
Stephen Hines071288a2011-01-27 14:38:26 -0800644 if (ObjectSlotMetadata) {
645 ScriptCompiled::ObjectSlotList &objectSlotList = mpResult->mObjectSlots;
646
647 for (int i = 0, e = ObjectSlotMetadata->getNumOperands(); i != e; i++) {
648 llvm::MDNode *ObjectSlot = ObjectSlotMetadata->getOperand(i);
649 if (ObjectSlot != NULL &&
650 ObjectSlot->getNumOperands() == 1) {
651 llvm::Value *SlotMDS = ObjectSlot->getOperand(0);
652 if (SlotMDS->getValueID() == llvm::Value::MDStringVal) {
653 llvm::StringRef Slot =
654 static_cast<llvm::MDString*>(SlotMDS)->getString();
655 uint32_t USlot = 0;
656 if (Slot.getAsInteger(10, USlot)) {
657 setError("Non-integer object slot value '" + Slot.str() + "'");
658 goto on_bcc_compile_error;
659 }
660 objectSlotList.push_back(USlot);
661 }
662 }
663 }
664 }
665
Logan1f028c02010-11-27 01:02:48 +0800666on_bcc_compile_error:
667 // LOGE("on_bcc_compiler_error");
668 if (CodeGenPasses) {
669 delete CodeGenPasses;
670 } else if (TD) {
671 delete TD;
672 }
673 if (TM)
674 delete TM;
675
676 if (mError.empty()) {
Logan65719812011-01-07 11:17:14 +0800677 return 0;
Logan1f028c02010-11-27 01:02:48 +0800678 }
679
680 // LOGE(getErrorMessage());
Logan65719812011-01-07 11:17:14 +0800681 return 1;
Logan1f028c02010-11-27 01:02:48 +0800682}
683
684
Logan1f028c02010-11-27 01:02:48 +0800685Compiler::~Compiler() {
Logan1f028c02010-11-27 01:02:48 +0800686 delete mModule;
Logan1f028c02010-11-27 01:02:48 +0800687 delete mContext;
Logana4994f52010-11-27 14:06:02 +0800688
689 // llvm::llvm_shutdown();
Logan1f028c02010-11-27 01:02:48 +0800690}
691
Logan1f028c02010-11-27 01:02:48 +0800692} // namespace bcc