blob: 3d6e98369e363bedc62b9e0de66432b47dad301e [file] [log] [blame]
buzbee67bf8852011-08-17 17:51:35 -07001/*
2 * Copyright (C) 2011 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 "Dalvik.h"
18#include "CompilerInternals.h"
19#include "Dataflow.h"
Ian Rogers0571d352011-11-03 19:51:38 -070020#include "leb128.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070021#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070022#include "runtime.h"
buzbee67bf8852011-08-17 17:51:35 -070023
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080024namespace art {
25
buzbeece302932011-10-04 14:32:18 -070026/* Default optimizer/debug setting for the compiler. */
Elliott Hughese52e49b2012-04-02 16:05:44 -070027static uint32_t kCompilerOptimizerDisableFlags = 0 | // Disable specific optimizations
Bill Buzbeea114add2012-05-03 15:00:40 -070028 //(1 << kLoadStoreElimination) |
29 //(1 << kLoadHoisting) |
30 //(1 << kSuppressLoads) |
31 //(1 << kNullCheckElimination) |
32 //(1 << kPromoteRegs) |
33 //(1 << kTrackLiveTemps) |
34 //(1 << kSkipLargeMethodOptimization) |
35 //(1 << kSafeOptimizations) |
36 //(1 << kBBOpt) |
37 //(1 << kMatch) |
38 //(1 << kPromoteCompilerTemps) |
39 0;
buzbeece302932011-10-04 14:32:18 -070040
Elliott Hughese52e49b2012-04-02 16:05:44 -070041static uint32_t kCompilerDebugFlags = 0 | // Enable debug/testing modes
Bill Buzbeea114add2012-05-03 15:00:40 -070042 //(1 << kDebugDisplayMissingTargets) |
43 //(1 << kDebugVerbose) |
44 //(1 << kDebugDumpCFG) |
45 //(1 << kDebugSlowFieldPath) |
46 //(1 << kDebugSlowInvokePath) |
47 //(1 << kDebugSlowStringPath) |
48 //(1 << kDebugSlowestFieldPath) |
49 //(1 << kDebugSlowestStringPath) |
50 //(1 << kDebugExerciseResolveMethod) |
51 //(1 << kDebugVerifyDataflow) |
52 //(1 << kDebugShowMemoryUsage) |
53 //(1 << kDebugShowNops) |
54 //(1 << kDebugCountOpcodes) |
buzbeead8f15e2012-06-18 14:49:45 -070055#if defined(ART_USE_QUICK_COMPILER)
56 //(1 << kDebugDumpBitcodeFile) |
57#endif
Bill Buzbeea114add2012-05-03 15:00:40 -070058 0;
buzbeece302932011-10-04 14:32:18 -070059
buzbee31a4a6f2012-02-28 15:36:15 -080060inline bool contentIsInsn(const u2* codePtr) {
Bill Buzbeea114add2012-05-03 15:00:40 -070061 u2 instr = *codePtr;
62 Instruction::Code opcode = (Instruction::Code)(instr & 0xff);
buzbee67bf8852011-08-17 17:51:35 -070063
Bill Buzbeea114add2012-05-03 15:00:40 -070064 /*
65 * Since the low 8-bit in metadata may look like NOP, we need to check
66 * both the low and whole sub-word to determine whether it is code or data.
67 */
68 return (opcode != Instruction::NOP || instr == 0);
buzbee67bf8852011-08-17 17:51:35 -070069}
70
71/*
72 * Parse an instruction, return the length of the instruction
73 */
buzbee31a4a6f2012-02-28 15:36:15 -080074inline int parseInsn(CompilationUnit* cUnit, const u2* codePtr,
Bill Buzbeea114add2012-05-03 15:00:40 -070075 DecodedInstruction* decoded_instruction, bool printMe)
buzbee67bf8852011-08-17 17:51:35 -070076{
Elliott Hughesadb8c672012-03-06 16:49:32 -080077 // Don't parse instruction data
78 if (!contentIsInsn(codePtr)) {
79 return 0;
80 }
buzbee67bf8852011-08-17 17:51:35 -070081
Elliott Hughesadb8c672012-03-06 16:49:32 -080082 const Instruction* instruction = Instruction::At(codePtr);
83 *decoded_instruction = DecodedInstruction(instruction);
buzbee67bf8852011-08-17 17:51:35 -070084
Elliott Hughesadb8c672012-03-06 16:49:32 -080085 if (printMe) {
Bill Buzbeea114add2012-05-03 15:00:40 -070086 char* decodedString = oatGetDalvikDisassembly(cUnit, *decoded_instruction,
87 NULL);
88 LOG(INFO) << codePtr << ": 0x"
89 << std::hex << static_cast<int>(decoded_instruction->opcode)
Elliott Hughesadb8c672012-03-06 16:49:32 -080090 << " " << decodedString;
91 }
92 return instruction->SizeInCodeUnits();
buzbee67bf8852011-08-17 17:51:35 -070093}
94
95#define UNKNOWN_TARGET 0xffffffff
96
Elliott Hughesadb8c672012-03-06 16:49:32 -080097inline bool isGoto(MIR* insn) {
98 switch (insn->dalvikInsn.opcode) {
99 case Instruction::GOTO:
100 case Instruction::GOTO_16:
101 case Instruction::GOTO_32:
102 return true;
103 default:
104 return false;
Bill Buzbeea114add2012-05-03 15:00:40 -0700105 }
buzbee67bf8852011-08-17 17:51:35 -0700106}
107
108/*
109 * Identify unconditional branch instructions
110 */
Elliott Hughesadb8c672012-03-06 16:49:32 -0800111inline bool isUnconditionalBranch(MIR* insn) {
112 switch (insn->dalvikInsn.opcode) {
113 case Instruction::RETURN_VOID:
114 case Instruction::RETURN:
115 case Instruction::RETURN_WIDE:
116 case Instruction::RETURN_OBJECT:
117 return true;
Bill Buzbeea114add2012-05-03 15:00:40 -0700118 default:
119 return isGoto(insn);
Elliott Hughesadb8c672012-03-06 16:49:32 -0800120 }
buzbee67bf8852011-08-17 17:51:35 -0700121}
122
123/* Split an existing block from the specified code offset into two */
buzbee31a4a6f2012-02-28 15:36:15 -0800124BasicBlock *splitBlock(CompilationUnit* cUnit, unsigned int codeOffset,
Bill Buzbeea114add2012-05-03 15:00:40 -0700125 BasicBlock* origBlock, BasicBlock** immedPredBlockP)
buzbee67bf8852011-08-17 17:51:35 -0700126{
Bill Buzbeea114add2012-05-03 15:00:40 -0700127 MIR* insn = origBlock->firstMIRInsn;
128 while (insn) {
129 if (insn->offset == codeOffset) break;
130 insn = insn->next;
131 }
132 if (insn == NULL) {
133 LOG(FATAL) << "Break split failed";
134 }
135 BasicBlock *bottomBlock = oatNewBB(cUnit, kDalvikByteCode,
136 cUnit->numBlocks++);
137 oatInsertGrowableList(cUnit, &cUnit->blockList, (intptr_t) bottomBlock);
buzbee67bf8852011-08-17 17:51:35 -0700138
Bill Buzbeea114add2012-05-03 15:00:40 -0700139 bottomBlock->startOffset = codeOffset;
140 bottomBlock->firstMIRInsn = insn;
141 bottomBlock->lastMIRInsn = origBlock->lastMIRInsn;
buzbee67bf8852011-08-17 17:51:35 -0700142
Bill Buzbeea114add2012-05-03 15:00:40 -0700143 /* Add it to the quick lookup cache */
144 cUnit->blockMap.Put(bottomBlock->startOffset, bottomBlock);
buzbee5b537102012-01-17 17:33:47 -0800145
Bill Buzbeea114add2012-05-03 15:00:40 -0700146 /* Handle the taken path */
147 bottomBlock->taken = origBlock->taken;
148 if (bottomBlock->taken) {
149 origBlock->taken = NULL;
150 oatDeleteGrowableList(bottomBlock->taken->predecessors,
buzbeeba938cb2012-02-03 14:47:55 -0800151 (intptr_t)origBlock);
Bill Buzbeea114add2012-05-03 15:00:40 -0700152 oatInsertGrowableList(cUnit, bottomBlock->taken->predecessors,
153 (intptr_t)bottomBlock);
154 }
155
156 /* Handle the fallthrough path */
157 bottomBlock->needFallThroughBranch = origBlock->needFallThroughBranch;
158 bottomBlock->fallThrough = origBlock->fallThrough;
159 origBlock->fallThrough = bottomBlock;
160 origBlock->needFallThroughBranch = true;
161 oatInsertGrowableList(cUnit, bottomBlock->predecessors,
162 (intptr_t)origBlock);
163 if (bottomBlock->fallThrough) {
164 oatDeleteGrowableList(bottomBlock->fallThrough->predecessors,
165 (intptr_t)origBlock);
166 oatInsertGrowableList(cUnit, bottomBlock->fallThrough->predecessors,
167 (intptr_t)bottomBlock);
168 }
169
170 /* Handle the successor list */
171 if (origBlock->successorBlockList.blockListType != kNotUsed) {
172 bottomBlock->successorBlockList = origBlock->successorBlockList;
173 origBlock->successorBlockList.blockListType = kNotUsed;
174 GrowableListIterator iterator;
175
176 oatGrowableListIteratorInit(&bottomBlock->successorBlockList.blocks,
177 &iterator);
178 while (true) {
179 SuccessorBlockInfo *successorBlockInfo =
180 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
181 if (successorBlockInfo == NULL) break;
182 BasicBlock *bb = successorBlockInfo->block;
183 oatDeleteGrowableList(bb->predecessors, (intptr_t)origBlock);
184 oatInsertGrowableList(cUnit, bb->predecessors, (intptr_t)bottomBlock);
buzbee67bf8852011-08-17 17:51:35 -0700185 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700186 }
buzbee67bf8852011-08-17 17:51:35 -0700187
Bill Buzbeea114add2012-05-03 15:00:40 -0700188 origBlock->lastMIRInsn = insn->prev;
buzbee67bf8852011-08-17 17:51:35 -0700189
Bill Buzbeea114add2012-05-03 15:00:40 -0700190 insn->prev->next = NULL;
191 insn->prev = NULL;
192 /*
193 * Update the immediate predecessor block pointer so that outgoing edges
194 * can be applied to the proper block.
195 */
196 if (immedPredBlockP) {
197 DCHECK_EQ(*immedPredBlockP, origBlock);
198 *immedPredBlockP = bottomBlock;
199 }
200 return bottomBlock;
buzbee67bf8852011-08-17 17:51:35 -0700201}
202
203/*
204 * Given a code offset, find out the block that starts with it. If the offset
buzbee9ab05de2012-01-18 15:43:48 -0800205 * is in the middle of an existing block, split it into two. If immedPredBlockP
206 * is not non-null and is the block being split, update *immedPredBlockP to
207 * point to the bottom block so that outgoing edges can be set up properly
208 * (by the caller)
buzbee5b537102012-01-17 17:33:47 -0800209 * Utilizes a map for fast lookup of the typical cases.
buzbee67bf8852011-08-17 17:51:35 -0700210 */
buzbee31a4a6f2012-02-28 15:36:15 -0800211BasicBlock *findBlock(CompilationUnit* cUnit, unsigned int codeOffset,
212 bool split, bool create, BasicBlock** immedPredBlockP)
buzbee67bf8852011-08-17 17:51:35 -0700213{
Bill Buzbeea114add2012-05-03 15:00:40 -0700214 GrowableList* blockList = &cUnit->blockList;
215 BasicBlock* bb;
216 unsigned int i;
217 SafeMap<unsigned int, BasicBlock*>::iterator it;
buzbee67bf8852011-08-17 17:51:35 -0700218
Bill Buzbeea114add2012-05-03 15:00:40 -0700219 it = cUnit->blockMap.find(codeOffset);
220 if (it != cUnit->blockMap.end()) {
221 return it->second;
222 } else if (!create) {
223 return NULL;
224 }
225
226 if (split) {
227 for (i = 0; i < blockList->numUsed; i++) {
228 bb = (BasicBlock *) blockList->elemList[i];
229 if (bb->blockType != kDalvikByteCode) continue;
230 /* Check if a branch jumps into the middle of an existing block */
231 if ((codeOffset > bb->startOffset) && (bb->lastMIRInsn != NULL) &&
232 (codeOffset <= bb->lastMIRInsn->offset)) {
233 BasicBlock *newBB = splitBlock(cUnit, codeOffset, bb,
234 bb == *immedPredBlockP ?
235 immedPredBlockP : NULL);
236 return newBB;
237 }
buzbee5b537102012-01-17 17:33:47 -0800238 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700239 }
buzbee5b537102012-01-17 17:33:47 -0800240
Bill Buzbeea114add2012-05-03 15:00:40 -0700241 /* Create a new one */
242 bb = oatNewBB(cUnit, kDalvikByteCode, cUnit->numBlocks++);
243 oatInsertGrowableList(cUnit, &cUnit->blockList, (intptr_t) bb);
244 bb->startOffset = codeOffset;
245 cUnit->blockMap.Put(bb->startOffset, bb);
246 return bb;
buzbee67bf8852011-08-17 17:51:35 -0700247}
248
buzbeead8f15e2012-06-18 14:49:45 -0700249/* Turn method name into a legal Linux file name */
250void oatReplaceSpecialChars(std::string& str)
251{
252 static const struct { const char before; const char after; } match[] =
253 {{'/','-'}, {';','#'}, {' ','#'}, {'$','+'},
254 {'(','@'}, {')','@'}, {'<','='}, {'>','='}};
255 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
256 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
257 }
258}
259
buzbee67bf8852011-08-17 17:51:35 -0700260/* Dump the CFG into a DOT graph */
261void oatDumpCFG(CompilationUnit* cUnit, const char* dirPrefix)
262{
Bill Buzbeea114add2012-05-03 15:00:40 -0700263 FILE* file;
buzbeead8f15e2012-06-18 14:49:45 -0700264 std::string fname(PrettyMethod(cUnit->method_idx, *cUnit->dex_file));
265 oatReplaceSpecialChars(fname);
266 fname = StringPrintf("%s%s%x.dot", dirPrefix, fname.c_str(),
267 cUnit->entryBlock->fallThrough->startOffset);
268 file = fopen(fname.c_str(), "w");
Bill Buzbeea114add2012-05-03 15:00:40 -0700269 if (file == NULL) {
270 return;
271 }
272 fprintf(file, "digraph G {\n");
273
274 fprintf(file, " rankdir=TB\n");
275
276 int numReachableBlocks = cUnit->numReachableBlocks;
277 int idx;
278 const GrowableList *blockList = &cUnit->blockList;
279
280 for (idx = 0; idx < numReachableBlocks; idx++) {
281 int blockIdx = cUnit->dfsOrder.elemList[idx];
282 BasicBlock *bb = (BasicBlock *) oatGrowableListGetElement(blockList,
283 blockIdx);
284 if (bb == NULL) break;
285 if (bb->blockType == kEntryBlock) {
286 fprintf(file, " entry [shape=Mdiamond];\n");
287 } else if (bb->blockType == kExitBlock) {
288 fprintf(file, " exit [shape=Mdiamond];\n");
289 } else if (bb->blockType == kDalvikByteCode) {
290 fprintf(file, " block%04x [shape=record,label = \"{ \\\n",
291 bb->startOffset);
292 const MIR *mir;
293 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
294 bb->firstMIRInsn ? " | " : " ");
295 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
296 fprintf(file, " {%04x %s\\l}%s\\\n", mir->offset,
297 mir->ssaRep ? oatFullDisassembler(cUnit, mir) :
298 Instruction::Name(mir->dalvikInsn.opcode),
299 mir->next ? " | " : " ");
300 }
301 fprintf(file, " }\"];\n\n");
302 } else if (bb->blockType == kExceptionHandling) {
303 char blockName[BLOCK_NAME_LEN];
304
305 oatGetBlockName(bb, blockName);
306 fprintf(file, " %s [shape=invhouse];\n", blockName);
buzbee67bf8852011-08-17 17:51:35 -0700307 }
buzbee67bf8852011-08-17 17:51:35 -0700308
Bill Buzbeea114add2012-05-03 15:00:40 -0700309 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
buzbee67bf8852011-08-17 17:51:35 -0700310
Bill Buzbeea114add2012-05-03 15:00:40 -0700311 if (bb->taken) {
312 oatGetBlockName(bb, blockName1);
313 oatGetBlockName(bb->taken, blockName2);
314 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
315 blockName1, blockName2);
buzbee67bf8852011-08-17 17:51:35 -0700316 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700317 if (bb->fallThrough) {
318 oatGetBlockName(bb, blockName1);
319 oatGetBlockName(bb->fallThrough, blockName2);
320 fprintf(file, " %s:s -> %s:n\n", blockName1, blockName2);
321 }
322
323 if (bb->successorBlockList.blockListType != kNotUsed) {
324 fprintf(file, " succ%04x [shape=%s,label = \"{ \\\n",
325 bb->startOffset,
326 (bb->successorBlockList.blockListType == kCatch) ?
327 "Mrecord" : "record");
328 GrowableListIterator iterator;
329 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
330 &iterator);
331 SuccessorBlockInfo *successorBlockInfo =
332 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
333
334 int succId = 0;
335 while (true) {
336 if (successorBlockInfo == NULL) break;
337
338 BasicBlock *destBlock = successorBlockInfo->block;
339 SuccessorBlockInfo *nextSuccessorBlockInfo =
340 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
341
342 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
343 succId++,
344 successorBlockInfo->key,
345 destBlock->startOffset,
346 (nextSuccessorBlockInfo != NULL) ? " | " : " ");
347
348 successorBlockInfo = nextSuccessorBlockInfo;
349 }
350 fprintf(file, " }\"];\n\n");
351
352 oatGetBlockName(bb, blockName1);
353 fprintf(file, " %s:s -> succ%04x:n [style=dashed]\n",
354 blockName1, bb->startOffset);
355
356 if (bb->successorBlockList.blockListType == kPackedSwitch ||
357 bb->successorBlockList.blockListType == kSparseSwitch) {
358
359 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
360 &iterator);
361
362 succId = 0;
363 while (true) {
364 SuccessorBlockInfo *successorBlockInfo = (SuccessorBlockInfo *)
365 oatGrowableListIteratorNext(&iterator);
366 if (successorBlockInfo == NULL) break;
367
368 BasicBlock *destBlock = successorBlockInfo->block;
369
370 oatGetBlockName(destBlock, blockName2);
371 fprintf(file, " succ%04x:f%d:e -> %s:n\n", bb->startOffset,
372 succId++, blockName2);
373 }
374 }
375 }
376 fprintf(file, "\n");
377
378 /* Display the dominator tree */
379 oatGetBlockName(bb, blockName1);
380 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
381 blockName1, blockName1);
382 if (bb->iDom) {
383 oatGetBlockName(bb->iDom, blockName2);
384 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", blockName2, blockName1);
385 }
386 }
387 fprintf(file, "}\n");
388 fclose(file);
buzbee67bf8852011-08-17 17:51:35 -0700389}
390
391/* Verify if all the successor is connected with all the claimed predecessors */
buzbee31a4a6f2012-02-28 15:36:15 -0800392bool verifyPredInfo(CompilationUnit* cUnit, BasicBlock* bb)
buzbee67bf8852011-08-17 17:51:35 -0700393{
Bill Buzbeea114add2012-05-03 15:00:40 -0700394 GrowableListIterator iter;
buzbee67bf8852011-08-17 17:51:35 -0700395
Bill Buzbeea114add2012-05-03 15:00:40 -0700396 oatGrowableListIteratorInit(bb->predecessors, &iter);
397 while (true) {
398 BasicBlock *predBB = (BasicBlock*)oatGrowableListIteratorNext(&iter);
399 if (!predBB) break;
400 bool found = false;
401 if (predBB->taken == bb) {
402 found = true;
403 } else if (predBB->fallThrough == bb) {
404 found = true;
405 } else if (predBB->successorBlockList.blockListType != kNotUsed) {
406 GrowableListIterator iterator;
407 oatGrowableListIteratorInit(&predBB->successorBlockList.blocks,
408 &iterator);
409 while (true) {
410 SuccessorBlockInfo *successorBlockInfo = (SuccessorBlockInfo *)
411 oatGrowableListIteratorNext(&iterator);
412 if (successorBlockInfo == NULL) break;
413 BasicBlock *succBB = successorBlockInfo->block;
414 if (succBB == bb) {
buzbee67bf8852011-08-17 17:51:35 -0700415 found = true;
Bill Buzbeea114add2012-05-03 15:00:40 -0700416 break;
buzbee67bf8852011-08-17 17:51:35 -0700417 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700418 }
buzbee67bf8852011-08-17 17:51:35 -0700419 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700420 if (found == false) {
421 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
422 oatGetBlockName(bb, blockName1);
423 oatGetBlockName(predBB, blockName2);
424 oatDumpCFG(cUnit, "/sdcard/cfg/");
425 LOG(FATAL) << "Successor " << blockName1 << "not found from "
426 << blockName2;
427 }
428 }
429 return true;
buzbee67bf8852011-08-17 17:51:35 -0700430}
431
432/* Identify code range in try blocks and set up the empty catch blocks */
buzbee31a4a6f2012-02-28 15:36:15 -0800433void processTryCatchBlocks(CompilationUnit* cUnit)
buzbee67bf8852011-08-17 17:51:35 -0700434{
Bill Buzbeea114add2012-05-03 15:00:40 -0700435 const DexFile::CodeItem* code_item = cUnit->code_item;
436 int triesSize = code_item->tries_size_;
437 int offset;
buzbee67bf8852011-08-17 17:51:35 -0700438
Bill Buzbeea114add2012-05-03 15:00:40 -0700439 if (triesSize == 0) {
440 return;
441 }
442
443 ArenaBitVector* tryBlockAddr = cUnit->tryBlockAddr;
444
445 for (int i = 0; i < triesSize; i++) {
446 const DexFile::TryItem* pTry =
447 DexFile::GetTryItems(*code_item, i);
448 int startOffset = pTry->start_addr_;
449 int endOffset = startOffset + pTry->insn_count_;
450 for (offset = startOffset; offset < endOffset; offset++) {
451 oatSetBit(cUnit, tryBlockAddr, offset);
buzbee67bf8852011-08-17 17:51:35 -0700452 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700453 }
buzbee67bf8852011-08-17 17:51:35 -0700454
Bill Buzbeea114add2012-05-03 15:00:40 -0700455 // Iterate over each of the handlers to enqueue the empty Catch blocks
456 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
457 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
458 for (uint32_t idx = 0; idx < handlers_size; idx++) {
459 CatchHandlerIterator iterator(handlers_ptr);
460 for (; iterator.HasNext(); iterator.Next()) {
461 uint32_t address = iterator.GetHandlerAddress();
462 findBlock(cUnit, address, false /* split */, true /*create*/,
463 /* immedPredBlockP */ NULL);
buzbee67bf8852011-08-17 17:51:35 -0700464 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700465 handlers_ptr = iterator.EndDataPointer();
466 }
buzbee67bf8852011-08-17 17:51:35 -0700467}
468
Elliott Hughesadb8c672012-03-06 16:49:32 -0800469/* Process instructions with the kBranch flag */
buzbee31a4a6f2012-02-28 15:36:15 -0800470BasicBlock* processCanBranch(CompilationUnit* cUnit, BasicBlock* curBlock,
Bill Buzbeea114add2012-05-03 15:00:40 -0700471 MIR* insn, int curOffset, int width, int flags,
472 const u2* codePtr, const u2* codeEnd)
buzbee67bf8852011-08-17 17:51:35 -0700473{
Bill Buzbeea114add2012-05-03 15:00:40 -0700474 int target = curOffset;
475 switch (insn->dalvikInsn.opcode) {
476 case Instruction::GOTO:
477 case Instruction::GOTO_16:
478 case Instruction::GOTO_32:
479 target += (int) insn->dalvikInsn.vA;
480 break;
481 case Instruction::IF_EQ:
482 case Instruction::IF_NE:
483 case Instruction::IF_LT:
484 case Instruction::IF_GE:
485 case Instruction::IF_GT:
486 case Instruction::IF_LE:
487 target += (int) insn->dalvikInsn.vC;
488 break;
489 case Instruction::IF_EQZ:
490 case Instruction::IF_NEZ:
491 case Instruction::IF_LTZ:
492 case Instruction::IF_GEZ:
493 case Instruction::IF_GTZ:
494 case Instruction::IF_LEZ:
495 target += (int) insn->dalvikInsn.vB;
496 break;
497 default:
498 LOG(FATAL) << "Unexpected opcode(" << (int)insn->dalvikInsn.opcode
499 << ") with kBranch set";
500 }
501 BasicBlock *takenBlock = findBlock(cUnit, target,
502 /* split */
503 true,
504 /* create */
505 true,
506 /* immedPredBlockP */
507 &curBlock);
508 curBlock->taken = takenBlock;
509 oatInsertGrowableList(cUnit, takenBlock->predecessors, (intptr_t)curBlock);
buzbee67bf8852011-08-17 17:51:35 -0700510
Bill Buzbeea114add2012-05-03 15:00:40 -0700511 /* Always terminate the current block for conditional branches */
512 if (flags & Instruction::kContinue) {
513 BasicBlock *fallthroughBlock = findBlock(cUnit,
514 curOffset + width,
515 /*
516 * If the method is processed
517 * in sequential order from the
518 * beginning, we don't need to
519 * specify split for continue
520 * blocks. However, this
521 * routine can be called by
522 * compileLoop, which starts
523 * parsing the method from an
524 * arbitrary address in the
525 * method body.
526 */
527 true,
528 /* create */
529 true,
530 /* immedPredBlockP */
531 &curBlock);
532 curBlock->fallThrough = fallthroughBlock;
533 oatInsertGrowableList(cUnit, fallthroughBlock->predecessors,
534 (intptr_t)curBlock);
535 } else if (codePtr < codeEnd) {
536 /* Create a fallthrough block for real instructions (incl. NOP) */
537 if (contentIsInsn(codePtr)) {
538 findBlock(cUnit, curOffset + width,
539 /* split */
540 false,
541 /* create */
542 true,
543 /* immedPredBlockP */
544 NULL);
buzbee67bf8852011-08-17 17:51:35 -0700545 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700546 }
547 return curBlock;
buzbee67bf8852011-08-17 17:51:35 -0700548}
549
Elliott Hughesadb8c672012-03-06 16:49:32 -0800550/* Process instructions with the kSwitch flag */
buzbee31a4a6f2012-02-28 15:36:15 -0800551void processCanSwitch(CompilationUnit* cUnit, BasicBlock* curBlock,
552 MIR* insn, int curOffset, int width, int flags)
buzbee67bf8852011-08-17 17:51:35 -0700553{
Bill Buzbeea114add2012-05-03 15:00:40 -0700554 u2* switchData= (u2 *) (cUnit->insns + curOffset + insn->dalvikInsn.vB);
555 int size;
556 int* keyTable;
557 int* targetTable;
558 int i;
559 int firstKey;
buzbee67bf8852011-08-17 17:51:35 -0700560
Bill Buzbeea114add2012-05-03 15:00:40 -0700561 /*
562 * Packed switch data format:
563 * ushort ident = 0x0100 magic value
564 * ushort size number of entries in the table
565 * int first_key first (and lowest) switch case value
566 * int targets[size] branch targets, relative to switch opcode
567 *
568 * Total size is (4+size*2) 16-bit code units.
569 */
570 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
571 DCHECK_EQ(static_cast<int>(switchData[0]),
572 static_cast<int>(Instruction::kPackedSwitchSignature));
573 size = switchData[1];
574 firstKey = switchData[2] | (switchData[3] << 16);
575 targetTable = (int *) &switchData[4];
576 keyTable = NULL; // Make the compiler happy
577 /*
578 * Sparse switch data format:
579 * ushort ident = 0x0200 magic value
580 * ushort size number of entries in the table; > 0
581 * int keys[size] keys, sorted low-to-high; 32-bit aligned
582 * int targets[size] branch targets, relative to switch opcode
583 *
584 * Total size is (2+size*4) 16-bit code units.
585 */
586 } else {
587 DCHECK_EQ(static_cast<int>(switchData[0]),
588 static_cast<int>(Instruction::kSparseSwitchSignature));
589 size = switchData[1];
590 keyTable = (int *) &switchData[2];
591 targetTable = (int *) &switchData[2 + size*2];
592 firstKey = 0; // To make the compiler happy
593 }
buzbee67bf8852011-08-17 17:51:35 -0700594
Bill Buzbeea114add2012-05-03 15:00:40 -0700595 if (curBlock->successorBlockList.blockListType != kNotUsed) {
596 LOG(FATAL) << "Successor block list already in use: "
597 << (int)curBlock->successorBlockList.blockListType;
598 }
599 curBlock->successorBlockList.blockListType =
600 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
601 kPackedSwitch : kSparseSwitch;
602 oatInitGrowableList(cUnit, &curBlock->successorBlockList.blocks, size,
603 kListSuccessorBlocks);
604
605 for (i = 0; i < size; i++) {
606 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
607 /* split */
608 true,
609 /* create */
610 true,
611 /* immedPredBlockP */
612 &curBlock);
613 SuccessorBlockInfo *successorBlockInfo =
614 (SuccessorBlockInfo *) oatNew(cUnit, sizeof(SuccessorBlockInfo),
615 false, kAllocSuccessor);
616 successorBlockInfo->block = caseBlock;
617 successorBlockInfo->key =
Elliott Hughesadb8c672012-03-06 16:49:32 -0800618 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
Bill Buzbeea114add2012-05-03 15:00:40 -0700619 firstKey + i : keyTable[i];
620 oatInsertGrowableList(cUnit, &curBlock->successorBlockList.blocks,
621 (intptr_t) successorBlockInfo);
622 oatInsertGrowableList(cUnit, caseBlock->predecessors,
buzbeeba938cb2012-02-03 14:47:55 -0800623 (intptr_t)curBlock);
Bill Buzbeea114add2012-05-03 15:00:40 -0700624 }
625
626 /* Fall-through case */
627 BasicBlock* fallthroughBlock = findBlock(cUnit,
628 curOffset + width,
629 /* split */
630 false,
631 /* create */
632 true,
633 /* immedPredBlockP */
634 NULL);
635 curBlock->fallThrough = fallthroughBlock;
636 oatInsertGrowableList(cUnit, fallthroughBlock->predecessors,
637 (intptr_t)curBlock);
buzbee67bf8852011-08-17 17:51:35 -0700638}
639
Elliott Hughesadb8c672012-03-06 16:49:32 -0800640/* Process instructions with the kThrow flag */
buzbee31a4a6f2012-02-28 15:36:15 -0800641void processCanThrow(CompilationUnit* cUnit, BasicBlock* curBlock, MIR* insn,
642 int curOffset, int width, int flags,
643 ArenaBitVector* tryBlockAddr, const u2* codePtr,
644 const u2* codeEnd)
buzbee67bf8852011-08-17 17:51:35 -0700645{
Bill Buzbeea114add2012-05-03 15:00:40 -0700646 const DexFile::CodeItem* code_item = cUnit->code_item;
buzbee67bf8852011-08-17 17:51:35 -0700647
Bill Buzbeea114add2012-05-03 15:00:40 -0700648 /* In try block */
649 if (oatIsBitSet(tryBlockAddr, curOffset)) {
650 CatchHandlerIterator iterator(*code_item, curOffset);
buzbee67bf8852011-08-17 17:51:35 -0700651
Bill Buzbeea114add2012-05-03 15:00:40 -0700652 if (curBlock->successorBlockList.blockListType != kNotUsed) {
653 LOG(FATAL) << "Successor block list already in use: "
654 << (int)curBlock->successorBlockList.blockListType;
buzbee67bf8852011-08-17 17:51:35 -0700655 }
656
Bill Buzbeea114add2012-05-03 15:00:40 -0700657 curBlock->successorBlockList.blockListType = kCatch;
658 oatInitGrowableList(cUnit, &curBlock->successorBlockList.blocks, 2,
659 kListSuccessorBlocks);
660
661 for (;iterator.HasNext(); iterator.Next()) {
662 BasicBlock *catchBlock = findBlock(cUnit, iterator.GetHandlerAddress(),
663 false /* split*/,
664 false /* creat */,
665 NULL /* immedPredBlockP */);
666 catchBlock->catchEntry = true;
667 SuccessorBlockInfo *successorBlockInfo = (SuccessorBlockInfo *)
668 oatNew(cUnit, sizeof(SuccessorBlockInfo), false, kAllocSuccessor);
669 successorBlockInfo->block = catchBlock;
670 successorBlockInfo->key = iterator.GetHandlerTypeIndex();
671 oatInsertGrowableList(cUnit, &curBlock->successorBlockList.blocks,
672 (intptr_t) successorBlockInfo);
673 oatInsertGrowableList(cUnit, catchBlock->predecessors,
674 (intptr_t)curBlock);
buzbee67bf8852011-08-17 17:51:35 -0700675 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700676 } else {
677 BasicBlock *ehBlock = oatNewBB(cUnit, kExceptionHandling,
678 cUnit->numBlocks++);
679 curBlock->taken = ehBlock;
680 oatInsertGrowableList(cUnit, &cUnit->blockList, (intptr_t) ehBlock);
681 ehBlock->startOffset = curOffset;
682 oatInsertGrowableList(cUnit, ehBlock->predecessors, (intptr_t)curBlock);
683 }
684
685 /*
686 * Force the current block to terminate.
687 *
688 * Data may be present before codeEnd, so we need to parse it to know
689 * whether it is code or data.
690 */
691 if (codePtr < codeEnd) {
692 /* Create a fallthrough block for real instructions (incl. NOP) */
693 if (contentIsInsn(codePtr)) {
694 BasicBlock *fallthroughBlock = findBlock(cUnit,
695 curOffset + width,
696 /* split */
697 false,
698 /* create */
699 true,
700 /* immedPredBlockP */
701 NULL);
702 /*
703 * THROW is an unconditional branch. NOTE:
704 * THROW_VERIFICATION_ERROR is also an unconditional
705 * branch, but we shouldn't treat it as such until we have
706 * a dead code elimination pass (which won't be important
buzbee2cfc6392012-05-07 14:51:40 -0700707 * until inlining w/ constant propagation is implemented.
Bill Buzbeea114add2012-05-03 15:00:40 -0700708 */
709 if (insn->dalvikInsn.opcode != Instruction::THROW) {
710 curBlock->fallThrough = fallthroughBlock;
711 oatInsertGrowableList(cUnit, fallthroughBlock->predecessors,
712 (intptr_t)curBlock);
713 }
714 }
715 }
buzbee67bf8852011-08-17 17:51:35 -0700716}
717
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800718void oatInit(CompilationUnit* cUnit, const Compiler& compiler) {
719 if (!oatArchInit()) {
720 LOG(FATAL) << "Failed to initialize oat";
721 }
722 if (!oatHeapInit(cUnit)) {
723 LOG(FATAL) << "Failed to initialize oat heap";
724 }
725}
726
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700727CompiledMethod* oatCompileMethod(Compiler& compiler,
728 const DexFile::CodeItem* code_item,
729 uint32_t access_flags, uint32_t method_idx,
730 const ClassLoader* class_loader,
731 const DexFile& dex_file)
buzbee67bf8852011-08-17 17:51:35 -0700732{
Bill Buzbeea114add2012-05-03 15:00:40 -0700733 VLOG(compiler) << "Compiling " << PrettyMethod(method_idx, dex_file) << "...";
Brian Carlstrom94496d32011-08-22 09:22:47 -0700734
Bill Buzbeea114add2012-05-03 15:00:40 -0700735 const u2* codePtr = code_item->insns_;
736 const u2* codeEnd = code_item->insns_ + code_item->insns_size_in_code_units_;
737 int numBlocks = 0;
738 unsigned int curOffset = 0;
buzbee67bf8852011-08-17 17:51:35 -0700739
Bill Buzbeea114add2012-05-03 15:00:40 -0700740 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
741 UniquePtr<CompilationUnit> cUnit(new CompilationUnit);
buzbeeba938cb2012-02-03 14:47:55 -0800742
Bill Buzbeea114add2012-05-03 15:00:40 -0700743 oatInit(cUnit.get(), compiler);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800744
Bill Buzbeea114add2012-05-03 15:00:40 -0700745 cUnit->compiler = &compiler;
746 cUnit->class_linker = class_linker;
747 cUnit->dex_file = &dex_file;
748 cUnit->dex_cache = class_linker->FindDexCache(dex_file);
749 cUnit->method_idx = method_idx;
750 cUnit->code_item = code_item;
751 cUnit->access_flags = access_flags;
752 cUnit->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
753 cUnit->instructionSet = compiler.GetInstructionSet();
754 cUnit->insns = code_item->insns_;
755 cUnit->insnsSize = code_item->insns_size_in_code_units_;
756 cUnit->numIns = code_item->ins_size_;
757 cUnit->numRegs = code_item->registers_size_ - cUnit->numIns;
758 cUnit->numOuts = code_item->outs_size_;
buzbee2cfc6392012-05-07 14:51:40 -0700759#if defined(ART_USE_QUICK_COMPILER)
buzbee6969d502012-06-15 16:40:31 -0700760 if ((PrettyMethod(method_idx, dex_file).find("fibonacci") != std::string::npos)
761 || (PrettyMethod(method_idx, dex_file).find("HelloWorld") != std::string::npos)
762 ) {
763 cUnit->genBitcode = true;
764 }
buzbee2cfc6392012-05-07 14:51:40 -0700765#endif
Bill Buzbeea114add2012-05-03 15:00:40 -0700766 /* Adjust this value accordingly once inlining is performed */
767 cUnit->numDalvikRegisters = code_item->registers_size_;
768 // TODO: set this from command line
769 cUnit->compilerFlipMatch = false;
770 bool useMatch = !cUnit->compilerMethodMatch.empty();
771 bool match = useMatch && (cUnit->compilerFlipMatch ^
772 (PrettyMethod(method_idx, dex_file).find(cUnit->compilerMethodMatch) !=
773 std::string::npos));
774 if (!useMatch || match) {
775 cUnit->disableOpt = kCompilerOptimizerDisableFlags;
776 cUnit->enableDebug = kCompilerDebugFlags;
777 cUnit->printMe = VLOG_IS_ON(compiler) ||
778 (cUnit->enableDebug & (1 << kDebugVerbose));
779 }
buzbee2cfc6392012-05-07 14:51:40 -0700780#if defined(ART_USE_QUICK_COMPILER)
buzbee6969d502012-06-15 16:40:31 -0700781 if (cUnit->genBitcode) {
782 cUnit->printMe = true;
buzbeead8f15e2012-06-18 14:49:45 -0700783 cUnit->enableDebug |= (1 << kDebugDumpBitcodeFile);
buzbee6969d502012-06-15 16:40:31 -0700784 }
buzbee2cfc6392012-05-07 14:51:40 -0700785#endif
Bill Buzbeea114add2012-05-03 15:00:40 -0700786 if (cUnit->instructionSet == kX86) {
787 // Disable optimizations on X86 for now
788 cUnit->disableOpt = -1;
789 }
790 /* Are we generating code for the debugger? */
791 if (compiler.IsDebuggingSupported()) {
792 cUnit->genDebugger = true;
793 // Yes, disable most optimizations
794 cUnit->disableOpt |= (
795 (1 << kLoadStoreElimination) |
796 (1 << kLoadHoisting) |
797 (1 << kSuppressLoads) |
798 (1 << kPromoteRegs) |
799 (1 << kBBOpt) |
800 (1 << kMatch) |
801 (1 << kTrackLiveTemps));
802 }
803
804 /* Gathering opcode stats? */
805 if (kCompilerDebugFlags & (1 << kDebugCountOpcodes)) {
806 cUnit->opcodeCount = (int*)oatNew(cUnit.get(),
807 kNumPackedOpcodes * sizeof(int), true, kAllocMisc);
808 }
809
810 /* Assume non-throwing leaf */
811 cUnit->attrs = (METHOD_IS_LEAF | METHOD_IS_THROW_FREE);
812
813 /* Initialize the block list, estimate size based on insnsSize */
814 oatInitGrowableList(cUnit.get(), &cUnit->blockList, cUnit->insnsSize,
815 kListBlockList);
816
817 /* Initialize the switchTables list */
818 oatInitGrowableList(cUnit.get(), &cUnit->switchTables, 4,
819 kListSwitchTables);
820
821 /* Intialize the fillArrayData list */
822 oatInitGrowableList(cUnit.get(), &cUnit->fillArrayData, 4,
823 kListFillArrayData);
824
825 /* Intialize the throwLaunchpads list, estimate size based on insnsSize */
826 oatInitGrowableList(cUnit.get(), &cUnit->throwLaunchpads, cUnit->insnsSize,
827 kListThrowLaunchPads);
828
829 /* Intialize the instrinsicLaunchpads list */
830 oatInitGrowableList(cUnit.get(), &cUnit->intrinsicLaunchpads, 4,
831 kListMisc);
832
833
834 /* Intialize the suspendLaunchpads list */
835 oatInitGrowableList(cUnit.get(), &cUnit->suspendLaunchpads, 2048,
836 kListSuspendLaunchPads);
837
838 /* Allocate the bit-vector to track the beginning of basic blocks */
839 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit.get(),
840 cUnit->insnsSize,
841 true /* expandable */);
842 cUnit->tryBlockAddr = tryBlockAddr;
843
844 /* Create the default entry and exit blocks and enter them to the list */
845 BasicBlock *entryBlock = oatNewBB(cUnit.get(), kEntryBlock, numBlocks++);
846 BasicBlock *exitBlock = oatNewBB(cUnit.get(), kExitBlock, numBlocks++);
847
848 cUnit->entryBlock = entryBlock;
849 cUnit->exitBlock = exitBlock;
850
851 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) entryBlock);
852 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) exitBlock);
853
854 /* Current block to record parsed instructions */
855 BasicBlock *curBlock = oatNewBB(cUnit.get(), kDalvikByteCode, numBlocks++);
856 curBlock->startOffset = 0;
857 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) curBlock);
858 /* Add first block to the fast lookup cache */
859 cUnit->blockMap.Put(curBlock->startOffset, curBlock);
860 entryBlock->fallThrough = curBlock;
861 oatInsertGrowableList(cUnit.get(), curBlock->predecessors,
862 (intptr_t)entryBlock);
863
864 /*
865 * Store back the number of blocks since new blocks may be created of
866 * accessing cUnit.
867 */
868 cUnit->numBlocks = numBlocks;
869
870 /* Identify code range in try blocks and set up the empty catch blocks */
871 processTryCatchBlocks(cUnit.get());
872
873 /* Set up for simple method detection */
874 int numPatterns = sizeof(specialPatterns)/sizeof(specialPatterns[0]);
875 bool livePattern = (numPatterns > 0) && !(cUnit->disableOpt & (1 << kMatch));
Elliott Hughesabe64aa2012-05-30 17:34:45 -0700876 bool* deadPattern = (bool*)oatNew(cUnit.get(), sizeof(bool) * numPatterns, true,
Bill Buzbeea114add2012-05-03 15:00:40 -0700877 kAllocMisc);
878 SpecialCaseHandler specialCase = kNoHandler;
879 int patternPos = 0;
880
881 /* Parse all instructions and put them into containing basic blocks */
882 while (codePtr < codeEnd) {
883 MIR *insn = (MIR *) oatNew(cUnit.get(), sizeof(MIR), true, kAllocMIR);
884 insn->offset = curOffset;
885 int width = parseInsn(cUnit.get(), codePtr, &insn->dalvikInsn, false);
886 insn->width = width;
887 Instruction::Code opcode = insn->dalvikInsn.opcode;
888 if (cUnit->opcodeCount != NULL) {
889 cUnit->opcodeCount[static_cast<int>(opcode)]++;
buzbee44b412b2012-02-04 08:50:53 -0800890 }
891
Bill Buzbeea114add2012-05-03 15:00:40 -0700892 /* Terminate when the data section is seen */
893 if (width == 0)
894 break;
895
896 /* Possible simple method? */
897 if (livePattern) {
898 livePattern = false;
899 specialCase = kNoHandler;
900 for (int i = 0; i < numPatterns; i++) {
901 if (!deadPattern[i]) {
902 if (specialPatterns[i].opcodes[patternPos] == opcode) {
903 livePattern = true;
904 specialCase = specialPatterns[i].handlerCode;
905 } else {
906 deadPattern[i] = true;
907 }
908 }
909 }
910 patternPos++;
buzbeea7c12682012-03-19 13:13:53 -0700911 }
912
Bill Buzbeea114add2012-05-03 15:00:40 -0700913 oatAppendMIR(curBlock, insn);
buzbeecefd1872011-09-09 09:59:52 -0700914
Bill Buzbeea114add2012-05-03 15:00:40 -0700915 codePtr += width;
916 int flags = Instruction::Flags(insn->dalvikInsn.opcode);
buzbee67bf8852011-08-17 17:51:35 -0700917
Bill Buzbeea114add2012-05-03 15:00:40 -0700918 int dfFlags = oatDataFlowAttributes[insn->dalvikInsn.opcode];
buzbee67bf8852011-08-17 17:51:35 -0700919
Bill Buzbeea114add2012-05-03 15:00:40 -0700920 if (dfFlags & DF_HAS_DEFS) {
buzbeebff24652012-05-06 16:22:05 -0700921 cUnit->defCount += (dfFlags & DF_A_WIDE) ? 2 : 1;
Bill Buzbeea114add2012-05-03 15:00:40 -0700922 }
buzbee67bf8852011-08-17 17:51:35 -0700923
Bill Buzbeea114add2012-05-03 15:00:40 -0700924 if (flags & Instruction::kBranch) {
925 curBlock = processCanBranch(cUnit.get(), curBlock, insn, curOffset,
926 width, flags, codePtr, codeEnd);
927 } else if (flags & Instruction::kReturn) {
928 curBlock->fallThrough = exitBlock;
929 oatInsertGrowableList(cUnit.get(), exitBlock->predecessors,
930 (intptr_t)curBlock);
931 /*
932 * Terminate the current block if there are instructions
933 * afterwards.
934 */
935 if (codePtr < codeEnd) {
936 /*
937 * Create a fallthrough block for real instructions
938 * (incl. NOP).
939 */
940 if (contentIsInsn(codePtr)) {
941 findBlock(cUnit.get(), curOffset + width,
942 /* split */
943 false,
944 /* create */
945 true,
946 /* immedPredBlockP */
947 NULL);
948 }
949 }
950 } else if (flags & Instruction::kThrow) {
951 processCanThrow(cUnit.get(), curBlock, insn, curOffset, width, flags,
952 tryBlockAddr, codePtr, codeEnd);
953 } else if (flags & Instruction::kSwitch) {
954 processCanSwitch(cUnit.get(), curBlock, insn, curOffset, width, flags);
955 }
956 curOffset += width;
957 BasicBlock *nextBlock = findBlock(cUnit.get(), curOffset,
958 /* split */
959 false,
960 /* create */
961 false,
962 /* immedPredBlockP */
963 NULL);
964 if (nextBlock) {
965 /*
966 * The next instruction could be the target of a previously parsed
967 * forward branch so a block is already created. If the current
968 * instruction is not an unconditional branch, connect them through
969 * the fall-through link.
970 */
971 DCHECK(curBlock->fallThrough == NULL ||
972 curBlock->fallThrough == nextBlock ||
973 curBlock->fallThrough == exitBlock);
buzbee5ade1d22011-09-09 14:44:52 -0700974
Bill Buzbeea114add2012-05-03 15:00:40 -0700975 if ((curBlock->fallThrough == NULL) && (flags & Instruction::kContinue)) {
976 curBlock->fallThrough = nextBlock;
977 oatInsertGrowableList(cUnit.get(), nextBlock->predecessors,
978 (intptr_t)curBlock);
979 }
980 curBlock = nextBlock;
981 }
982 }
buzbeefc9e6fa2012-03-23 15:14:29 -0700983
Bill Buzbeea114add2012-05-03 15:00:40 -0700984 if (!(cUnit->disableOpt & (1 << kSkipLargeMethodOptimization))) {
985 if ((cUnit->numBlocks > MANY_BLOCKS) ||
986 ((cUnit->numBlocks > MANY_BLOCKS_INITIALIZER) &&
987 PrettyMethod(method_idx, dex_file, false).find("init>") !=
988 std::string::npos)) {
989 cUnit->qdMode = true;
990 }
991 }
buzbeefc9e6fa2012-03-23 15:14:29 -0700992
buzbee2cfc6392012-05-07 14:51:40 -0700993#if defined(ART_USE_QUICK_COMPILER)
994 if (cUnit->genBitcode) {
995 // Bitcode generation requires full dataflow analysis, no qdMode
996 cUnit->qdMode = false;
997 }
998#endif
999
Bill Buzbeea114add2012-05-03 15:00:40 -07001000 if (cUnit->qdMode) {
1001 cUnit->disableDataflow = true;
1002 // Disable optimization which require dataflow/ssa
1003 cUnit->disableOpt |=
1004 (1 << kNullCheckElimination) |
1005 (1 << kBBOpt) |
1006 (1 << kPromoteRegs);
1007 if (cUnit->printMe) {
1008 LOG(INFO) << "QD mode enabled: "
1009 << PrettyMethod(method_idx, dex_file)
1010 << " too big: " << cUnit->numBlocks;
1011 }
1012 }
buzbeec1f45042011-09-21 16:03:19 -07001013
Bill Buzbeea114add2012-05-03 15:00:40 -07001014 if (cUnit->printMe) {
1015 oatDumpCompilationUnit(cUnit.get());
1016 }
buzbee67bf8852011-08-17 17:51:35 -07001017
Bill Buzbeea114add2012-05-03 15:00:40 -07001018 if (cUnit->enableDebug & (1 << kDebugVerifyDataflow)) {
1019 /* Verify if all blocks are connected as claimed */
1020 oatDataFlowAnalysisDispatcher(cUnit.get(), verifyPredInfo, kAllNodes,
1021 false /* isIterative */);
1022 }
buzbee67bf8852011-08-17 17:51:35 -07001023
Bill Buzbeea114add2012-05-03 15:00:40 -07001024 /* Perform SSA transformation for the whole method */
1025 oatMethodSSATransformation(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001026
buzbee2cfc6392012-05-07 14:51:40 -07001027 /* Do constant propagation */
1028 // TODO: Probably need to make these expandable to support new ssa names
1029 // introducted during MIR optimization passes
1030 cUnit->isConstantV = oatAllocBitVector(cUnit.get(), cUnit->numSSARegs,
1031 false /* not expandable */);
1032 cUnit->constantValues =
1033 (int*)oatNew(cUnit.get(), sizeof(int) * cUnit->numSSARegs, true,
1034 kAllocDFInfo);
1035 oatDataFlowAnalysisDispatcher(cUnit.get(), oatDoConstantPropagation,
1036 kAllNodes,
1037 false /* isIterative */);
1038
Bill Buzbeea114add2012-05-03 15:00:40 -07001039 /* Detect loops */
1040 oatMethodLoopDetection(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001041
Bill Buzbeea114add2012-05-03 15:00:40 -07001042 /* Count uses */
1043 oatMethodUseCount(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001044
Bill Buzbeea114add2012-05-03 15:00:40 -07001045 /* Perform null check elimination */
1046 oatMethodNullCheckElimination(cUnit.get());
1047
1048 /* Do some basic block optimizations */
1049 oatMethodBasicBlockOptimization(cUnit.get());
1050
1051 oatInitializeRegAlloc(cUnit.get()); // Needs to happen after SSA naming
1052
1053 /* Allocate Registers using simple local allocation scheme */
1054 oatSimpleRegAlloc(cUnit.get());
1055
buzbee2cfc6392012-05-07 14:51:40 -07001056#if defined(ART_USE_QUICK_COMPILER)
1057 /* Go the LLVM path? */
1058 if (cUnit->genBitcode) {
1059 // MIR->Bitcode
1060 oatMethodMIR2Bitcode(cUnit.get());
1061 // Bitcode->LIR
1062 oatMethodBitcode2LIR(cUnit.get());
1063 } else {
1064#endif
1065 if (specialCase != kNoHandler) {
1066 /*
1067 * Custom codegen for special cases. If for any reason the
1068 * special codegen doesn't succeed, cUnit->firstLIRInsn will
1069 * set to NULL;
1070 */
1071 oatSpecialMIR2LIR(cUnit.get(), specialCase);
1072 }
buzbee67bf8852011-08-17 17:51:35 -07001073
buzbee2cfc6392012-05-07 14:51:40 -07001074 /* Convert MIR to LIR, etc. */
1075 if (cUnit->firstLIRInsn == NULL) {
1076 oatMethodMIR2LIR(cUnit.get());
1077 }
1078#if defined(ART_USE_QUICK_COMPILER)
Bill Buzbeea114add2012-05-03 15:00:40 -07001079 }
buzbee2cfc6392012-05-07 14:51:40 -07001080#endif
buzbee67bf8852011-08-17 17:51:35 -07001081
Bill Buzbeea114add2012-05-03 15:00:40 -07001082 // Debugging only
1083 if (cUnit->enableDebug & (1 << kDebugDumpCFG)) {
1084 oatDumpCFG(cUnit.get(), "/sdcard/cfg/");
1085 }
buzbee16da88c2012-03-20 10:38:17 -07001086
Bill Buzbeea114add2012-05-03 15:00:40 -07001087 /* Method is not empty */
1088 if (cUnit->firstLIRInsn) {
buzbee67bf8852011-08-17 17:51:35 -07001089
Bill Buzbeea114add2012-05-03 15:00:40 -07001090 // mark the targets of switch statement case labels
1091 oatProcessSwitchTables(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001092
Bill Buzbeea114add2012-05-03 15:00:40 -07001093 /* Convert LIR into machine code. */
1094 oatAssembleLIR(cUnit.get());
buzbee99ba9642012-01-25 14:23:14 -08001095
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07001096 if (cUnit->printMe) {
Bill Buzbeea114add2012-05-03 15:00:40 -07001097 oatCodegenDump(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001098 }
1099
Bill Buzbeea114add2012-05-03 15:00:40 -07001100 if (cUnit->opcodeCount != NULL) {
1101 LOG(INFO) << "Opcode Count";
1102 for (int i = 0; i < kNumPackedOpcodes; i++) {
1103 if (cUnit->opcodeCount[i] != 0) {
1104 LOG(INFO) << "-C- "
1105 << Instruction::Name(static_cast<Instruction::Code>(i))
1106 << " " << cUnit->opcodeCount[i];
buzbee67bf8852011-08-17 17:51:35 -07001107 }
Bill Buzbeea114add2012-05-03 15:00:40 -07001108 }
1109 }
1110 }
buzbeea7c12682012-03-19 13:13:53 -07001111
Bill Buzbeea114add2012-05-03 15:00:40 -07001112 // Combine vmap tables - core regs, then fp regs - into vmapTable
1113 std::vector<uint16_t> vmapTable;
1114 for (size_t i = 0 ; i < cUnit->coreVmapTable.size(); i++) {
1115 vmapTable.push_back(cUnit->coreVmapTable[i]);
1116 }
1117 // If we have a frame, push a marker to take place of lr
1118 if (cUnit->frameSize > 0) {
1119 vmapTable.push_back(INVALID_VREG);
1120 } else {
1121 DCHECK_EQ(__builtin_popcount(cUnit->coreSpillMask), 0);
1122 DCHECK_EQ(__builtin_popcount(cUnit->fpSpillMask), 0);
1123 }
1124 // Combine vmap tables - core regs, then fp regs
1125 for (uint32_t i = 0; i < cUnit->fpVmapTable.size(); i++) {
1126 vmapTable.push_back(cUnit->fpVmapTable[i]);
1127 }
1128 CompiledMethod* result =
1129 new CompiledMethod(cUnit->instructionSet, cUnit->codeBuffer,
1130 cUnit->frameSize, cUnit->coreSpillMask,
1131 cUnit->fpSpillMask, cUnit->mappingTable, vmapTable);
buzbee67bf8852011-08-17 17:51:35 -07001132
Bill Buzbeea114add2012-05-03 15:00:40 -07001133 VLOG(compiler) << "Compiled " << PrettyMethod(method_idx, dex_file)
1134 << " (" << (cUnit->codeBuffer.size() * sizeof(cUnit->codeBuffer[0]))
1135 << " bytes)";
buzbee5abfa3e2012-01-31 17:01:43 -08001136
1137#ifdef WITH_MEMSTATS
Bill Buzbeea114add2012-05-03 15:00:40 -07001138 if (cUnit->enableDebug & (1 << kDebugShowMemoryUsage)) {
1139 oatDumpMemStats(cUnit.get());
1140 }
buzbee5abfa3e2012-01-31 17:01:43 -08001141#endif
buzbee67bf8852011-08-17 17:51:35 -07001142
Bill Buzbeea114add2012-05-03 15:00:40 -07001143 oatArenaReset(cUnit.get());
buzbeeba938cb2012-02-03 14:47:55 -08001144
Bill Buzbeea114add2012-05-03 15:00:40 -07001145 return result;
buzbee67bf8852011-08-17 17:51:35 -07001146}
1147
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001148} // namespace art
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001149
Bill Buzbeea114add2012-05-03 15:00:40 -07001150extern "C" art::CompiledMethod*
1151 ArtCompileMethod(art::Compiler& compiler,
1152 const art::DexFile::CodeItem* code_item,
1153 uint32_t access_flags, uint32_t method_idx,
1154 const art::ClassLoader* class_loader,
1155 const art::DexFile& dex_file)
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001156{
1157 CHECK_EQ(compiler.GetInstructionSet(), art::oatInstructionSet());
Bill Buzbeea114add2012-05-03 15:00:40 -07001158 return art::oatCompileMethod(compiler, code_item, access_flags, method_idx,
1159 class_loader, dex_file);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001160}