blob: b4bdd5dc3d5c9df866829b169571ee228dd955b9 [file] [log] [blame]
Logan Chien8b977d32012-02-21 19:14:55 +08001/*
2 * Copyright (C) 2012 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#include "compilation_unit.h"
18
Logan Chien110bcba2012-04-16 19:11:28 +080019#include "compiled_method.h"
Shih-wei Liaod7726e42012-04-20 15:23:36 -070020#include "file.h"
Elliott Hughes0f3c5532012-03-30 14:51:51 -070021#include "instruction_set.h"
Logan Chien8b977d32012-02-21 19:14:55 +080022#include "ir_builder.h"
23#include "logging.h"
Shih-wei Liaod7726e42012-04-20 15:23:36 -070024#include "os.h"
Logan Chien8b977d32012-02-21 19:14:55 +080025
TDYa127d668a062012-04-13 12:36:57 -070026#include "runtime_support_builder_arm.h"
27#include "runtime_support_builder_x86.h"
28
Logan Chien8b977d32012-02-21 19:14:55 +080029#include <llvm/ADT/OwningPtr.h>
30#include <llvm/ADT/StringSet.h>
31#include <llvm/ADT/Triple.h>
32#include <llvm/Analysis/CallGraph.h>
33#include <llvm/Analysis/DebugInfo.h>
TDYa127f15b0ab2012-05-11 21:01:36 -070034#include <llvm/Analysis/Dominators.h>
35#include <llvm/Analysis/LoopInfo.h>
Logan Chien8b977d32012-02-21 19:14:55 +080036#include <llvm/Analysis/LoopPass.h>
37#include <llvm/Analysis/RegionPass.h>
TDYa127f15b0ab2012-05-11 21:01:36 -070038#include <llvm/Analysis/ScalarEvolution.h>
Logan Chien8b977d32012-02-21 19:14:55 +080039#include <llvm/Analysis/Verifier.h>
40#include <llvm/Assembly/PrintModulePass.h>
41#include <llvm/Bitcode/ReaderWriter.h>
42#include <llvm/CallGraphSCCPass.h>
Logan Chien110bcba2012-04-16 19:11:28 +080043#include <llvm/CodeGen/MachineFrameInfo.h>
44#include <llvm/CodeGen/MachineFunction.h>
45#include <llvm/CodeGen/MachineFunctionPass.h>
Logan Chien8b977d32012-02-21 19:14:55 +080046#include <llvm/DerivedTypes.h>
47#include <llvm/LLVMContext.h>
Logan Chien8b977d32012-02-21 19:14:55 +080048#include <llvm/Module.h>
49#include <llvm/PassManager.h>
50#include <llvm/Support/Debug.h>
51#include <llvm/Support/FormattedStream.h>
52#include <llvm/Support/ManagedStatic.h>
Shih-wei Liaod7726e42012-04-20 15:23:36 -070053#include <llvm/Support/MemoryBuffer.h>
Logan Chien8b977d32012-02-21 19:14:55 +080054#include <llvm/Support/PassNameParser.h>
55#include <llvm/Support/PluginLoader.h>
56#include <llvm/Support/PrettyStackTrace.h>
57#include <llvm/Support/Signals.h>
58#include <llvm/Support/SystemUtils.h>
59#include <llvm/Support/TargetRegistry.h>
60#include <llvm/Support/TargetSelect.h>
61#include <llvm/Support/ToolOutputFile.h>
62#include <llvm/Support/raw_ostream.h>
Shih-wei Liaod7726e42012-04-20 15:23:36 -070063#include <llvm/Support/system_error.h>
Logan Chien8b977d32012-02-21 19:14:55 +080064#include <llvm/Target/TargetData.h>
65#include <llvm/Target/TargetLibraryInfo.h>
66#include <llvm/Target/TargetMachine.h>
Shih-wei Liaof1cb9a52012-04-20 01:49:18 -070067#include <llvm/Transforms/IPO.h>
Logan Chien8b977d32012-02-21 19:14:55 +080068#include <llvm/Transforms/IPO/PassManagerBuilder.h>
TDYa127f15b0ab2012-05-11 21:01:36 -070069#include <llvm/Transforms/Scalar.h>
Logan Chien8b977d32012-02-21 19:14:55 +080070
Shih-wei Liaod7726e42012-04-20 15:23:36 -070071#include <sys/types.h>
72#include <sys/wait.h>
73#include <unistd.h>
74
Logan Chien8b977d32012-02-21 19:14:55 +080075#include <string>
76
Logan Chien110bcba2012-04-16 19:11:28 +080077namespace {
78
79class UpdateFrameSizePass : public llvm::MachineFunctionPass {
80 public:
81 static char ID;
82
83 UpdateFrameSizePass() : llvm::MachineFunctionPass(ID), cunit_(NULL) {
84 LOG(FATAL) << "Unexpected instantiation of UpdateFrameSizePass";
85 // NOTE: We have to declare this constructor for llvm::RegisterPass, but
86 // this constructor won't work because we have no information on
87 // CompilationUnit. Thus, we should place a LOG(FATAL) here.
88 }
89
90 UpdateFrameSizePass(art::compiler_llvm::CompilationUnit* cunit)
91 : llvm::MachineFunctionPass(ID), cunit_(cunit) {
92 }
93
94 virtual bool runOnMachineFunction(llvm::MachineFunction &MF) {
95 cunit_->UpdateFrameSizeInBytes(MF.getFunction(),
96 MF.getFrameInfo()->getStackSize());
97 return false;
98 }
99
100 private:
101 art::compiler_llvm::CompilationUnit* cunit_;
102};
103
104char UpdateFrameSizePass::ID = 0;
105
106llvm::RegisterPass<UpdateFrameSizePass> reg_update_frame_size_pass_(
107 "update-frame-size", "Update frame size pass", false, false);
108
TDYa127f15b0ab2012-05-11 21:01:36 -0700109
110// TODO: We may need something to manage these passes.
111// TODO: We need high-level IR to analysis and do this at the IRBuilder level.
112class AddSuspendCheckToLoopLatchPass : public llvm::LoopPass {
113 public:
114 static char ID;
115
116 AddSuspendCheckToLoopLatchPass() : llvm::LoopPass(ID), irb_(NULL) {
117 LOG(FATAL) << "Unexpected instantiation of AddSuspendCheckToLoopLatchPass";
118 // NOTE: We have to declare this constructor for llvm::RegisterPass, but
119 // this constructor won't work because we have no information on
120 // IRBuilder. Thus, we should place a LOG(FATAL) here.
121 }
122
123 AddSuspendCheckToLoopLatchPass(art::compiler_llvm::IRBuilder* irb)
124 : llvm::LoopPass(ID), irb_(irb) {
125 }
126
127 virtual void getAnalysisUsage(llvm::AnalysisUsage &AU) const {
128 AU.addRequiredID(llvm::LoopSimplifyID);
129
130 AU.addPreserved<llvm::DominatorTree>();
131 AU.addPreserved<llvm::LoopInfo>();
132 AU.addPreservedID(llvm::LoopSimplifyID);
133 AU.addPreserved<llvm::ScalarEvolution>();
134 AU.addPreservedID(llvm::BreakCriticalEdgesID);
135 }
136
137 virtual bool runOnLoop(llvm::Loop *loop, llvm::LPPassManager &lpm) {
138 CHECK_EQ(loop->getNumBackEdges(), 1U) << "Loop must be simplified!";
139 llvm::BasicBlock* bb = loop->getLoopLatch();
140 CHECK_NE(bb, static_cast<void*>(NULL)) << "A single loop latch must exist.";
141
142 irb_->SetInsertPoint(bb->getTerminator());
143
Shih-wei Liaoaad0d972012-05-16 00:50:55 -0700144 using art::compiler_llvm::runtime_support::TestSuspend;
145 using art::compiler_llvm::runtime_support::GetCurrentThread;
TDYa127f15b0ab2012-05-11 21:01:36 -0700146 llvm::Value* runtime_func = irb_->GetRuntime(TestSuspend);
147 llvm::Value* thread_object_addr = irb_->CreateCall(irb_->GetRuntime(GetCurrentThread));
148 irb_->CreateCall(runtime_func, thread_object_addr);
149
150 return true;
151 }
152
153 private:
154 art::compiler_llvm::IRBuilder* irb_;
155};
156
157char AddSuspendCheckToLoopLatchPass::ID = 0;
158
159llvm::RegisterPass<AddSuspendCheckToLoopLatchPass> reg_add_suspend_check_to_loop_latch_pass_(
160 "add-suspend-check-to-loop-latch", "Add suspend check to loop latch pass", false, false);
161
162
Logan Chien110bcba2012-04-16 19:11:28 +0800163} // end anonymous namespace
164
Logan Chien8b977d32012-02-21 19:14:55 +0800165namespace art {
166namespace compiler_llvm {
167
168llvm::Module* makeLLVMModuleContents(llvm::Module* module);
169
170
Logan Chien6546ec52012-03-17 20:08:29 +0800171CompilationUnit::CompilationUnit(InstructionSet insn_set, size_t elf_idx)
Logan Chien8ba2fc52012-04-23 09:10:46 +0800172: cunit_lock_("compilation_unit_lock"), insn_set_(insn_set), elf_idx_(elf_idx),
TDYa127b2eb5c12012-05-24 15:52:10 -0700173 context_(new llvm::LLVMContext()), compiled_methods_map_(new CompiledMethodMap()),
174 mem_usage_(0), num_elf_funcs_(0) {
Logan Chien8b977d32012-02-21 19:14:55 +0800175
176 // Create the module and include the runtime function declaration
177 module_ = new llvm::Module("art", *context_);
178 makeLLVMModuleContents(module_);
179
180 // Create IRBuilder
181 irb_.reset(new IRBuilder(*context_, *module_));
TDYa127d668a062012-04-13 12:36:57 -0700182
183 // We always need a switch case, so just use a normal function.
184 switch(insn_set_) {
185 default:
186 runtime_support_.reset(new RuntimeSupportBuilder(*context_, *module_, *irb_));
187 break;
188 case kArm:
189 case kThumb2:
190 runtime_support_.reset(new RuntimeSupportBuilderARM(*context_, *module_, *irb_));
191 break;
192 case kX86:
193 runtime_support_.reset(new RuntimeSupportBuilderX86(*context_, *module_, *irb_));
194 break;
195 }
196
197 runtime_support_->OptimizeRuntimeSupport();
198
199 irb_->SetRuntimeSupport(runtime_support_.get());
Logan Chien8b977d32012-02-21 19:14:55 +0800200}
201
202
203CompilationUnit::~CompilationUnit() {
204}
205
206
Logan Chien08e1ba32012-05-08 15:08:51 +0800207bool CompilationUnit::Materialize(size_t thread_count) {
Logan Chien8ba2fc52012-04-23 09:10:46 +0800208 MutexLock GUARD(cunit_lock_);
209
Logan Chienb5eb00c2012-05-18 19:56:46 +0800210 // Materialize the bitcode to elf_image_
211 llvm::raw_string_ostream str_os(elf_image_);
212 bool success = MaterializeToFile(str_os);
213 LOG(INFO) << "Compilation Unit: " << elf_idx_ << (success ? " (done)" : " (failed)");
TDYa127388a83b2012-05-09 18:56:22 -0700214
Logan Chienb5eb00c2012-05-18 19:56:46 +0800215 // Free the resources
216 context_.reset(NULL);
217 irb_.reset(NULL);
218 module_ = NULL;
TDYa127b2eb5c12012-05-24 15:52:10 -0700219 runtime_support_.reset(NULL);
220 compiled_methods_map_.reset(NULL);
TDYa127388a83b2012-05-09 18:56:22 -0700221
Logan Chienb5eb00c2012-05-18 19:56:46 +0800222 return success;
Logan Chien8b977d32012-02-21 19:14:55 +0800223}
224
225
Logan Chien110bcba2012-04-16 19:11:28 +0800226void CompilationUnit::RegisterCompiledMethod(const llvm::Function* func,
227 CompiledMethod* compiled_method) {
Logan Chien8ba2fc52012-04-23 09:10:46 +0800228 MutexLock GUARD(cunit_lock_);
TDYa127b2eb5c12012-05-24 15:52:10 -0700229 compiled_methods_map_->Put(func, compiled_method);
Logan Chien110bcba2012-04-16 19:11:28 +0800230}
231
232
233void CompilationUnit::UpdateFrameSizeInBytes(const llvm::Function* func,
234 size_t frame_size_in_bytes) {
Logan Chien8ba2fc52012-04-23 09:10:46 +0800235 MutexLock GUARD(cunit_lock_);
Logan Chien110bcba2012-04-16 19:11:28 +0800236 SafeMap<const llvm::Function*, CompiledMethod*>::iterator iter =
TDYa127b2eb5c12012-05-24 15:52:10 -0700237 compiled_methods_map_->find(func);
Logan Chien110bcba2012-04-16 19:11:28 +0800238
TDYa127b2eb5c12012-05-24 15:52:10 -0700239 if (iter != compiled_methods_map_->end()) {
Logan Chien110bcba2012-04-16 19:11:28 +0800240 CompiledMethod* compiled_method = iter->second;
241 compiled_method->SetFrameSizeInBytes(frame_size_in_bytes);
242
243 if (frame_size_in_bytes > 1728u) {
244 LOG(WARNING) << "Huge frame size: " << frame_size_in_bytes
245 << " elf_idx=" << compiled_method->GetElfIndex()
246 << " elf_func_idx=" << compiled_method->GetElfFuncIndex();
247 }
248 }
249}
250
Logan Chienb1bab1c2012-05-11 11:05:45 +0800251bool CompilationUnit::MaterializeToFile(llvm::raw_ostream& out_stream) {
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700252 // Lookup the LLVM target
253 char const* target_triple = NULL;
254 char const* target_attr = NULL;
255
Logan Chienb1bab1c2012-05-11 11:05:45 +0800256 switch (insn_set_) {
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700257 case kThumb2:
258 target_triple = "thumb-none-linux-gnueabi";
259 target_attr = "+thumb2,+neon,+neonfp,+vfp3";
260 break;
261
262 case kArm:
263 target_triple = "armv7-none-linux-gnueabi";
264 // TODO: Fix for Xoom.
265 target_attr = "+v7,+neon,+neonfp,+vfp3";
266 break;
267
268 case kX86:
269 target_triple = "i386-pc-linux-gnu";
270 target_attr = "";
271 break;
272
273 case kMips:
274 target_triple = "mipsel-unknown-linux";
275 target_attr = "mips32r2";
276 break;
277
278 default:
Logan Chienb1bab1c2012-05-11 11:05:45 +0800279 LOG(FATAL) << "Unknown instruction set: " << insn_set_;
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700280 }
281
282 std::string errmsg;
283 llvm::Target const* target =
284 llvm::TargetRegistry::lookupTarget(target_triple, errmsg);
285
286 CHECK(target != NULL) << errmsg;
287
288 // Target options
289 llvm::TargetOptions target_options;
290 target_options.FloatABIType = llvm::FloatABI::Soft;
291 target_options.NoFramePointerElim = true;
292 target_options.NoFramePointerElimNonLeaf = true;
293 target_options.UseSoftFloat = false;
TDYa1273978da52012-05-19 07:45:39 -0700294 target_options.EnableFastISel = false;
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700295
296 // Create the llvm::TargetMachine
Logan Chienb6bed0b2012-05-04 15:03:56 +0800297 llvm::OwningPtr<llvm::TargetMachine> target_machine(
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700298 target->createTargetMachine(target_triple, "", target_attr, target_options,
299 llvm::Reloc::Static, llvm::CodeModel::Small,
TDYa127e4c2ccc2012-05-13 21:10:36 -0700300 llvm::CodeGenOpt::Less));
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700301
Logan Chienb6bed0b2012-05-04 15:03:56 +0800302 CHECK(target_machine.get() != NULL) << "Failed to create target machine";
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700303
304 // Add target data
305 llvm::TargetData const* target_data = target_machine->getTargetData();
306
307 // PassManager for code generation passes
308 llvm::PassManager pm;
309 pm.add(new llvm::TargetData(*target_data));
310
311 // FunctionPassManager for optimization pass
Logan Chien799ef4f2012-04-23 00:17:47 +0800312 llvm::FunctionPassManager fpm(module_);
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700313 fpm.add(new llvm::TargetData(*target_data));
314
TDYa127f15b0ab2012-05-11 21:01:36 -0700315 if (bitcode_filename_.empty()) {
316 // If we don't need write the bitcode to file, add the AddSuspendCheckToLoopLatchPass to the
317 // regular FunctionPass.
318 fpm.add(new ::AddSuspendCheckToLoopLatchPass(irb_.get()));
319 } else {
320 // Run AddSuspendCheckToLoopLatchPass before we write the bitcode to file.
321 llvm::FunctionPassManager fpm2(module_);
322 fpm2.add(new ::AddSuspendCheckToLoopLatchPass(irb_.get()));
323 fpm2.doInitialization();
324 for (llvm::Module::iterator F = module_->begin(), E = module_->end();
325 F != E; ++F) {
326 fpm2.run(*F);
327 }
328 fpm2.doFinalization();
329
330
331 // Write bitcode to file
332 std::string errmsg;
333
334 llvm::OwningPtr<llvm::tool_output_file> out_file(
335 new llvm::tool_output_file(bitcode_filename_.c_str(), errmsg,
336 llvm::raw_fd_ostream::F_Binary));
337
338
339 if (!errmsg.empty()) {
340 LOG(ERROR) << "Failed to create bitcode output file: " << errmsg;
341 return false;
342 }
343
344 llvm::WriteBitcodeToFile(module_, out_file->os());
345 out_file->keep();
346 }
347
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700348 // Add optimization pass
349 llvm::PassManagerBuilder pm_builder;
Shih-wei Liaoe0e40242012-05-08 01:04:03 -0700350 //pm_builder.Inliner = llvm::createFunctionInliningPass();
351 pm_builder.Inliner = llvm::createAlwaysInlinerPass();
Shih-wei Liao415576b2012-04-23 15:28:53 -0700352 //pm_builder.Inliner = llvm::createPartialInliningPass();
353 pm_builder.OptLevel = 3;
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700354 pm_builder.DisableSimplifyLibCalls = 1;
TDYa127e4c2ccc2012-05-13 21:10:36 -0700355 pm_builder.DisableUnitAtATime = 1;
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700356 pm_builder.populateFunctionPassManager(fpm);
TDYa127ce9c3172012-05-15 06:09:27 -0700357 pm_builder.populateModulePassManager(pm);
358 pm.add(llvm::createStripDeadPrototypesPass());
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700359
360 // Add passes to emit ELF image
361 {
Logan Chien08e1ba32012-05-08 15:08:51 +0800362 llvm::formatted_raw_ostream formatted_os(out_stream, false);
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700363
364 // Ask the target to add backend passes as necessary.
365 if (target_machine->addPassesToEmitFile(pm,
366 formatted_os,
367 llvm::TargetMachine::CGFT_ObjectFile,
368 true)) {
369 LOG(FATAL) << "Unable to generate ELF for this target";
370 return false;
371 }
372
373 // FIXME: Unable to run the UpdateFrameSizePass pass since it tries to
374 // update the value reside in the different address space.
375 // Add pass to update the frame_size_in_bytes_
376 //pm.add(new ::UpdateFrameSizePass(this));
377
378 // Run the per-function optimization
379 fpm.doInitialization();
Logan Chien799ef4f2012-04-23 00:17:47 +0800380 for (llvm::Module::iterator F = module_->begin(), E = module_->end();
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700381 F != E; ++F) {
382 fpm.run(*F);
383 }
384 fpm.doFinalization();
385
386 // Run the code generation passes
Logan Chien799ef4f2012-04-23 00:17:47 +0800387 pm.run(*module_);
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700388 }
389
390 return true;
391}
Logan Chien110bcba2012-04-16 19:11:28 +0800392
Logan Chien8b977d32012-02-21 19:14:55 +0800393} // namespace compiler_llvm
394} // namespace art