blob: d6f891b497f0d01c5f51545225363b40becab8bc [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"
buzbeec143c552011-08-20 17:38:58 -070020#include "constants.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
24static inline bool contentIsInsn(const u2* codePtr) {
25 u2 instr = *codePtr;
26 Opcode opcode = (Opcode)(instr & 0xff);
27
28 /*
29 * Since the low 8-bit in metadata may look like OP_NOP, we need to check
30 * both the low and whole sub-word to determine whether it is code or data.
31 */
32 return (opcode != OP_NOP || instr == 0);
33}
34
35/*
36 * Parse an instruction, return the length of the instruction
37 */
38static inline int parseInsn(const u2* codePtr, DecodedInstruction* decInsn,
39 bool printMe)
40{
41 // Don't parse instruction data
42 if (!contentIsInsn(codePtr)) {
43 return 0;
44 }
45
46 u2 instr = *codePtr;
47 Opcode opcode = dexOpcodeFromCodeUnit(instr);
48
49 dexDecodeInstruction(codePtr, decInsn);
50 if (printMe) {
51 char *decodedString = oatGetDalvikDisassembly(decInsn, NULL);
52 LOG(INFO) << codePtr << ": 0x" << std::hex << (int)opcode <<
53 " " << decodedString;
54 }
55 return dexGetWidthFromOpcode(opcode);
56}
57
58#define UNKNOWN_TARGET 0xffffffff
59
60static inline bool isGoto(MIR* insn)
61{
62 switch (insn->dalvikInsn.opcode) {
63 case OP_GOTO:
64 case OP_GOTO_16:
65 case OP_GOTO_32:
66 return true;
67 default:
68 return false;
69 }
70}
71
72/*
73 * Identify unconditional branch instructions
74 */
75static inline bool isUnconditionalBranch(MIR* insn)
76{
77 switch (insn->dalvikInsn.opcode) {
78 case OP_RETURN_VOID:
79 case OP_RETURN:
80 case OP_RETURN_WIDE:
81 case OP_RETURN_OBJECT:
82 return true;
83 default:
84 return isGoto(insn);
85 }
86}
87
88/* Split an existing block from the specified code offset into two */
89static BasicBlock *splitBlock(CompilationUnit* cUnit,
90 unsigned int codeOffset,
91 BasicBlock* origBlock)
92{
93 MIR* insn = origBlock->firstMIRInsn;
94 while (insn) {
95 if (insn->offset == codeOffset) break;
96 insn = insn->next;
97 }
98 if (insn == NULL) {
99 LOG(FATAL) << "Break split failed";
100 }
101 BasicBlock *bottomBlock = oatNewBB(kDalvikByteCode,
102 cUnit->numBlocks++);
103 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bottomBlock);
104
105 bottomBlock->startOffset = codeOffset;
106 bottomBlock->firstMIRInsn = insn;
107 bottomBlock->lastMIRInsn = origBlock->lastMIRInsn;
108
109 /* Handle the taken path */
110 bottomBlock->taken = origBlock->taken;
111 if (bottomBlock->taken) {
112 origBlock->taken = NULL;
113 oatClearBit(bottomBlock->taken->predecessors, origBlock->id);
114 oatSetBit(bottomBlock->taken->predecessors, bottomBlock->id);
115 }
116
117 /* Handle the fallthrough path */
118 bottomBlock->needFallThroughBranch = origBlock->needFallThroughBranch;
119 bottomBlock->fallThrough = origBlock->fallThrough;
120 origBlock->fallThrough = bottomBlock;
121 origBlock->needFallThroughBranch = true;
122 oatSetBit(bottomBlock->predecessors, origBlock->id);
123 if (bottomBlock->fallThrough) {
124 oatClearBit(bottomBlock->fallThrough->predecessors,
125 origBlock->id);
126 oatSetBit(bottomBlock->fallThrough->predecessors,
127 bottomBlock->id);
128 }
129
130 /* Handle the successor list */
131 if (origBlock->successorBlockList.blockListType != kNotUsed) {
132 bottomBlock->successorBlockList = origBlock->successorBlockList;
133 origBlock->successorBlockList.blockListType = kNotUsed;
134 GrowableListIterator iterator;
135
136 oatGrowableListIteratorInit(&bottomBlock->successorBlockList.blocks,
137 &iterator);
138 while (true) {
139 SuccessorBlockInfo *successorBlockInfo =
140 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
141 if (successorBlockInfo == NULL) break;
142 BasicBlock *bb = successorBlockInfo->block;
143 oatClearBit(bb->predecessors, origBlock->id);
144 oatSetBit(bb->predecessors, bottomBlock->id);
145 }
146 }
147
148 origBlock->lastMIRInsn = insn->prev;
149
150 insn->prev->next = NULL;
151 insn->prev = NULL;
152 return bottomBlock;
153}
154
155/*
156 * Given a code offset, find out the block that starts with it. If the offset
157 * is in the middle of an existing block, split it into two.
158 */
159static BasicBlock *findBlock(CompilationUnit* cUnit,
160 unsigned int codeOffset,
161 bool split, bool create)
162{
163 GrowableList* blockList = &cUnit->blockList;
164 BasicBlock* bb;
165 unsigned int i;
166
167 for (i = 0; i < blockList->numUsed; i++) {
168 bb = (BasicBlock *) blockList->elemList[i];
169 if (bb->blockType != kDalvikByteCode) continue;
170 if (bb->startOffset == codeOffset) return bb;
171 /* Check if a branch jumps into the middle of an existing block */
172 if ((split == true) && (codeOffset > bb->startOffset) &&
173 (bb->lastMIRInsn != NULL) &&
174 (codeOffset <= bb->lastMIRInsn->offset)) {
175 BasicBlock *newBB = splitBlock(cUnit, codeOffset, bb);
176 return newBB;
177 }
178 }
179 if (create) {
180 bb = oatNewBB(kDalvikByteCode, cUnit->numBlocks++);
181 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bb);
182 bb->startOffset = codeOffset;
183 return bb;
184 }
185 return NULL;
186}
187
188/* Dump the CFG into a DOT graph */
189void oatDumpCFG(CompilationUnit* cUnit, const char* dirPrefix)
190{
buzbee67bf8852011-08-17 17:51:35 -0700191 FILE* file;
buzbeedfd3d702011-08-28 12:56:51 -0700192 std::string name = art::PrettyMethod(cUnit->method);
buzbee67bf8852011-08-17 17:51:35 -0700193 char startOffset[80];
194 sprintf(startOffset, "_%x", cUnit->entryBlock->fallThrough->startOffset);
195 char* fileName = (char *) oatNew(
buzbeec143c552011-08-20 17:38:58 -0700196 strlen(dirPrefix) +
197 name.length() +
198 strlen(".dot") + 1, true);
199 sprintf(fileName, "%s%s%s.dot", dirPrefix, name.c_str(), startOffset);
buzbee67bf8852011-08-17 17:51:35 -0700200
201 /*
202 * Convert the special characters into a filesystem- and shell-friendly
203 * format.
204 */
205 int i;
206 for (i = strlen(dirPrefix); fileName[i]; i++) {
207 if (fileName[i] == '/') {
208 fileName[i] = '_';
209 } else if (fileName[i] == ';') {
210 fileName[i] = '#';
211 } else if (fileName[i] == '$') {
212 fileName[i] = '+';
213 } else if (fileName[i] == '(' || fileName[i] == ')') {
214 fileName[i] = '@';
215 } else if (fileName[i] == '<' || fileName[i] == '>') {
216 fileName[i] = '=';
217 }
218 }
219 file = fopen(fileName, "w");
220 if (file == NULL) {
221 return;
222 }
223 fprintf(file, "digraph G {\n");
224
225 fprintf(file, " rankdir=TB\n");
226
227 int numReachableBlocks = cUnit->numReachableBlocks;
228 int idx;
229 const GrowableList *blockList = &cUnit->blockList;
230
231 for (idx = 0; idx < numReachableBlocks; idx++) {
232 int blockIdx = cUnit->dfsOrder.elemList[idx];
233 BasicBlock *bb = (BasicBlock *) oatGrowableListGetElement(blockList,
234 blockIdx);
235 if (bb == NULL) break;
236 if (bb->blockType == kEntryBlock) {
237 fprintf(file, " entry [shape=Mdiamond];\n");
238 } else if (bb->blockType == kExitBlock) {
239 fprintf(file, " exit [shape=Mdiamond];\n");
240 } else if (bb->blockType == kDalvikByteCode) {
241 fprintf(file, " block%04x [shape=record,label = \"{ \\\n",
242 bb->startOffset);
243 const MIR *mir;
244 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
245 bb->firstMIRInsn ? " | " : " ");
246 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
247 fprintf(file, " {%04x %s\\l}%s\\\n", mir->offset,
248 mir->ssaRep ?
249 oatFullDisassembler(cUnit, mir) :
250 dexGetOpcodeName(mir->dalvikInsn.opcode),
251 mir->next ? " | " : " ");
252 }
253 fprintf(file, " }\"];\n\n");
254 } else if (bb->blockType == kExceptionHandling) {
255 char blockName[BLOCK_NAME_LEN];
256
257 oatGetBlockName(bb, blockName);
258 fprintf(file, " %s [shape=invhouse];\n", blockName);
259 }
260
261 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
262
263 if (bb->taken) {
264 oatGetBlockName(bb, blockName1);
265 oatGetBlockName(bb->taken, blockName2);
266 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
267 blockName1, blockName2);
268 }
269 if (bb->fallThrough) {
270 oatGetBlockName(bb, blockName1);
271 oatGetBlockName(bb->fallThrough, blockName2);
272 fprintf(file, " %s:s -> %s:n\n", blockName1, blockName2);
273 }
274
275 if (bb->successorBlockList.blockListType != kNotUsed) {
276 fprintf(file, " succ%04x [shape=%s,label = \"{ \\\n",
277 bb->startOffset,
278 (bb->successorBlockList.blockListType == kCatch) ?
279 "Mrecord" : "record");
280 GrowableListIterator iterator;
281 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
282 &iterator);
283 SuccessorBlockInfo *successorBlockInfo =
284 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
285
286 int succId = 0;
287 while (true) {
288 if (successorBlockInfo == NULL) break;
289
290 BasicBlock *destBlock = successorBlockInfo->block;
291 SuccessorBlockInfo *nextSuccessorBlockInfo =
292 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
293
294 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
295 succId++,
296 successorBlockInfo->key,
297 destBlock->startOffset,
298 (nextSuccessorBlockInfo != NULL) ? " | " : " ");
299
300 successorBlockInfo = nextSuccessorBlockInfo;
301 }
302 fprintf(file, " }\"];\n\n");
303
304 oatGetBlockName(bb, blockName1);
305 fprintf(file, " %s:s -> succ%04x:n [style=dashed]\n",
306 blockName1, bb->startOffset);
307
308 if (bb->successorBlockList.blockListType == kPackedSwitch ||
309 bb->successorBlockList.blockListType == kSparseSwitch) {
310
311 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
312 &iterator);
313
314 succId = 0;
315 while (true) {
316 SuccessorBlockInfo *successorBlockInfo =
317 (SuccessorBlockInfo *)
318 oatGrowableListIteratorNext(&iterator);
319 if (successorBlockInfo == NULL) break;
320
321 BasicBlock *destBlock = successorBlockInfo->block;
322
323 oatGetBlockName(destBlock, blockName2);
324 fprintf(file, " succ%04x:f%d:e -> %s:n\n",
325 bb->startOffset, succId++,
326 blockName2);
327 }
328 }
329 }
330 fprintf(file, "\n");
331
332 /*
333 * If we need to debug the dominator tree, uncomment the following code
334 */
335#if 1
336 oatGetBlockName(bb, blockName1);
337 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
338 blockName1, blockName1);
339 if (bb->iDom) {
340 oatGetBlockName(bb->iDom, blockName2);
341 fprintf(file, " cfg%s:s -> cfg%s:n\n\n",
342 blockName2, blockName1);
343 }
344#endif
345 }
346 fprintf(file, "}\n");
347 fclose(file);
348}
349
350/* Verify if all the successor is connected with all the claimed predecessors */
351static bool verifyPredInfo(CompilationUnit* cUnit, BasicBlock* bb)
352{
353 ArenaBitVectorIterator bvIterator;
354
355 oatBitVectorIteratorInit(bb->predecessors, &bvIterator);
356 while (true) {
357 int blockIdx = oatBitVectorIteratorNext(&bvIterator);
358 if (blockIdx == -1) break;
359 BasicBlock *predBB = (BasicBlock *)
360 oatGrowableListGetElement(&cUnit->blockList, blockIdx);
361 bool found = false;
362 if (predBB->taken == bb) {
363 found = true;
364 } else if (predBB->fallThrough == bb) {
365 found = true;
366 } else if (predBB->successorBlockList.blockListType != kNotUsed) {
367 GrowableListIterator iterator;
368 oatGrowableListIteratorInit(&predBB->successorBlockList.blocks,
369 &iterator);
370 while (true) {
371 SuccessorBlockInfo *successorBlockInfo =
372 (SuccessorBlockInfo *)
373 oatGrowableListIteratorNext(&iterator);
374 if (successorBlockInfo == NULL) break;
375 BasicBlock *succBB = successorBlockInfo->block;
376 if (succBB == bb) {
377 found = true;
378 break;
379 }
380 }
381 }
382 if (found == false) {
383 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
384 oatGetBlockName(bb, blockName1);
385 oatGetBlockName(predBB, blockName2);
386 oatDumpCFG(cUnit, "/sdcard/cfg/");
387 LOG(FATAL) << "Successor " << blockName1 << "not found from "
388 << blockName2;
389 }
390 }
391 return true;
392}
393
394/* Identify code range in try blocks and set up the empty catch blocks */
395static void processTryCatchBlocks(CompilationUnit* cUnit)
396{
buzbeec143c552011-08-20 17:38:58 -0700397
398 UNIMPLEMENTED(WARNING) << "Need to finish processTryCatchBlocks()";
399#if 0
buzbee67bf8852011-08-17 17:51:35 -0700400 const Method* meth = cUnit->method;
401 const DexCode *pCode = dvmGetMethodCode(meth);
402 int triesSize = pCode->triesSize;
403 int i;
404 int offset;
405
406 if (triesSize == 0) {
407 return;
408 }
409
410 const DexTry* pTries = dexGetTries(pCode);
411 ArenaBitVector* tryBlockAddr = cUnit->tryBlockAddr;
412
413 /* Mark all the insn offsets in Try blocks */
414 for (i = 0; i < triesSize; i++) {
415 const DexTry* pTry = &pTries[i];
416 /* all in 16-bit units */
417 int startOffset = pTry->startAddr;
418 int endOffset = startOffset + pTry->insnCount;
419
420 for (offset = startOffset; offset < endOffset; offset++) {
421 oatSetBit(tryBlockAddr, offset);
422 }
423 }
424
425 /* Iterate over each of the handlers to enqueue the empty Catch blocks */
426 offset = dexGetFirstHandlerOffset(pCode);
427 int handlersSize = dexGetHandlersSize(pCode);
428
429 for (i = 0; i < handlersSize; i++) {
430 DexCatchIterator iterator;
431 dexCatchIteratorInit(&iterator, pCode, offset);
432
433 for (;;) {
434 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
435
436 if (handler == NULL) {
437 break;
438 }
439
440 /*
441 * Create dummy catch blocks first. Since these are created before
442 * other blocks are processed, "split" is specified as false.
443 */
444 findBlock(cUnit, handler->address,
445 /* split */
446 false,
447 /* create */
448 true);
449 }
450
451 offset = dexCatchIteratorGetEndOffset(&iterator, pCode);
452 }
buzbeec143c552011-08-20 17:38:58 -0700453#endif
buzbee67bf8852011-08-17 17:51:35 -0700454}
455
456/* Process instructions with the kInstrCanBranch flag */
457static void processCanBranch(CompilationUnit* cUnit, BasicBlock* curBlock,
458 MIR* insn, int curOffset, int width, int flags,
459 const u2* codePtr, const u2* codeEnd)
460{
461 int target = curOffset;
462 switch (insn->dalvikInsn.opcode) {
463 case OP_GOTO:
464 case OP_GOTO_16:
465 case OP_GOTO_32:
466 target += (int) insn->dalvikInsn.vA;
467 break;
468 case OP_IF_EQ:
469 case OP_IF_NE:
470 case OP_IF_LT:
471 case OP_IF_GE:
472 case OP_IF_GT:
473 case OP_IF_LE:
474 target += (int) insn->dalvikInsn.vC;
475 break;
476 case OP_IF_EQZ:
477 case OP_IF_NEZ:
478 case OP_IF_LTZ:
479 case OP_IF_GEZ:
480 case OP_IF_GTZ:
481 case OP_IF_LEZ:
482 target += (int) insn->dalvikInsn.vB;
483 break;
484 default:
485 LOG(FATAL) << "Unexpected opcode(" << (int)insn->dalvikInsn.opcode
486 << ") with kInstrCanBranch set";
487 }
488 BasicBlock *takenBlock = findBlock(cUnit, target,
489 /* split */
490 true,
491 /* create */
492 true);
493 curBlock->taken = takenBlock;
494 oatSetBit(takenBlock->predecessors, curBlock->id);
495
496 /* Always terminate the current block for conditional branches */
497 if (flags & kInstrCanContinue) {
498 BasicBlock *fallthroughBlock = findBlock(cUnit,
499 curOffset + width,
500 /*
501 * If the method is processed
502 * in sequential order from the
503 * beginning, we don't need to
504 * specify split for continue
505 * blocks. However, this
506 * routine can be called by
507 * compileLoop, which starts
508 * parsing the method from an
509 * arbitrary address in the
510 * method body.
511 */
512 true,
513 /* create */
514 true);
515 curBlock->fallThrough = fallthroughBlock;
516 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
517 } else if (codePtr < codeEnd) {
518 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
519 if (contentIsInsn(codePtr)) {
520 findBlock(cUnit, curOffset + width,
521 /* split */
522 false,
523 /* create */
524 true);
525 }
526 }
527}
528
529/* Process instructions with the kInstrCanSwitch flag */
530static void processCanSwitch(CompilationUnit* cUnit, BasicBlock* curBlock,
531 MIR* insn, int curOffset, int width, int flags)
532{
533 u2* switchData= (u2 *) (cUnit->insns + curOffset +
534 insn->dalvikInsn.vB);
535 int size;
536 int* keyTable;
537 int* targetTable;
538 int i;
539 int firstKey;
540
541 /*
542 * Packed switch data format:
543 * ushort ident = 0x0100 magic value
544 * ushort size number of entries in the table
545 * int first_key first (and lowest) switch case value
546 * int targets[size] branch targets, relative to switch opcode
547 *
548 * Total size is (4+size*2) 16-bit code units.
549 */
550 if (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) {
551 assert(switchData[0] == kPackedSwitchSignature);
552 size = switchData[1];
553 firstKey = switchData[2] | (switchData[3] << 16);
554 targetTable = (int *) &switchData[4];
555 keyTable = NULL; // Make the compiler happy
556 /*
557 * Sparse switch data format:
558 * ushort ident = 0x0200 magic value
559 * ushort size number of entries in the table; > 0
560 * int keys[size] keys, sorted low-to-high; 32-bit aligned
561 * int targets[size] branch targets, relative to switch opcode
562 *
563 * Total size is (2+size*4) 16-bit code units.
564 */
565 } else {
566 assert(switchData[0] == kSparseSwitchSignature);
567 size = switchData[1];
568 keyTable = (int *) &switchData[2];
569 targetTable = (int *) &switchData[2 + size*2];
570 firstKey = 0; // To make the compiler happy
571 }
572
573 if (curBlock->successorBlockList.blockListType != kNotUsed) {
574 LOG(FATAL) << "Successor block list already in use: " <<
575 (int)curBlock->successorBlockList.blockListType;
576 }
577 curBlock->successorBlockList.blockListType =
578 (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) ?
579 kPackedSwitch : kSparseSwitch;
580 oatInitGrowableList(&curBlock->successorBlockList.blocks, size);
581
582 for (i = 0; i < size; i++) {
583 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
584 /* split */
585 true,
586 /* create */
587 true);
588 SuccessorBlockInfo *successorBlockInfo =
589 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
590 false);
591 successorBlockInfo->block = caseBlock;
592 successorBlockInfo->key = (insn->dalvikInsn.opcode == OP_PACKED_SWITCH)?
593 firstKey + i : keyTable[i];
594 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
595 (intptr_t) successorBlockInfo);
596 oatSetBit(caseBlock->predecessors, curBlock->id);
597 }
598
599 /* Fall-through case */
600 BasicBlock* fallthroughBlock = findBlock(cUnit,
601 curOffset + width,
602 /* split */
603 false,
604 /* create */
605 true);
606 curBlock->fallThrough = fallthroughBlock;
607 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
608}
609
610/* Process instructions with the kInstrCanThrow flag */
611static void processCanThrow(CompilationUnit* cUnit, BasicBlock* curBlock,
612 MIR* insn, int curOffset, int width, int flags,
613 ArenaBitVector* tryBlockAddr, const u2* codePtr,
614 const u2* codeEnd)
615{
buzbeec143c552011-08-20 17:38:58 -0700616 UNIMPLEMENTED(WARNING) << "Need to complete processCanThrow";
617#if 0
buzbee67bf8852011-08-17 17:51:35 -0700618 const Method* method = cUnit->method;
619 const DexCode* dexCode = dvmGetMethodCode(method);
620
621 /* In try block */
622 if (oatIsBitSet(tryBlockAddr, curOffset)) {
623 DexCatchIterator iterator;
624
625 if (!dexFindCatchHandler(&iterator, dexCode, curOffset)) {
626 LOG(FATAL) << "Catch block not found in dexfile for insn " <<
627 curOffset << " in " << method->name;
628
629 }
630 if (curBlock->successorBlockList.blockListType != kNotUsed) {
631 LOG(FATAL) << "Successor block list already in use: " <<
632 (int)curBlock->successorBlockList.blockListType;
633 }
634 curBlock->successorBlockList.blockListType = kCatch;
635 oatInitGrowableList(&curBlock->successorBlockList.blocks, 2);
636
637 for (;;) {
638 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
639
640 if (handler == NULL) {
641 break;
642 }
643
644 BasicBlock *catchBlock = findBlock(cUnit, handler->address,
645 /* split */
646 false,
647 /* create */
648 false);
649
650 SuccessorBlockInfo *successorBlockInfo =
651 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
652 false);
653 successorBlockInfo->block = catchBlock;
654 successorBlockInfo->key = handler->typeIdx;
655 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
656 (intptr_t) successorBlockInfo);
657 oatSetBit(catchBlock->predecessors, curBlock->id);
658 }
659 } else {
660 BasicBlock *ehBlock = oatNewBB(kExceptionHandling,
661 cUnit->numBlocks++);
662 curBlock->taken = ehBlock;
663 oatInsertGrowableList(&cUnit->blockList, (intptr_t) ehBlock);
664 ehBlock->startOffset = curOffset;
665 oatSetBit(ehBlock->predecessors, curBlock->id);
666 }
667
668 /*
669 * Force the current block to terminate.
670 *
671 * Data may be present before codeEnd, so we need to parse it to know
672 * whether it is code or data.
673 */
674 if (codePtr < codeEnd) {
675 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
676 if (contentIsInsn(codePtr)) {
677 BasicBlock *fallthroughBlock = findBlock(cUnit,
678 curOffset + width,
679 /* split */
680 false,
681 /* create */
682 true);
683 /*
684 * OP_THROW and OP_THROW_VERIFICATION_ERROR are unconditional
685 * branches.
686 */
687 if (insn->dalvikInsn.opcode != OP_THROW_VERIFICATION_ERROR &&
688 insn->dalvikInsn.opcode != OP_THROW) {
689 curBlock->fallThrough = fallthroughBlock;
690 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
691 }
692 }
693 }
buzbeec143c552011-08-20 17:38:58 -0700694#endif
buzbee67bf8852011-08-17 17:51:35 -0700695}
696
697/*
698 * Compile a method.
699 */
buzbeec143c552011-08-20 17:38:58 -0700700bool oatCompileMethod(Method* method, art::InstructionSet insnSet)
buzbee67bf8852011-08-17 17:51:35 -0700701{
buzbee439c4fa2011-08-27 15:59:07 -0700702 bool compiling = true;
703 if (!method->IsStatic()) {
buzbeedfd3d702011-08-28 12:56:51 -0700704 compiling = false; // assume skip
705 if (PrettyMethod(method).find("virtualCall") != std::string::npos) {
706 compiling = true;
707 }
buzbeedd3efae2011-08-28 14:39:07 -0700708 if (PrettyMethod(method).find("getFoo") != std::string::npos) {
709 compiling = true;
710 }
711 if (PrettyMethod(method).find("setFoo") != std::string::npos) {
712 compiling = true;
713 }
buzbeedfd3d702011-08-28 12:56:51 -0700714 if (PrettyMethod(method).find("IntMath.<init>") != std::string::npos) {
715 compiling = true;
716 }
717 if (PrettyMethod(method).find("java.lang.Object.<init>") != std::string::npos) {
718 compiling = true;
719 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700720 } else if (method->GetName()->ToModifiedUtf8().find("foo") != std::string::npos) {
buzbee439c4fa2011-08-27 15:59:07 -0700721 compiling = false;
722 }
723
724 if (compiling) {
buzbeedfd3d702011-08-28 12:56:51 -0700725 LOG(INFO) << "Compiling " << PrettyMethod(method);
buzbee439c4fa2011-08-27 15:59:07 -0700726 } else {
buzbeedfd3d702011-08-28 12:56:51 -0700727 LOG(INFO) << "not compiling " << PrettyMethod(method);
Brian Carlstrom94496d32011-08-22 09:22:47 -0700728 return false;
729 }
730
buzbee67bf8852011-08-17 17:51:35 -0700731 CompilationUnit cUnit;
buzbeec143c552011-08-20 17:38:58 -0700732 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
733 const art::DexFile& dex_file = class_linker->FindDexFile(
734 method->GetDeclaringClass()->GetDexCache());
735 const art::DexFile::CodeItem* code_item =
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700736 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbeec143c552011-08-20 17:38:58 -0700737 const u2* codePtr = code_item->insns_;
738 const u2* codeEnd = code_item->insns_ + code_item->insns_size_;
buzbee67bf8852011-08-17 17:51:35 -0700739 int numBlocks = 0;
740 unsigned int curOffset = 0;
741
742#if 1
743 // FIXME - temp 'till properly integrated
744 oatInit();
745#endif
746
747 memset(&cUnit, 0, sizeof(cUnit));
748 cUnit.method = method;
buzbeec143c552011-08-20 17:38:58 -0700749 cUnit.instructionSet = (OatInstructionSetType)insnSet;
750 cUnit.insns = code_item->insns_;
751 cUnit.insnsSize = code_item->insns_size_;
buzbee67bf8852011-08-17 17:51:35 -0700752#if 1
buzbee3ea4ec52011-08-22 17:37:19 -0700753 // TODO: Use command-line argument passing mechanism
buzbee67bf8852011-08-17 17:51:35 -0700754 cUnit.printMe = true;
755 cUnit.printMeVerbose = true;
buzbee3ea4ec52011-08-22 17:37:19 -0700756 cUnit.disableOpt = 0 |
757 (1 << kLoadStoreElimination) |
758 (1 << kLoadHoisting) |
759 (1 << kTrackLiveTemps) |
760 (1 << kSuppressLoads) |
761 (1 << kPromoteRegs) |
762 0;
buzbee67bf8852011-08-17 17:51:35 -0700763#endif
764
765 /* Initialize the block list */
766 oatInitGrowableList(&cUnit.blockList, 40);
767
768 /* Initialize the switchTables list */
769 oatInitGrowableList(&cUnit.switchTables, 4);
770
771 /* Intialize the fillArrayData list */
772 oatInitGrowableList(&cUnit.fillArrayData, 4);
773
774 /* Allocate the bit-vector to track the beginning of basic blocks */
775 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit.insnsSize,
776 true /* expandable */);
777 cUnit.tryBlockAddr = tryBlockAddr;
778
779 /* Create the default entry and exit blocks and enter them to the list */
780 BasicBlock *entryBlock = oatNewBB(kEntryBlock, numBlocks++);
781 BasicBlock *exitBlock = oatNewBB(kExitBlock, numBlocks++);
782
783 cUnit.entryBlock = entryBlock;
784 cUnit.exitBlock = exitBlock;
785
786 oatInsertGrowableList(&cUnit.blockList, (intptr_t) entryBlock);
787 oatInsertGrowableList(&cUnit.blockList, (intptr_t) exitBlock);
788
789 /* Current block to record parsed instructions */
790 BasicBlock *curBlock = oatNewBB(kDalvikByteCode, numBlocks++);
791 curBlock->startOffset = 0;
792 oatInsertGrowableList(&cUnit.blockList, (intptr_t) curBlock);
793 entryBlock->fallThrough = curBlock;
794 oatSetBit(curBlock->predecessors, entryBlock->id);
795
796 /*
797 * Store back the number of blocks since new blocks may be created of
798 * accessing cUnit.
799 */
800 cUnit.numBlocks = numBlocks;
801
802 /* Identify code range in try blocks and set up the empty catch blocks */
803 processTryCatchBlocks(&cUnit);
804
805 /* Parse all instructions and put them into containing basic blocks */
806 while (codePtr < codeEnd) {
807 MIR *insn = (MIR *) oatNew(sizeof(MIR), true);
808 insn->offset = curOffset;
809 int width = parseInsn(codePtr, &insn->dalvikInsn, false);
810 insn->width = width;
811
812 /* Terminate when the data section is seen */
813 if (width == 0)
814 break;
815
816 oatAppendMIR(curBlock, insn);
817
818 codePtr += width;
819 int flags = dexGetFlagsFromOpcode(insn->dalvikInsn.opcode);
820
821 if (flags & kInstrCanBranch) {
822 processCanBranch(&cUnit, curBlock, insn, curOffset, width, flags,
823 codePtr, codeEnd);
824 } else if (flags & kInstrCanReturn) {
825 curBlock->fallThrough = exitBlock;
826 oatSetBit(exitBlock->predecessors, curBlock->id);
827 /*
828 * Terminate the current block if there are instructions
829 * afterwards.
830 */
831 if (codePtr < codeEnd) {
832 /*
833 * Create a fallthrough block for real instructions
834 * (incl. OP_NOP).
835 */
836 if (contentIsInsn(codePtr)) {
837 findBlock(&cUnit, curOffset + width,
838 /* split */
839 false,
840 /* create */
841 true);
842 }
843 }
844 } else if (flags & kInstrCanThrow) {
845 processCanThrow(&cUnit, curBlock, insn, curOffset, width, flags,
846 tryBlockAddr, codePtr, codeEnd);
847 } else if (flags & kInstrCanSwitch) {
848 processCanSwitch(&cUnit, curBlock, insn, curOffset, width, flags);
849 }
850 curOffset += width;
851 BasicBlock *nextBlock = findBlock(&cUnit, curOffset,
852 /* split */
853 false,
854 /* create */
855 false);
856 if (nextBlock) {
857 /*
858 * The next instruction could be the target of a previously parsed
859 * forward branch so a block is already created. If the current
860 * instruction is not an unconditional branch, connect them through
861 * the fall-through link.
862 */
863 assert(curBlock->fallThrough == NULL ||
864 curBlock->fallThrough == nextBlock ||
865 curBlock->fallThrough == exitBlock);
866
867 if ((curBlock->fallThrough == NULL) &&
868 (flags & kInstrCanContinue)) {
869 curBlock->fallThrough = nextBlock;
870 oatSetBit(nextBlock->predecessors, curBlock->id);
871 }
872 curBlock = nextBlock;
873 }
874 }
875
876 if (cUnit.printMe) {
877 oatDumpCompilationUnit(&cUnit);
878 }
879
880 /* Adjust this value accordingly once inlining is performed */
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700881 cUnit.numDalvikRegisters = cUnit.method->NumRegisters();
buzbee67bf8852011-08-17 17:51:35 -0700882
883
884 /* Verify if all blocks are connected as claimed */
885 oatDataFlowAnalysisDispatcher(&cUnit, verifyPredInfo,
886 kAllNodes,
887 false /* isIterative */);
888
889
890
891 /* Perform SSA transformation for the whole method */
892 oatMethodSSATransformation(&cUnit);
893
894 oatInitializeRegAlloc(&cUnit); // Needs to happen after SSA naming
895
896 /* Allocate Registers using simple local allocation scheme */
897 oatSimpleRegAlloc(&cUnit);
898
899 /* Convert MIR to LIR, etc. */
900 oatMethodMIR2LIR(&cUnit);
901
902 // Debugging only
903 //oatDumpCFG(&cUnit, "/sdcard/cfg/");
904
905 /* Method is not empty */
906 if (cUnit.firstLIRInsn) {
907
908 // mark the targets of switch statement case labels
909 oatProcessSwitchTables(&cUnit);
910
911 /* Convert LIR into machine code. */
912 oatAssembleLIR(&cUnit);
913
914 if (cUnit.printMe) {
915 oatCodegenDump(&cUnit);
916 }
917 }
918
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700919 art::ByteArray* managed_code = art::ByteArray::Alloc(cUnit.codeBuffer.size() * 2);
920 memcpy(managed_code->GetData(),
921 reinterpret_cast<const int8_t*>(&cUnit.codeBuffer[0]),
922 managed_code->GetLength());
923 method->SetCode(managed_code, art::kThumb2);
Shih-wei Liaod11af152011-08-23 16:02:11 -0700924 method->SetFrameSizeInBytes(cUnit.frameSize);
buzbeec143c552011-08-20 17:38:58 -0700925 method->SetCoreSpillMask(cUnit.coreSpillMask);
926 method->SetFpSpillMask(cUnit.fpSpillMask);
927 // TODO: Transmit mapping table to caller
buzbee67bf8852011-08-17 17:51:35 -0700928
929#if 0
930 oatDumpCFG(&cUnit, "/sdcard/cfg/");
931#endif
932
Brian Carlstrombffb1552011-08-25 12:23:53 -0700933 return true;
buzbee67bf8852011-08-17 17:51:35 -0700934}
935
936void oatInit(void)
937{
938#if 1
939 // FIXME - temp hack 'till properly integrated
940 static bool initialized = false;
941 if (initialized)
942 return;
943 initialized = true;
944 LOG(INFO) << "Initializing compiler";
945#endif
946 if (!oatArchInit()) {
947 LOG(FATAL) << "Failed to initialize oat";
948 }
949 if (!oatHeapInit()) {
950 LOG(FATAL) << "Failed to initialize oat heap";
951 }
952}