blob: 140f6811f3558acab95b3f7cfa17343c5c66914f [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)
buzbee4f1181f2012-06-22 13:52:12 -0700760 // TODO: remove - temp for Quick compiler bring-up
buzbee6969d502012-06-15 16:40:31 -0700761 if ((PrettyMethod(method_idx, dex_file).find("fibonacci") != std::string::npos)
762 || (PrettyMethod(method_idx, dex_file).find("HelloWorld") != std::string::npos)
buzbee4f1181f2012-06-22 13:52:12 -0700763 || (PrettyMethod(method_idx, dex_file).find("count10_006") != std::string::npos)
buzbee32412962012-06-26 16:27:56 -0700764 || (PrettyMethod(method_idx, dex_file).find("exceptions_007") != std::string::npos)
765 || (PrettyMethod(method_idx, dex_file).find("catchAndRethrow") != std::string::npos)
766 || (PrettyMethod(method_idx, dex_file).find("throwNullPointerException") != std::string::npos)
buzbee4f1181f2012-06-22 13:52:12 -0700767 || (PrettyMethod(method_idx, dex_file).find("math_012") != std::string::npos)
768 || (PrettyMethod(method_idx, dex_file).find("math_013") != std::string::npos)
buzbee32412962012-06-26 16:27:56 -0700769 || (PrettyMethod(method_idx, dex_file).find("math_014") != std::string::npos)
buzbee4f1181f2012-06-22 13:52:12 -0700770 || (PrettyMethod(method_idx, dex_file).find("float_017") != std::string::npos)
buzbee8fa0fda2012-06-27 15:44:52 -0700771 || (PrettyMethod(method_idx, dex_file).find("array_028") != std::string::npos)
772 || (PrettyMethod(method_idx, dex_file).find("writeArray") != std::string::npos)
773 || (PrettyMethod(method_idx, dex_file).find("writeTest") != std::string::npos)
774 || (PrettyMethod(method_idx, dex_file).find("copyTest") != std::string::npos)
buzbee101305f2012-06-28 18:00:56 -0700775 || (PrettyMethod(method_idx, dex_file).find("shiftTest1") != std::string::npos)
776 || (PrettyMethod(method_idx, dex_file).find("shiftTest2") != std::string::npos)
777 || (PrettyMethod(method_idx, dex_file).find("unsignedShiftTest") != std::string::npos)
buzbee6969d502012-06-15 16:40:31 -0700778 ) {
779 cUnit->genBitcode = true;
780 }
buzbee2cfc6392012-05-07 14:51:40 -0700781#endif
Bill Buzbeea114add2012-05-03 15:00:40 -0700782 /* Adjust this value accordingly once inlining is performed */
783 cUnit->numDalvikRegisters = code_item->registers_size_;
784 // TODO: set this from command line
785 cUnit->compilerFlipMatch = false;
786 bool useMatch = !cUnit->compilerMethodMatch.empty();
787 bool match = useMatch && (cUnit->compilerFlipMatch ^
788 (PrettyMethod(method_idx, dex_file).find(cUnit->compilerMethodMatch) !=
789 std::string::npos));
790 if (!useMatch || match) {
791 cUnit->disableOpt = kCompilerOptimizerDisableFlags;
792 cUnit->enableDebug = kCompilerDebugFlags;
793 cUnit->printMe = VLOG_IS_ON(compiler) ||
794 (cUnit->enableDebug & (1 << kDebugVerbose));
795 }
buzbee2cfc6392012-05-07 14:51:40 -0700796#if defined(ART_USE_QUICK_COMPILER)
buzbee6969d502012-06-15 16:40:31 -0700797 if (cUnit->genBitcode) {
798 cUnit->printMe = true;
buzbeead8f15e2012-06-18 14:49:45 -0700799 cUnit->enableDebug |= (1 << kDebugDumpBitcodeFile);
buzbee4f1181f2012-06-22 13:52:12 -0700800 // Disable non-safe optimizations for now
801 cUnit->disableOpt |= ~(1 << kSafeOptimizations);
buzbee6969d502012-06-15 16:40:31 -0700802 }
buzbee2cfc6392012-05-07 14:51:40 -0700803#endif
Bill Buzbeea114add2012-05-03 15:00:40 -0700804 if (cUnit->instructionSet == kX86) {
jeffhaoe2962482012-06-28 11:29:57 -0700805 // Disable some optimizations on X86 for now
806 cUnit->disableOpt |= (
807 (1 << kLoadStoreElimination) |
808 (1 << kPromoteRegs) |
809 (1 << kTrackLiveTemps));
Bill Buzbeea114add2012-05-03 15:00:40 -0700810 }
811 /* Are we generating code for the debugger? */
812 if (compiler.IsDebuggingSupported()) {
813 cUnit->genDebugger = true;
814 // Yes, disable most optimizations
815 cUnit->disableOpt |= (
816 (1 << kLoadStoreElimination) |
817 (1 << kLoadHoisting) |
818 (1 << kSuppressLoads) |
819 (1 << kPromoteRegs) |
820 (1 << kBBOpt) |
821 (1 << kMatch) |
822 (1 << kTrackLiveTemps));
823 }
824
825 /* Gathering opcode stats? */
826 if (kCompilerDebugFlags & (1 << kDebugCountOpcodes)) {
827 cUnit->opcodeCount = (int*)oatNew(cUnit.get(),
828 kNumPackedOpcodes * sizeof(int), true, kAllocMisc);
829 }
830
831 /* Assume non-throwing leaf */
832 cUnit->attrs = (METHOD_IS_LEAF | METHOD_IS_THROW_FREE);
833
834 /* Initialize the block list, estimate size based on insnsSize */
835 oatInitGrowableList(cUnit.get(), &cUnit->blockList, cUnit->insnsSize,
836 kListBlockList);
837
838 /* Initialize the switchTables list */
839 oatInitGrowableList(cUnit.get(), &cUnit->switchTables, 4,
840 kListSwitchTables);
841
842 /* Intialize the fillArrayData list */
843 oatInitGrowableList(cUnit.get(), &cUnit->fillArrayData, 4,
844 kListFillArrayData);
845
846 /* Intialize the throwLaunchpads list, estimate size based on insnsSize */
847 oatInitGrowableList(cUnit.get(), &cUnit->throwLaunchpads, cUnit->insnsSize,
848 kListThrowLaunchPads);
849
850 /* Intialize the instrinsicLaunchpads list */
851 oatInitGrowableList(cUnit.get(), &cUnit->intrinsicLaunchpads, 4,
852 kListMisc);
853
854
855 /* Intialize the suspendLaunchpads list */
856 oatInitGrowableList(cUnit.get(), &cUnit->suspendLaunchpads, 2048,
857 kListSuspendLaunchPads);
858
859 /* Allocate the bit-vector to track the beginning of basic blocks */
860 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit.get(),
861 cUnit->insnsSize,
862 true /* expandable */);
863 cUnit->tryBlockAddr = tryBlockAddr;
864
865 /* Create the default entry and exit blocks and enter them to the list */
866 BasicBlock *entryBlock = oatNewBB(cUnit.get(), kEntryBlock, numBlocks++);
867 BasicBlock *exitBlock = oatNewBB(cUnit.get(), kExitBlock, numBlocks++);
868
869 cUnit->entryBlock = entryBlock;
870 cUnit->exitBlock = exitBlock;
871
872 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) entryBlock);
873 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) exitBlock);
874
875 /* Current block to record parsed instructions */
876 BasicBlock *curBlock = oatNewBB(cUnit.get(), kDalvikByteCode, numBlocks++);
877 curBlock->startOffset = 0;
878 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) curBlock);
879 /* Add first block to the fast lookup cache */
880 cUnit->blockMap.Put(curBlock->startOffset, curBlock);
881 entryBlock->fallThrough = curBlock;
882 oatInsertGrowableList(cUnit.get(), curBlock->predecessors,
883 (intptr_t)entryBlock);
884
885 /*
886 * Store back the number of blocks since new blocks may be created of
887 * accessing cUnit.
888 */
889 cUnit->numBlocks = numBlocks;
890
891 /* Identify code range in try blocks and set up the empty catch blocks */
892 processTryCatchBlocks(cUnit.get());
893
894 /* Set up for simple method detection */
895 int numPatterns = sizeof(specialPatterns)/sizeof(specialPatterns[0]);
896 bool livePattern = (numPatterns > 0) && !(cUnit->disableOpt & (1 << kMatch));
Elliott Hughesabe64aa2012-05-30 17:34:45 -0700897 bool* deadPattern = (bool*)oatNew(cUnit.get(), sizeof(bool) * numPatterns, true,
Bill Buzbeea114add2012-05-03 15:00:40 -0700898 kAllocMisc);
899 SpecialCaseHandler specialCase = kNoHandler;
900 int patternPos = 0;
901
902 /* Parse all instructions and put them into containing basic blocks */
903 while (codePtr < codeEnd) {
904 MIR *insn = (MIR *) oatNew(cUnit.get(), sizeof(MIR), true, kAllocMIR);
905 insn->offset = curOffset;
906 int width = parseInsn(cUnit.get(), codePtr, &insn->dalvikInsn, false);
907 insn->width = width;
908 Instruction::Code opcode = insn->dalvikInsn.opcode;
909 if (cUnit->opcodeCount != NULL) {
910 cUnit->opcodeCount[static_cast<int>(opcode)]++;
buzbee44b412b2012-02-04 08:50:53 -0800911 }
912
Bill Buzbeea114add2012-05-03 15:00:40 -0700913 /* Terminate when the data section is seen */
914 if (width == 0)
915 break;
916
917 /* Possible simple method? */
918 if (livePattern) {
919 livePattern = false;
920 specialCase = kNoHandler;
921 for (int i = 0; i < numPatterns; i++) {
922 if (!deadPattern[i]) {
923 if (specialPatterns[i].opcodes[patternPos] == opcode) {
924 livePattern = true;
925 specialCase = specialPatterns[i].handlerCode;
926 } else {
927 deadPattern[i] = true;
928 }
929 }
930 }
931 patternPos++;
buzbeea7c12682012-03-19 13:13:53 -0700932 }
933
Bill Buzbeea114add2012-05-03 15:00:40 -0700934 oatAppendMIR(curBlock, insn);
buzbeecefd1872011-09-09 09:59:52 -0700935
Bill Buzbeea114add2012-05-03 15:00:40 -0700936 codePtr += width;
937 int flags = Instruction::Flags(insn->dalvikInsn.opcode);
buzbee67bf8852011-08-17 17:51:35 -0700938
Bill Buzbeea114add2012-05-03 15:00:40 -0700939 int dfFlags = oatDataFlowAttributes[insn->dalvikInsn.opcode];
buzbee67bf8852011-08-17 17:51:35 -0700940
Bill Buzbeea114add2012-05-03 15:00:40 -0700941 if (dfFlags & DF_HAS_DEFS) {
buzbeebff24652012-05-06 16:22:05 -0700942 cUnit->defCount += (dfFlags & DF_A_WIDE) ? 2 : 1;
Bill Buzbeea114add2012-05-03 15:00:40 -0700943 }
buzbee67bf8852011-08-17 17:51:35 -0700944
Bill Buzbeea114add2012-05-03 15:00:40 -0700945 if (flags & Instruction::kBranch) {
946 curBlock = processCanBranch(cUnit.get(), curBlock, insn, curOffset,
947 width, flags, codePtr, codeEnd);
948 } else if (flags & Instruction::kReturn) {
949 curBlock->fallThrough = exitBlock;
950 oatInsertGrowableList(cUnit.get(), exitBlock->predecessors,
951 (intptr_t)curBlock);
952 /*
953 * Terminate the current block if there are instructions
954 * afterwards.
955 */
956 if (codePtr < codeEnd) {
957 /*
958 * Create a fallthrough block for real instructions
959 * (incl. NOP).
960 */
961 if (contentIsInsn(codePtr)) {
962 findBlock(cUnit.get(), curOffset + width,
963 /* split */
964 false,
965 /* create */
966 true,
967 /* immedPredBlockP */
968 NULL);
969 }
970 }
971 } else if (flags & Instruction::kThrow) {
972 processCanThrow(cUnit.get(), curBlock, insn, curOffset, width, flags,
973 tryBlockAddr, codePtr, codeEnd);
974 } else if (flags & Instruction::kSwitch) {
975 processCanSwitch(cUnit.get(), curBlock, insn, curOffset, width, flags);
976 }
977 curOffset += width;
978 BasicBlock *nextBlock = findBlock(cUnit.get(), curOffset,
979 /* split */
980 false,
981 /* create */
982 false,
983 /* immedPredBlockP */
984 NULL);
985 if (nextBlock) {
986 /*
987 * The next instruction could be the target of a previously parsed
988 * forward branch so a block is already created. If the current
989 * instruction is not an unconditional branch, connect them through
990 * the fall-through link.
991 */
992 DCHECK(curBlock->fallThrough == NULL ||
993 curBlock->fallThrough == nextBlock ||
994 curBlock->fallThrough == exitBlock);
buzbee5ade1d22011-09-09 14:44:52 -0700995
Bill Buzbeea114add2012-05-03 15:00:40 -0700996 if ((curBlock->fallThrough == NULL) && (flags & Instruction::kContinue)) {
997 curBlock->fallThrough = nextBlock;
998 oatInsertGrowableList(cUnit.get(), nextBlock->predecessors,
999 (intptr_t)curBlock);
1000 }
1001 curBlock = nextBlock;
1002 }
1003 }
buzbeefc9e6fa2012-03-23 15:14:29 -07001004
Bill Buzbeea114add2012-05-03 15:00:40 -07001005 if (!(cUnit->disableOpt & (1 << kSkipLargeMethodOptimization))) {
1006 if ((cUnit->numBlocks > MANY_BLOCKS) ||
1007 ((cUnit->numBlocks > MANY_BLOCKS_INITIALIZER) &&
1008 PrettyMethod(method_idx, dex_file, false).find("init>") !=
1009 std::string::npos)) {
1010 cUnit->qdMode = true;
1011 }
1012 }
buzbeefc9e6fa2012-03-23 15:14:29 -07001013
buzbee2cfc6392012-05-07 14:51:40 -07001014#if defined(ART_USE_QUICK_COMPILER)
1015 if (cUnit->genBitcode) {
1016 // Bitcode generation requires full dataflow analysis, no qdMode
1017 cUnit->qdMode = false;
1018 }
1019#endif
1020
Bill Buzbeea114add2012-05-03 15:00:40 -07001021 if (cUnit->qdMode) {
1022 cUnit->disableDataflow = true;
1023 // Disable optimization which require dataflow/ssa
1024 cUnit->disableOpt |=
1025 (1 << kNullCheckElimination) |
1026 (1 << kBBOpt) |
1027 (1 << kPromoteRegs);
1028 if (cUnit->printMe) {
1029 LOG(INFO) << "QD mode enabled: "
1030 << PrettyMethod(method_idx, dex_file)
1031 << " too big: " << cUnit->numBlocks;
1032 }
1033 }
buzbeec1f45042011-09-21 16:03:19 -07001034
Bill Buzbeea114add2012-05-03 15:00:40 -07001035 if (cUnit->printMe) {
1036 oatDumpCompilationUnit(cUnit.get());
1037 }
buzbee67bf8852011-08-17 17:51:35 -07001038
Bill Buzbeea114add2012-05-03 15:00:40 -07001039 if (cUnit->enableDebug & (1 << kDebugVerifyDataflow)) {
1040 /* Verify if all blocks are connected as claimed */
1041 oatDataFlowAnalysisDispatcher(cUnit.get(), verifyPredInfo, kAllNodes,
1042 false /* isIterative */);
1043 }
buzbee67bf8852011-08-17 17:51:35 -07001044
Bill Buzbeea114add2012-05-03 15:00:40 -07001045 /* Perform SSA transformation for the whole method */
1046 oatMethodSSATransformation(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001047
buzbee2cfc6392012-05-07 14:51:40 -07001048 /* Do constant propagation */
1049 // TODO: Probably need to make these expandable to support new ssa names
1050 // introducted during MIR optimization passes
1051 cUnit->isConstantV = oatAllocBitVector(cUnit.get(), cUnit->numSSARegs,
1052 false /* not expandable */);
1053 cUnit->constantValues =
1054 (int*)oatNew(cUnit.get(), sizeof(int) * cUnit->numSSARegs, true,
1055 kAllocDFInfo);
1056 oatDataFlowAnalysisDispatcher(cUnit.get(), oatDoConstantPropagation,
1057 kAllNodes,
1058 false /* isIterative */);
1059
Bill Buzbeea114add2012-05-03 15:00:40 -07001060 /* Detect loops */
1061 oatMethodLoopDetection(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001062
Bill Buzbeea114add2012-05-03 15:00:40 -07001063 /* Count uses */
1064 oatMethodUseCount(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001065
Bill Buzbeea114add2012-05-03 15:00:40 -07001066 /* Perform null check elimination */
1067 oatMethodNullCheckElimination(cUnit.get());
1068
1069 /* Do some basic block optimizations */
1070 oatMethodBasicBlockOptimization(cUnit.get());
1071
1072 oatInitializeRegAlloc(cUnit.get()); // Needs to happen after SSA naming
1073
1074 /* Allocate Registers using simple local allocation scheme */
1075 oatSimpleRegAlloc(cUnit.get());
1076
buzbee2cfc6392012-05-07 14:51:40 -07001077#if defined(ART_USE_QUICK_COMPILER)
1078 /* Go the LLVM path? */
1079 if (cUnit->genBitcode) {
1080 // MIR->Bitcode
1081 oatMethodMIR2Bitcode(cUnit.get());
1082 // Bitcode->LIR
1083 oatMethodBitcode2LIR(cUnit.get());
1084 } else {
1085#endif
1086 if (specialCase != kNoHandler) {
1087 /*
1088 * Custom codegen for special cases. If for any reason the
1089 * special codegen doesn't succeed, cUnit->firstLIRInsn will
1090 * set to NULL;
1091 */
1092 oatSpecialMIR2LIR(cUnit.get(), specialCase);
1093 }
buzbee67bf8852011-08-17 17:51:35 -07001094
buzbee2cfc6392012-05-07 14:51:40 -07001095 /* Convert MIR to LIR, etc. */
1096 if (cUnit->firstLIRInsn == NULL) {
1097 oatMethodMIR2LIR(cUnit.get());
1098 }
1099#if defined(ART_USE_QUICK_COMPILER)
Bill Buzbeea114add2012-05-03 15:00:40 -07001100 }
buzbee2cfc6392012-05-07 14:51:40 -07001101#endif
buzbee67bf8852011-08-17 17:51:35 -07001102
Bill Buzbeea114add2012-05-03 15:00:40 -07001103 // Debugging only
1104 if (cUnit->enableDebug & (1 << kDebugDumpCFG)) {
1105 oatDumpCFG(cUnit.get(), "/sdcard/cfg/");
1106 }
buzbee16da88c2012-03-20 10:38:17 -07001107
Bill Buzbeea114add2012-05-03 15:00:40 -07001108 /* Method is not empty */
1109 if (cUnit->firstLIRInsn) {
buzbee67bf8852011-08-17 17:51:35 -07001110
Bill Buzbeea114add2012-05-03 15:00:40 -07001111 // mark the targets of switch statement case labels
1112 oatProcessSwitchTables(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001113
Bill Buzbeea114add2012-05-03 15:00:40 -07001114 /* Convert LIR into machine code. */
1115 oatAssembleLIR(cUnit.get());
buzbee99ba9642012-01-25 14:23:14 -08001116
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07001117 if (cUnit->printMe) {
Bill Buzbeea114add2012-05-03 15:00:40 -07001118 oatCodegenDump(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001119 }
1120
Bill Buzbeea114add2012-05-03 15:00:40 -07001121 if (cUnit->opcodeCount != NULL) {
1122 LOG(INFO) << "Opcode Count";
1123 for (int i = 0; i < kNumPackedOpcodes; i++) {
1124 if (cUnit->opcodeCount[i] != 0) {
1125 LOG(INFO) << "-C- "
1126 << Instruction::Name(static_cast<Instruction::Code>(i))
1127 << " " << cUnit->opcodeCount[i];
buzbee67bf8852011-08-17 17:51:35 -07001128 }
Bill Buzbeea114add2012-05-03 15:00:40 -07001129 }
1130 }
1131 }
buzbeea7c12682012-03-19 13:13:53 -07001132
Bill Buzbeea114add2012-05-03 15:00:40 -07001133 // Combine vmap tables - core regs, then fp regs - into vmapTable
1134 std::vector<uint16_t> vmapTable;
1135 for (size_t i = 0 ; i < cUnit->coreVmapTable.size(); i++) {
1136 vmapTable.push_back(cUnit->coreVmapTable[i]);
1137 }
1138 // If we have a frame, push a marker to take place of lr
1139 if (cUnit->frameSize > 0) {
1140 vmapTable.push_back(INVALID_VREG);
1141 } else {
1142 DCHECK_EQ(__builtin_popcount(cUnit->coreSpillMask), 0);
1143 DCHECK_EQ(__builtin_popcount(cUnit->fpSpillMask), 0);
1144 }
1145 // Combine vmap tables - core regs, then fp regs
1146 for (uint32_t i = 0; i < cUnit->fpVmapTable.size(); i++) {
1147 vmapTable.push_back(cUnit->fpVmapTable[i]);
1148 }
1149 CompiledMethod* result =
1150 new CompiledMethod(cUnit->instructionSet, cUnit->codeBuffer,
1151 cUnit->frameSize, cUnit->coreSpillMask,
1152 cUnit->fpSpillMask, cUnit->mappingTable, vmapTable);
buzbee67bf8852011-08-17 17:51:35 -07001153
Bill Buzbeea114add2012-05-03 15:00:40 -07001154 VLOG(compiler) << "Compiled " << PrettyMethod(method_idx, dex_file)
1155 << " (" << (cUnit->codeBuffer.size() * sizeof(cUnit->codeBuffer[0]))
1156 << " bytes)";
buzbee5abfa3e2012-01-31 17:01:43 -08001157
1158#ifdef WITH_MEMSTATS
Bill Buzbeea114add2012-05-03 15:00:40 -07001159 if (cUnit->enableDebug & (1 << kDebugShowMemoryUsage)) {
1160 oatDumpMemStats(cUnit.get());
1161 }
buzbee5abfa3e2012-01-31 17:01:43 -08001162#endif
buzbee67bf8852011-08-17 17:51:35 -07001163
Bill Buzbeea114add2012-05-03 15:00:40 -07001164 oatArenaReset(cUnit.get());
buzbeeba938cb2012-02-03 14:47:55 -08001165
Bill Buzbeea114add2012-05-03 15:00:40 -07001166 return result;
buzbee67bf8852011-08-17 17:51:35 -07001167}
1168
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001169} // namespace art
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001170
Bill Buzbeea114add2012-05-03 15:00:40 -07001171extern "C" art::CompiledMethod*
1172 ArtCompileMethod(art::Compiler& compiler,
1173 const art::DexFile::CodeItem* code_item,
1174 uint32_t access_flags, uint32_t method_idx,
1175 const art::ClassLoader* class_loader,
1176 const art::DexFile& dex_file)
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001177{
1178 CHECK_EQ(compiler.GetInstructionSet(), art::oatInstructionSet());
Bill Buzbeea114add2012-05-03 15:00:40 -07001179 return art::oatCompileMethod(compiler, code_item, access_flags, method_idx,
1180 class_loader, dex_file);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001181}