blob: 429d1553fb7c3d87738ec114b9c41e98b716ffa6 [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
buzbeece302932011-10-04 14:32:18 -070024/* Default optimizer/debug setting for the compiler. */
25uint32_t compilerOptimizerDisableFlags = 0 | // Disable specific optimizations
26 // TODO: enable all of these by default in ToT
27 (1 << kLoadStoreElimination) |
28 (1 << kLoadHoisting) |
29 (1 << kSuppressLoads) |
30 (1 << kNullCheckElimination) |
31 (1 << kPromoteRegs) |
32 (1 << kTrackLiveTemps) |
33 0;
34
35uint32_t compilerDebugFlags = 0 | // Enable debug/testing modes
buzbeee3de7492011-10-05 13:37:17 -070036 //(1 << kDebugDisplayMissingTargets) |
buzbeece302932011-10-04 14:32:18 -070037 //(1 << kDebugVerbose) |
38 //(1 << kDebugDumpCFG) |
39 //(1 << kDebugSlowFieldPath) |
40 //(1 << kDebugSlowInvokePath) |
41 //(1 << kDebugSlowStringPath) |
42 //(1 << kDebugSlowestFieldPath) |
43 //(1 << kDebugSlowestStringPath) |
44 0;
45
46std::string compilerMethodMatch; // Method name match to apply above flags
47
48bool compilerFlipMatch = false; // Reverses sense of method name match
49
buzbeeed3e9302011-09-23 17:34:19 -070050STATIC inline bool contentIsInsn(const u2* codePtr) {
buzbee67bf8852011-08-17 17:51:35 -070051 u2 instr = *codePtr;
52 Opcode opcode = (Opcode)(instr & 0xff);
53
54 /*
55 * Since the low 8-bit in metadata may look like OP_NOP, we need to check
56 * both the low and whole sub-word to determine whether it is code or data.
57 */
58 return (opcode != OP_NOP || instr == 0);
59}
60
61/*
62 * Parse an instruction, return the length of the instruction
63 */
buzbeeed3e9302011-09-23 17:34:19 -070064STATIC inline int parseInsn(const u2* codePtr, DecodedInstruction* decInsn,
buzbee67bf8852011-08-17 17:51:35 -070065 bool printMe)
66{
67 // Don't parse instruction data
68 if (!contentIsInsn(codePtr)) {
69 return 0;
70 }
71
72 u2 instr = *codePtr;
73 Opcode opcode = dexOpcodeFromCodeUnit(instr);
74
75 dexDecodeInstruction(codePtr, decInsn);
76 if (printMe) {
77 char *decodedString = oatGetDalvikDisassembly(decInsn, NULL);
78 LOG(INFO) << codePtr << ": 0x" << std::hex << (int)opcode <<
79 " " << decodedString;
80 }
81 return dexGetWidthFromOpcode(opcode);
82}
83
84#define UNKNOWN_TARGET 0xffffffff
85
buzbeeed3e9302011-09-23 17:34:19 -070086STATIC inline bool isGoto(MIR* insn)
buzbee67bf8852011-08-17 17:51:35 -070087{
88 switch (insn->dalvikInsn.opcode) {
89 case OP_GOTO:
90 case OP_GOTO_16:
91 case OP_GOTO_32:
92 return true;
93 default:
94 return false;
95 }
96}
97
98/*
99 * Identify unconditional branch instructions
100 */
buzbeeed3e9302011-09-23 17:34:19 -0700101STATIC inline bool isUnconditionalBranch(MIR* insn)
buzbee67bf8852011-08-17 17:51:35 -0700102{
103 switch (insn->dalvikInsn.opcode) {
104 case OP_RETURN_VOID:
105 case OP_RETURN:
106 case OP_RETURN_WIDE:
107 case OP_RETURN_OBJECT:
108 return true;
109 default:
110 return isGoto(insn);
111 }
112}
113
114/* Split an existing block from the specified code offset into two */
buzbeeed3e9302011-09-23 17:34:19 -0700115STATIC BasicBlock *splitBlock(CompilationUnit* cUnit,
buzbee67bf8852011-08-17 17:51:35 -0700116 unsigned int codeOffset,
117 BasicBlock* origBlock)
118{
119 MIR* insn = origBlock->firstMIRInsn;
120 while (insn) {
121 if (insn->offset == codeOffset) break;
122 insn = insn->next;
123 }
124 if (insn == NULL) {
125 LOG(FATAL) << "Break split failed";
126 }
127 BasicBlock *bottomBlock = oatNewBB(kDalvikByteCode,
128 cUnit->numBlocks++);
129 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bottomBlock);
130
131 bottomBlock->startOffset = codeOffset;
132 bottomBlock->firstMIRInsn = insn;
133 bottomBlock->lastMIRInsn = origBlock->lastMIRInsn;
134
135 /* Handle the taken path */
136 bottomBlock->taken = origBlock->taken;
137 if (bottomBlock->taken) {
138 origBlock->taken = NULL;
139 oatClearBit(bottomBlock->taken->predecessors, origBlock->id);
140 oatSetBit(bottomBlock->taken->predecessors, bottomBlock->id);
141 }
142
143 /* Handle the fallthrough path */
144 bottomBlock->needFallThroughBranch = origBlock->needFallThroughBranch;
145 bottomBlock->fallThrough = origBlock->fallThrough;
146 origBlock->fallThrough = bottomBlock;
147 origBlock->needFallThroughBranch = true;
148 oatSetBit(bottomBlock->predecessors, origBlock->id);
149 if (bottomBlock->fallThrough) {
150 oatClearBit(bottomBlock->fallThrough->predecessors,
151 origBlock->id);
152 oatSetBit(bottomBlock->fallThrough->predecessors,
153 bottomBlock->id);
154 }
155
156 /* Handle the successor list */
157 if (origBlock->successorBlockList.blockListType != kNotUsed) {
158 bottomBlock->successorBlockList = origBlock->successorBlockList;
159 origBlock->successorBlockList.blockListType = kNotUsed;
160 GrowableListIterator iterator;
161
162 oatGrowableListIteratorInit(&bottomBlock->successorBlockList.blocks,
163 &iterator);
164 while (true) {
165 SuccessorBlockInfo *successorBlockInfo =
166 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
167 if (successorBlockInfo == NULL) break;
168 BasicBlock *bb = successorBlockInfo->block;
169 oatClearBit(bb->predecessors, origBlock->id);
170 oatSetBit(bb->predecessors, bottomBlock->id);
171 }
172 }
173
174 origBlock->lastMIRInsn = insn->prev;
175
176 insn->prev->next = NULL;
177 insn->prev = NULL;
178 return bottomBlock;
179}
180
181/*
182 * Given a code offset, find out the block that starts with it. If the offset
183 * is in the middle of an existing block, split it into two.
184 */
buzbeeed3e9302011-09-23 17:34:19 -0700185STATIC BasicBlock *findBlock(CompilationUnit* cUnit,
buzbee67bf8852011-08-17 17:51:35 -0700186 unsigned int codeOffset,
187 bool split, bool create)
188{
189 GrowableList* blockList = &cUnit->blockList;
190 BasicBlock* bb;
191 unsigned int i;
192
193 for (i = 0; i < blockList->numUsed; i++) {
194 bb = (BasicBlock *) blockList->elemList[i];
195 if (bb->blockType != kDalvikByteCode) continue;
196 if (bb->startOffset == codeOffset) return bb;
197 /* Check if a branch jumps into the middle of an existing block */
198 if ((split == true) && (codeOffset > bb->startOffset) &&
199 (bb->lastMIRInsn != NULL) &&
200 (codeOffset <= bb->lastMIRInsn->offset)) {
201 BasicBlock *newBB = splitBlock(cUnit, codeOffset, bb);
202 return newBB;
203 }
204 }
205 if (create) {
206 bb = oatNewBB(kDalvikByteCode, cUnit->numBlocks++);
207 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bb);
208 bb->startOffset = codeOffset;
209 return bb;
210 }
211 return NULL;
212}
213
214/* Dump the CFG into a DOT graph */
215void oatDumpCFG(CompilationUnit* cUnit, const char* dirPrefix)
216{
buzbee67bf8852011-08-17 17:51:35 -0700217 FILE* file;
buzbeedfd3d702011-08-28 12:56:51 -0700218 std::string name = art::PrettyMethod(cUnit->method);
buzbee67bf8852011-08-17 17:51:35 -0700219 char startOffset[80];
220 sprintf(startOffset, "_%x", cUnit->entryBlock->fallThrough->startOffset);
221 char* fileName = (char *) oatNew(
buzbeec143c552011-08-20 17:38:58 -0700222 strlen(dirPrefix) +
223 name.length() +
224 strlen(".dot") + 1, true);
225 sprintf(fileName, "%s%s%s.dot", dirPrefix, name.c_str(), startOffset);
buzbee67bf8852011-08-17 17:51:35 -0700226
227 /*
228 * Convert the special characters into a filesystem- and shell-friendly
229 * format.
230 */
231 int i;
232 for (i = strlen(dirPrefix); fileName[i]; i++) {
233 if (fileName[i] == '/') {
234 fileName[i] = '_';
235 } else if (fileName[i] == ';') {
236 fileName[i] = '#';
237 } else if (fileName[i] == '$') {
238 fileName[i] = '+';
239 } else if (fileName[i] == '(' || fileName[i] == ')') {
240 fileName[i] = '@';
241 } else if (fileName[i] == '<' || fileName[i] == '>') {
242 fileName[i] = '=';
243 }
244 }
245 file = fopen(fileName, "w");
246 if (file == NULL) {
247 return;
248 }
249 fprintf(file, "digraph G {\n");
250
251 fprintf(file, " rankdir=TB\n");
252
253 int numReachableBlocks = cUnit->numReachableBlocks;
254 int idx;
255 const GrowableList *blockList = &cUnit->blockList;
256
257 for (idx = 0; idx < numReachableBlocks; idx++) {
258 int blockIdx = cUnit->dfsOrder.elemList[idx];
259 BasicBlock *bb = (BasicBlock *) oatGrowableListGetElement(blockList,
260 blockIdx);
261 if (bb == NULL) break;
262 if (bb->blockType == kEntryBlock) {
263 fprintf(file, " entry [shape=Mdiamond];\n");
264 } else if (bb->blockType == kExitBlock) {
265 fprintf(file, " exit [shape=Mdiamond];\n");
266 } else if (bb->blockType == kDalvikByteCode) {
267 fprintf(file, " block%04x [shape=record,label = \"{ \\\n",
268 bb->startOffset);
269 const MIR *mir;
270 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
271 bb->firstMIRInsn ? " | " : " ");
272 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
273 fprintf(file, " {%04x %s\\l}%s\\\n", mir->offset,
274 mir->ssaRep ?
275 oatFullDisassembler(cUnit, mir) :
276 dexGetOpcodeName(mir->dalvikInsn.opcode),
277 mir->next ? " | " : " ");
278 }
279 fprintf(file, " }\"];\n\n");
280 } else if (bb->blockType == kExceptionHandling) {
281 char blockName[BLOCK_NAME_LEN];
282
283 oatGetBlockName(bb, blockName);
284 fprintf(file, " %s [shape=invhouse];\n", blockName);
285 }
286
287 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
288
289 if (bb->taken) {
290 oatGetBlockName(bb, blockName1);
291 oatGetBlockName(bb->taken, blockName2);
292 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
293 blockName1, blockName2);
294 }
295 if (bb->fallThrough) {
296 oatGetBlockName(bb, blockName1);
297 oatGetBlockName(bb->fallThrough, blockName2);
298 fprintf(file, " %s:s -> %s:n\n", blockName1, blockName2);
299 }
300
301 if (bb->successorBlockList.blockListType != kNotUsed) {
302 fprintf(file, " succ%04x [shape=%s,label = \"{ \\\n",
303 bb->startOffset,
304 (bb->successorBlockList.blockListType == kCatch) ?
305 "Mrecord" : "record");
306 GrowableListIterator iterator;
307 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
308 &iterator);
309 SuccessorBlockInfo *successorBlockInfo =
310 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
311
312 int succId = 0;
313 while (true) {
314 if (successorBlockInfo == NULL) break;
315
316 BasicBlock *destBlock = successorBlockInfo->block;
317 SuccessorBlockInfo *nextSuccessorBlockInfo =
318 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
319
320 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
321 succId++,
322 successorBlockInfo->key,
323 destBlock->startOffset,
324 (nextSuccessorBlockInfo != NULL) ? " | " : " ");
325
326 successorBlockInfo = nextSuccessorBlockInfo;
327 }
328 fprintf(file, " }\"];\n\n");
329
330 oatGetBlockName(bb, blockName1);
331 fprintf(file, " %s:s -> succ%04x:n [style=dashed]\n",
332 blockName1, bb->startOffset);
333
334 if (bb->successorBlockList.blockListType == kPackedSwitch ||
335 bb->successorBlockList.blockListType == kSparseSwitch) {
336
337 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
338 &iterator);
339
340 succId = 0;
341 while (true) {
342 SuccessorBlockInfo *successorBlockInfo =
343 (SuccessorBlockInfo *)
344 oatGrowableListIteratorNext(&iterator);
345 if (successorBlockInfo == NULL) break;
346
347 BasicBlock *destBlock = successorBlockInfo->block;
348
349 oatGetBlockName(destBlock, blockName2);
350 fprintf(file, " succ%04x:f%d:e -> %s:n\n",
351 bb->startOffset, succId++,
352 blockName2);
353 }
354 }
355 }
356 fprintf(file, "\n");
357
buzbeece302932011-10-04 14:32:18 -0700358 /* Display the dominator tree */
buzbee67bf8852011-08-17 17:51:35 -0700359 oatGetBlockName(bb, blockName1);
360 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
361 blockName1, blockName1);
362 if (bb->iDom) {
363 oatGetBlockName(bb->iDom, blockName2);
364 fprintf(file, " cfg%s:s -> cfg%s:n\n\n",
365 blockName2, blockName1);
366 }
buzbee67bf8852011-08-17 17:51:35 -0700367 }
368 fprintf(file, "}\n");
369 fclose(file);
370}
371
372/* Verify if all the successor is connected with all the claimed predecessors */
buzbeeed3e9302011-09-23 17:34:19 -0700373STATIC bool verifyPredInfo(CompilationUnit* cUnit, BasicBlock* bb)
buzbee67bf8852011-08-17 17:51:35 -0700374{
375 ArenaBitVectorIterator bvIterator;
376
377 oatBitVectorIteratorInit(bb->predecessors, &bvIterator);
378 while (true) {
379 int blockIdx = oatBitVectorIteratorNext(&bvIterator);
380 if (blockIdx == -1) break;
381 BasicBlock *predBB = (BasicBlock *)
382 oatGrowableListGetElement(&cUnit->blockList, blockIdx);
383 bool found = false;
384 if (predBB->taken == bb) {
385 found = true;
386 } else if (predBB->fallThrough == bb) {
387 found = true;
388 } else if (predBB->successorBlockList.blockListType != kNotUsed) {
389 GrowableListIterator iterator;
390 oatGrowableListIteratorInit(&predBB->successorBlockList.blocks,
391 &iterator);
392 while (true) {
393 SuccessorBlockInfo *successorBlockInfo =
394 (SuccessorBlockInfo *)
395 oatGrowableListIteratorNext(&iterator);
396 if (successorBlockInfo == NULL) break;
397 BasicBlock *succBB = successorBlockInfo->block;
398 if (succBB == bb) {
399 found = true;
400 break;
401 }
402 }
403 }
404 if (found == false) {
405 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
406 oatGetBlockName(bb, blockName1);
407 oatGetBlockName(predBB, blockName2);
408 oatDumpCFG(cUnit, "/sdcard/cfg/");
409 LOG(FATAL) << "Successor " << blockName1 << "not found from "
410 << blockName2;
411 }
412 }
413 return true;
414}
415
416/* Identify code range in try blocks and set up the empty catch blocks */
buzbeeed3e9302011-09-23 17:34:19 -0700417STATIC void processTryCatchBlocks(CompilationUnit* cUnit)
buzbee67bf8852011-08-17 17:51:35 -0700418{
buzbeee9a72f62011-09-04 17:59:07 -0700419 const Method* method = cUnit->method;
420 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
421 const art::DexFile& dex_file = class_linker->FindDexFile(
422 method->GetDeclaringClass()->GetDexCache());
423 const art::DexFile::CodeItem* code_item =
424 dex_file.GetCodeItem(method->GetCodeItemOffset());
425 int triesSize = code_item->tries_size_;
buzbee67bf8852011-08-17 17:51:35 -0700426 int offset;
427
428 if (triesSize == 0) {
429 return;
430 }
431
buzbee67bf8852011-08-17 17:51:35 -0700432 ArenaBitVector* tryBlockAddr = cUnit->tryBlockAddr;
433
buzbeee9a72f62011-09-04 17:59:07 -0700434 for (int i = 0; i < triesSize; i++) {
435 const art::DexFile::TryItem* pTry =
436 art::DexFile::dexGetTryItems(*code_item, i);
437 int startOffset = pTry->start_addr_;
438 int endOffset = startOffset + pTry->insn_count_;
buzbee67bf8852011-08-17 17:51:35 -0700439 for (offset = startOffset; offset < endOffset; offset++) {
440 oatSetBit(tryBlockAddr, offset);
441 }
442 }
443
buzbeee9a72f62011-09-04 17:59:07 -0700444 // Iterate over each of the handlers to enqueue the empty Catch blocks
445 const art::byte* handlers_ptr =
446 art::DexFile::dexGetCatchHandlerData(*code_item, 0);
447 uint32_t handlers_size = art::DecodeUnsignedLeb128(&handlers_ptr);
448 for (uint32_t idx = 0; idx < handlers_size; idx++) {
449 art::DexFile::CatchHandlerIterator iterator(handlers_ptr);
buzbee67bf8852011-08-17 17:51:35 -0700450
buzbeee9a72f62011-09-04 17:59:07 -0700451 for (; !iterator.HasNext(); iterator.Next()) {
452 uint32_t address = iterator.Get().address_;
453 findBlock(cUnit, address, false /* split */, true /*create*/);
buzbee67bf8852011-08-17 17:51:35 -0700454 }
buzbeee9a72f62011-09-04 17:59:07 -0700455 handlers_ptr = iterator.GetData();
buzbee67bf8852011-08-17 17:51:35 -0700456 }
457}
458
459/* Process instructions with the kInstrCanBranch flag */
buzbeeed3e9302011-09-23 17:34:19 -0700460STATIC void processCanBranch(CompilationUnit* cUnit, BasicBlock* curBlock,
buzbee67bf8852011-08-17 17:51:35 -0700461 MIR* insn, int curOffset, int width, int flags,
462 const u2* codePtr, const u2* codeEnd)
463{
464 int target = curOffset;
465 switch (insn->dalvikInsn.opcode) {
466 case OP_GOTO:
467 case OP_GOTO_16:
468 case OP_GOTO_32:
469 target += (int) insn->dalvikInsn.vA;
470 break;
471 case OP_IF_EQ:
472 case OP_IF_NE:
473 case OP_IF_LT:
474 case OP_IF_GE:
475 case OP_IF_GT:
476 case OP_IF_LE:
477 target += (int) insn->dalvikInsn.vC;
478 break;
479 case OP_IF_EQZ:
480 case OP_IF_NEZ:
481 case OP_IF_LTZ:
482 case OP_IF_GEZ:
483 case OP_IF_GTZ:
484 case OP_IF_LEZ:
485 target += (int) insn->dalvikInsn.vB;
486 break;
487 default:
488 LOG(FATAL) << "Unexpected opcode(" << (int)insn->dalvikInsn.opcode
489 << ") with kInstrCanBranch set";
490 }
491 BasicBlock *takenBlock = findBlock(cUnit, target,
492 /* split */
493 true,
494 /* create */
495 true);
496 curBlock->taken = takenBlock;
497 oatSetBit(takenBlock->predecessors, curBlock->id);
498
499 /* Always terminate the current block for conditional branches */
500 if (flags & kInstrCanContinue) {
501 BasicBlock *fallthroughBlock = findBlock(cUnit,
502 curOffset + width,
503 /*
504 * If the method is processed
505 * in sequential order from the
506 * beginning, we don't need to
507 * specify split for continue
508 * blocks. However, this
509 * routine can be called by
510 * compileLoop, which starts
511 * parsing the method from an
512 * arbitrary address in the
513 * method body.
514 */
515 true,
516 /* create */
517 true);
518 curBlock->fallThrough = fallthroughBlock;
519 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
520 } else if (codePtr < codeEnd) {
521 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
522 if (contentIsInsn(codePtr)) {
523 findBlock(cUnit, curOffset + width,
524 /* split */
525 false,
526 /* create */
527 true);
528 }
529 }
530}
531
532/* Process instructions with the kInstrCanSwitch flag */
buzbeeed3e9302011-09-23 17:34:19 -0700533STATIC void processCanSwitch(CompilationUnit* cUnit, BasicBlock* curBlock,
buzbee67bf8852011-08-17 17:51:35 -0700534 MIR* insn, int curOffset, int width, int flags)
535{
536 u2* switchData= (u2 *) (cUnit->insns + curOffset +
537 insn->dalvikInsn.vB);
538 int size;
539 int* keyTable;
540 int* targetTable;
541 int i;
542 int firstKey;
543
544 /*
545 * Packed switch data format:
546 * ushort ident = 0x0100 magic value
547 * ushort size number of entries in the table
548 * int first_key first (and lowest) switch case value
549 * int targets[size] branch targets, relative to switch opcode
550 *
551 * Total size is (4+size*2) 16-bit code units.
552 */
553 if (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) {
buzbeeed3e9302011-09-23 17:34:19 -0700554 DCHECK_EQ(switchData[0], kPackedSwitchSignature);
buzbee67bf8852011-08-17 17:51:35 -0700555 size = switchData[1];
556 firstKey = switchData[2] | (switchData[3] << 16);
557 targetTable = (int *) &switchData[4];
558 keyTable = NULL; // Make the compiler happy
559 /*
560 * Sparse switch data format:
561 * ushort ident = 0x0200 magic value
562 * ushort size number of entries in the table; > 0
563 * int keys[size] keys, sorted low-to-high; 32-bit aligned
564 * int targets[size] branch targets, relative to switch opcode
565 *
566 * Total size is (2+size*4) 16-bit code units.
567 */
568 } else {
buzbeeed3e9302011-09-23 17:34:19 -0700569 DCHECK_EQ(switchData[0], kSparseSwitchSignature);
buzbee67bf8852011-08-17 17:51:35 -0700570 size = switchData[1];
571 keyTable = (int *) &switchData[2];
572 targetTable = (int *) &switchData[2 + size*2];
573 firstKey = 0; // To make the compiler happy
574 }
575
576 if (curBlock->successorBlockList.blockListType != kNotUsed) {
577 LOG(FATAL) << "Successor block list already in use: " <<
578 (int)curBlock->successorBlockList.blockListType;
579 }
580 curBlock->successorBlockList.blockListType =
581 (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) ?
582 kPackedSwitch : kSparseSwitch;
583 oatInitGrowableList(&curBlock->successorBlockList.blocks, size);
584
585 for (i = 0; i < size; i++) {
586 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
587 /* split */
588 true,
589 /* create */
590 true);
591 SuccessorBlockInfo *successorBlockInfo =
592 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
593 false);
594 successorBlockInfo->block = caseBlock;
595 successorBlockInfo->key = (insn->dalvikInsn.opcode == OP_PACKED_SWITCH)?
596 firstKey + i : keyTable[i];
597 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
598 (intptr_t) successorBlockInfo);
599 oatSetBit(caseBlock->predecessors, curBlock->id);
600 }
601
602 /* Fall-through case */
603 BasicBlock* fallthroughBlock = findBlock(cUnit,
604 curOffset + width,
605 /* split */
606 false,
607 /* create */
608 true);
609 curBlock->fallThrough = fallthroughBlock;
610 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
611}
612
613/* Process instructions with the kInstrCanThrow flag */
buzbeeed3e9302011-09-23 17:34:19 -0700614STATIC void processCanThrow(CompilationUnit* cUnit, BasicBlock* curBlock,
buzbee67bf8852011-08-17 17:51:35 -0700615 MIR* insn, int curOffset, int width, int flags,
616 ArenaBitVector* tryBlockAddr, const u2* codePtr,
617 const u2* codeEnd)
618{
buzbeee9a72f62011-09-04 17:59:07 -0700619
buzbee67bf8852011-08-17 17:51:35 -0700620 const Method* method = cUnit->method;
buzbeee9a72f62011-09-04 17:59:07 -0700621 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
622 const art::DexFile& dex_file = class_linker->FindDexFile(
623 method->GetDeclaringClass()->GetDexCache());
624 const art::DexFile::CodeItem* code_item =
625 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbee67bf8852011-08-17 17:51:35 -0700626
627 /* In try block */
628 if (oatIsBitSet(tryBlockAddr, curOffset)) {
buzbeee9a72f62011-09-04 17:59:07 -0700629 art::DexFile::CatchHandlerIterator iterator =
630 art::DexFile::dexFindCatchHandler(*code_item, curOffset);
buzbee67bf8852011-08-17 17:51:35 -0700631
buzbee67bf8852011-08-17 17:51:35 -0700632 if (curBlock->successorBlockList.blockListType != kNotUsed) {
633 LOG(FATAL) << "Successor block list already in use: " <<
634 (int)curBlock->successorBlockList.blockListType;
635 }
buzbeee9a72f62011-09-04 17:59:07 -0700636
buzbee67bf8852011-08-17 17:51:35 -0700637 curBlock->successorBlockList.blockListType = kCatch;
638 oatInitGrowableList(&curBlock->successorBlockList.blocks, 2);
639
buzbeee9a72f62011-09-04 17:59:07 -0700640 for (;!iterator.HasNext(); iterator.Next()) {
641 BasicBlock *catchBlock = findBlock(cUnit, iterator.Get().address_,
642 false /* split*/,
643 false /* creat */);
buzbee43a36422011-09-14 14:00:13 -0700644 catchBlock->catchEntry = true;
buzbee67bf8852011-08-17 17:51:35 -0700645 SuccessorBlockInfo *successorBlockInfo =
buzbeee9a72f62011-09-04 17:59:07 -0700646 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
647 false);
buzbee67bf8852011-08-17 17:51:35 -0700648 successorBlockInfo->block = catchBlock;
buzbeee9a72f62011-09-04 17:59:07 -0700649 successorBlockInfo->key = iterator.Get().type_idx_;
buzbee67bf8852011-08-17 17:51:35 -0700650 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
651 (intptr_t) successorBlockInfo);
652 oatSetBit(catchBlock->predecessors, curBlock->id);
653 }
654 } else {
655 BasicBlock *ehBlock = oatNewBB(kExceptionHandling,
656 cUnit->numBlocks++);
657 curBlock->taken = ehBlock;
658 oatInsertGrowableList(&cUnit->blockList, (intptr_t) ehBlock);
659 ehBlock->startOffset = curOffset;
660 oatSetBit(ehBlock->predecessors, curBlock->id);
661 }
662
663 /*
664 * Force the current block to terminate.
665 *
666 * Data may be present before codeEnd, so we need to parse it to know
667 * whether it is code or data.
668 */
669 if (codePtr < codeEnd) {
670 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
671 if (contentIsInsn(codePtr)) {
672 BasicBlock *fallthroughBlock = findBlock(cUnit,
673 curOffset + width,
674 /* split */
675 false,
676 /* create */
677 true);
678 /*
679 * OP_THROW and OP_THROW_VERIFICATION_ERROR are unconditional
680 * branches.
681 */
682 if (insn->dalvikInsn.opcode != OP_THROW_VERIFICATION_ERROR &&
683 insn->dalvikInsn.opcode != OP_THROW) {
684 curBlock->fallThrough = fallthroughBlock;
685 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
686 }
687 }
688 }
689}
690
691/*
692 * Compile a method.
693 */
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700694CompiledMethod* oatCompileMethod(const Compiler& compiler, const Method* method, art::InstructionSet insnSet)
buzbee67bf8852011-08-17 17:51:35 -0700695{
Brian Carlstrom16192862011-09-12 17:50:06 -0700696 if (compiler.IsVerbose()) {
697 LOG(INFO) << "Compiling " << PrettyMethod(method) << "...";
698 }
buzbee2a475e72011-09-07 17:19:17 -0700699 oatArenaReset();
Brian Carlstrom94496d32011-08-22 09:22:47 -0700700
buzbee67bf8852011-08-17 17:51:35 -0700701 CompilationUnit cUnit;
buzbeec143c552011-08-20 17:38:58 -0700702 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
703 const art::DexFile& dex_file = class_linker->FindDexFile(
704 method->GetDeclaringClass()->GetDexCache());
705 const art::DexFile::CodeItem* code_item =
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700706 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbeec143c552011-08-20 17:38:58 -0700707 const u2* codePtr = code_item->insns_;
708 const u2* codeEnd = code_item->insns_ + code_item->insns_size_;
buzbee67bf8852011-08-17 17:51:35 -0700709 int numBlocks = 0;
710 unsigned int curOffset = 0;
711
Brian Carlstrom16192862011-09-12 17:50:06 -0700712 oatInit(compiler);
buzbee67bf8852011-08-17 17:51:35 -0700713
714 memset(&cUnit, 0, sizeof(cUnit));
715 cUnit.method = method;
buzbeec143c552011-08-20 17:38:58 -0700716 cUnit.instructionSet = (OatInstructionSetType)insnSet;
717 cUnit.insns = code_item->insns_;
718 cUnit.insnsSize = code_item->insns_size_;
buzbeece302932011-10-04 14:32:18 -0700719 bool useMatch = compilerMethodMatch.length() != 0;
720 bool match = useMatch && (compilerFlipMatch ^
721 (PrettyMethod(method).find(compilerMethodMatch) != std::string::npos));
722 if (!useMatch || match) {
723 cUnit.disableOpt = compilerOptimizerDisableFlags;
724 cUnit.enableDebug = compilerDebugFlags;
725 cUnit.printMe = compiler.IsVerbose() ||
726 (cUnit.enableDebug & (1 << kDebugVerbose));
727 }
buzbee67bf8852011-08-17 17:51:35 -0700728
buzbeecefd1872011-09-09 09:59:52 -0700729 /* Assume non-throwing leaf */
730 cUnit.attrs = (METHOD_IS_LEAF | METHOD_IS_THROW_FREE);
731
buzbee67bf8852011-08-17 17:51:35 -0700732 /* Initialize the block list */
733 oatInitGrowableList(&cUnit.blockList, 40);
734
735 /* Initialize the switchTables list */
736 oatInitGrowableList(&cUnit.switchTables, 4);
737
738 /* Intialize the fillArrayData list */
739 oatInitGrowableList(&cUnit.fillArrayData, 4);
740
buzbee5ade1d22011-09-09 14:44:52 -0700741 /* Intialize the throwLaunchpads list */
742 oatInitGrowableList(&cUnit.throwLaunchpads, 4);
743
buzbeec1f45042011-09-21 16:03:19 -0700744 /* Intialize the suspendLaunchpads list */
745 oatInitGrowableList(&cUnit.suspendLaunchpads, 4);
746
buzbee67bf8852011-08-17 17:51:35 -0700747 /* Allocate the bit-vector to track the beginning of basic blocks */
748 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit.insnsSize,
749 true /* expandable */);
750 cUnit.tryBlockAddr = tryBlockAddr;
751
752 /* Create the default entry and exit blocks and enter them to the list */
753 BasicBlock *entryBlock = oatNewBB(kEntryBlock, numBlocks++);
754 BasicBlock *exitBlock = oatNewBB(kExitBlock, numBlocks++);
755
756 cUnit.entryBlock = entryBlock;
757 cUnit.exitBlock = exitBlock;
758
759 oatInsertGrowableList(&cUnit.blockList, (intptr_t) entryBlock);
760 oatInsertGrowableList(&cUnit.blockList, (intptr_t) exitBlock);
761
762 /* Current block to record parsed instructions */
763 BasicBlock *curBlock = oatNewBB(kDalvikByteCode, numBlocks++);
764 curBlock->startOffset = 0;
765 oatInsertGrowableList(&cUnit.blockList, (intptr_t) curBlock);
766 entryBlock->fallThrough = curBlock;
767 oatSetBit(curBlock->predecessors, entryBlock->id);
768
769 /*
770 * Store back the number of blocks since new blocks may be created of
771 * accessing cUnit.
772 */
773 cUnit.numBlocks = numBlocks;
774
775 /* Identify code range in try blocks and set up the empty catch blocks */
776 processTryCatchBlocks(&cUnit);
777
778 /* Parse all instructions and put them into containing basic blocks */
779 while (codePtr < codeEnd) {
780 MIR *insn = (MIR *) oatNew(sizeof(MIR), true);
781 insn->offset = curOffset;
782 int width = parseInsn(codePtr, &insn->dalvikInsn, false);
783 insn->width = width;
784
785 /* Terminate when the data section is seen */
786 if (width == 0)
787 break;
788
789 oatAppendMIR(curBlock, insn);
790
791 codePtr += width;
792 int flags = dexGetFlagsFromOpcode(insn->dalvikInsn.opcode);
793
794 if (flags & kInstrCanBranch) {
795 processCanBranch(&cUnit, curBlock, insn, curOffset, width, flags,
796 codePtr, codeEnd);
797 } else if (flags & kInstrCanReturn) {
798 curBlock->fallThrough = exitBlock;
799 oatSetBit(exitBlock->predecessors, curBlock->id);
800 /*
801 * Terminate the current block if there are instructions
802 * afterwards.
803 */
804 if (codePtr < codeEnd) {
805 /*
806 * Create a fallthrough block for real instructions
807 * (incl. OP_NOP).
808 */
809 if (contentIsInsn(codePtr)) {
810 findBlock(&cUnit, curOffset + width,
811 /* split */
812 false,
813 /* create */
814 true);
815 }
816 }
817 } else if (flags & kInstrCanThrow) {
818 processCanThrow(&cUnit, curBlock, insn, curOffset, width, flags,
819 tryBlockAddr, codePtr, codeEnd);
820 } else if (flags & kInstrCanSwitch) {
821 processCanSwitch(&cUnit, curBlock, insn, curOffset, width, flags);
822 }
823 curOffset += width;
824 BasicBlock *nextBlock = findBlock(&cUnit, curOffset,
825 /* split */
826 false,
827 /* create */
828 false);
829 if (nextBlock) {
830 /*
831 * The next instruction could be the target of a previously parsed
832 * forward branch so a block is already created. If the current
833 * instruction is not an unconditional branch, connect them through
834 * the fall-through link.
835 */
buzbeeed3e9302011-09-23 17:34:19 -0700836 DCHECK(curBlock->fallThrough == NULL ||
buzbee67bf8852011-08-17 17:51:35 -0700837 curBlock->fallThrough == nextBlock ||
838 curBlock->fallThrough == exitBlock);
839
840 if ((curBlock->fallThrough == NULL) &&
841 (flags & kInstrCanContinue)) {
842 curBlock->fallThrough = nextBlock;
843 oatSetBit(nextBlock->predecessors, curBlock->id);
844 }
845 curBlock = nextBlock;
846 }
847 }
848
849 if (cUnit.printMe) {
850 oatDumpCompilationUnit(&cUnit);
851 }
852
853 /* Adjust this value accordingly once inlining is performed */
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700854 cUnit.numDalvikRegisters = cUnit.method->NumRegisters();
buzbee67bf8852011-08-17 17:51:35 -0700855
856
857 /* Verify if all blocks are connected as claimed */
858 oatDataFlowAnalysisDispatcher(&cUnit, verifyPredInfo,
859 kAllNodes,
860 false /* isIterative */);
861
862
863
864 /* Perform SSA transformation for the whole method */
865 oatMethodSSATransformation(&cUnit);
866
buzbee43a36422011-09-14 14:00:13 -0700867 /* Perform null check elimination */
868 oatMethodNullCheckElimination(&cUnit);
869
buzbee67bf8852011-08-17 17:51:35 -0700870 oatInitializeRegAlloc(&cUnit); // Needs to happen after SSA naming
871
872 /* Allocate Registers using simple local allocation scheme */
873 oatSimpleRegAlloc(&cUnit);
874
875 /* Convert MIR to LIR, etc. */
876 oatMethodMIR2LIR(&cUnit);
877
878 // Debugging only
buzbeece302932011-10-04 14:32:18 -0700879 if (cUnit.enableDebug & (1 << kDebugDumpCFG)) {
buzbeeec5adf32011-09-11 15:25:43 -0700880 oatDumpCFG(&cUnit, "/sdcard/cfg/");
881 }
buzbee67bf8852011-08-17 17:51:35 -0700882
883 /* Method is not empty */
884 if (cUnit.firstLIRInsn) {
885
886 // mark the targets of switch statement case labels
887 oatProcessSwitchTables(&cUnit);
888
889 /* Convert LIR into machine code. */
890 oatAssembleLIR(&cUnit);
891
892 if (cUnit.printMe) {
893 oatCodegenDump(&cUnit);
894 }
895 }
896
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700897 // Combine vmap tables - core regs, then fp regs - into vmapTable
898 std::vector<uint16_t> vmapTable;
899 for (size_t i = 0 ; i < cUnit.coreVmapTable.size(); i++) {
900 vmapTable.push_back(cUnit.coreVmapTable[i]);
901 }
buzbeec41e5b52011-09-23 12:46:19 -0700902 // Add a marker to take place of lr
buzbee3ddc0d12011-10-05 10:36:21 -0700903 cUnit.coreVmapTable.push_back(INVALID_VREG);
buzbeec41e5b52011-09-23 12:46:19 -0700904 // Combine vmap tables - core regs, then fp regs
905 for (uint32_t i = 0; i < cUnit.fpVmapTable.size(); i++) {
906 cUnit.coreVmapTable.push_back(cUnit.fpVmapTable[i]);
907 }
908 DCHECK(cUnit.coreVmapTable.size() == (uint32_t)
909 (__builtin_popcount(cUnit.coreSpillMask) +
910 __builtin_popcount(cUnit.fpSpillMask)));
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700911 vmapTable.push_back(-1);
912 for (size_t i = 0; i < cUnit.fpVmapTable.size(); i++) {
913 vmapTable.push_back(cUnit.fpVmapTable[i]);
914 }
915 CompiledMethod* result = new CompiledMethod(art::kThumb2,
916 cUnit.codeBuffer,
917 cUnit.frameSize,
918 cUnit.frameSize - sizeof(intptr_t),
919 cUnit.coreSpillMask,
920 cUnit.fpSpillMask,
921 cUnit.mappingTable,
922 cUnit.coreVmapTable);
923
Brian Carlstrom16192862011-09-12 17:50:06 -0700924 if (compiler.IsVerbose()) {
925 LOG(INFO) << "Compiled " << PrettyMethod(method)
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700926 << " (" << (cUnit.codeBuffer.size() * sizeof(cUnit.codeBuffer[0])) << " bytes)";
Brian Carlstrom16192862011-09-12 17:50:06 -0700927 }
buzbee67bf8852011-08-17 17:51:35 -0700928
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700929 return result;
buzbee67bf8852011-08-17 17:51:35 -0700930}
931
Brian Carlstrom16192862011-09-12 17:50:06 -0700932void oatInit(const Compiler& compiler)
buzbee67bf8852011-08-17 17:51:35 -0700933{
buzbee67bf8852011-08-17 17:51:35 -0700934 static bool initialized = false;
935 if (initialized)
936 return;
937 initialized = true;
Brian Carlstrom16192862011-09-12 17:50:06 -0700938 if (compiler.IsVerbose()) {
939 LOG(INFO) << "Initializing compiler";
940 }
buzbee67bf8852011-08-17 17:51:35 -0700941 if (!oatArchInit()) {
942 LOG(FATAL) << "Failed to initialize oat";
943 }
944 if (!oatHeapInit()) {
945 LOG(FATAL) << "Failed to initialize oat heap";
946 }
947}