blob: 902839dd707e095140a7ab7f3d046437aa428c88 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2013 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 */
Dragos Sbirleadb063062013-07-23 16:29:09 -070016#include "base/stringprintf.h"
Dragos Sbirleabfaf44f2013-08-06 15:41:44 -070017#include "sea_ir/ir/instruction_tools.h"
18#include "sea_ir/ir/sea.h"
19#include "sea_ir/code_gen/code_gen.h"
20#include "sea_ir/types/type_inference.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#define MAX_REACHING_DEF_ITERERATIONS (10)
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070023// TODO: When development is done, this define should not
24// be needed, it is currently used as a cutoff
25// for cases where the iterative fixed point algorithm
26// does not reach a fixed point because of a bug.
Brian Carlstrom7940e442013-07-12 13:46:57 -070027
28namespace sea_ir {
29
Brian Carlstrom7940e442013-07-12 13:46:57 -070030int SeaNode::current_max_node_id_ = 0;
31
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070032void IRVisitor::Traverse(Region* region) {
33 std::vector<PhiInstructionNode*>* phis = region->GetPhiNodes();
34 for (std::vector<PhiInstructionNode*>::const_iterator cit = phis->begin();
35 cit != phis->end(); cit++) {
36 (*cit)->Accept(this);
37 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070038 std::vector<InstructionNode*>* instructions = region->GetInstructions();
39 for (std::vector<InstructionNode*>::const_iterator cit = instructions->begin();
40 cit != instructions->end(); cit++) {
41 (*cit)->Accept(this);
42 }
43}
44
45void IRVisitor::Traverse(SeaGraph* graph) {
46 for (std::vector<Region*>::const_iterator cit = ordered_regions_.begin();
47 cit != ordered_regions_.end(); cit++ ) {
48 (*cit)->Accept(this);
49 }
50}
Brian Carlstrom7940e442013-07-12 13:46:57 -070051
Dragos Sbirleaa3519a42013-08-07 14:41:55 -070052SeaGraph* SeaGraph::GetGraph(const art::DexFile& dex_file) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070053 return new SeaGraph(dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -070054}
55
Brian Carlstrom7940e442013-07-12 13:46:57 -070056void SeaGraph::AddEdge(Region* src, Region* dst) const {
57 src->AddSuccessor(dst);
58 dst->AddPredecessor(src);
59}
60
Brian Carlstrom1db91132013-07-12 18:05:20 -070061void SeaGraph::ComputeRPO(Region* current_region, int& current_rpo) {
62 current_region->SetRPO(VISITING);
63 std::vector<sea_ir::Region*>* succs = current_region->GetSuccessors();
64 for (std::vector<sea_ir::Region*>::iterator succ_it = succs->begin();
65 succ_it != succs->end(); ++succ_it) {
66 if (NOT_VISITED == (*succ_it)->GetRPO()) {
67 SeaGraph::ComputeRPO(*succ_it, current_rpo);
68 }
69 }
70 current_region->SetRPO(current_rpo--);
71}
72
73void SeaGraph::ComputeIDominators() {
74 bool changed = true;
75 while (changed) {
76 changed = false;
77 // Entry node has itself as IDOM.
78 std::vector<Region*>::iterator crt_it;
79 std::set<Region*> processedNodes;
80 // Find and mark the entry node(s).
81 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
82 if ((*crt_it)->GetPredecessors()->size() == 0) {
83 processedNodes.insert(*crt_it);
84 (*crt_it)->SetIDominator(*crt_it);
85 }
86 }
87 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
88 if ((*crt_it)->GetPredecessors()->size() == 0) {
89 continue;
90 }
91 // NewIDom = first (processed) predecessor of b.
92 Region* new_dom = NULL;
93 std::vector<Region*>* preds = (*crt_it)->GetPredecessors();
94 DCHECK(NULL != preds);
95 Region* root_pred = NULL;
96 for (std::vector<Region*>::iterator pred_it = preds->begin();
97 pred_it != preds->end(); ++pred_it) {
98 if (processedNodes.end() != processedNodes.find((*pred_it))) {
99 root_pred = *pred_it;
100 new_dom = root_pred;
101 break;
102 }
103 }
104 // For all other predecessors p of b, if idom is not set,
105 // then NewIdom = Intersect(p, NewIdom)
106 for (std::vector<Region*>::const_iterator pred_it = preds->begin();
107 pred_it != preds->end(); ++pred_it) {
108 DCHECK(NULL != *pred_it);
109 // if IDOMS[p] != UNDEFINED
110 if ((*pred_it != root_pred) && (*pred_it)->GetIDominator() != NULL) {
111 DCHECK(NULL != new_dom);
112 new_dom = SeaGraph::Intersect(*pred_it, new_dom);
113 }
114 }
115 DCHECK(NULL != *crt_it);
116 if ((*crt_it)->GetIDominator() != new_dom) {
117 (*crt_it)->SetIDominator(new_dom);
118 changed = true;
119 }
120 processedNodes.insert(*crt_it);
121 }
122 }
123
124 // For easily ordering of regions we need edges dominator->dominated.
125 for (std::vector<Region*>::iterator region_it = regions_.begin();
126 region_it != regions_.end(); region_it++) {
127 Region* idom = (*region_it)->GetIDominator();
128 if (idom != *region_it) {
129 idom->AddToIDominatedSet(*region_it);
130 }
131 }
132}
133
134Region* SeaGraph::Intersect(Region* i, Region* j) {
135 Region* finger1 = i;
136 Region* finger2 = j;
137 while (finger1 != finger2) {
138 while (finger1->GetRPO() > finger2->GetRPO()) {
139 DCHECK(NULL != finger1);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700140 finger1 = finger1->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700141 DCHECK(NULL != finger1);
142 }
143 while (finger1->GetRPO() < finger2->GetRPO()) {
144 DCHECK(NULL != finger2);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700145 finger2 = finger2->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700146 DCHECK(NULL != finger2);
147 }
148 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700149 return finger1; // finger1 should be equal to finger2 at this point.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700150}
151
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152void SeaGraph::ComputeDownExposedDefs() {
153 for (std::vector<Region*>::iterator region_it = regions_.begin();
154 region_it != regions_.end(); region_it++) {
155 (*region_it)->ComputeDownExposedDefs();
156 }
157}
158
159void SeaGraph::ComputeReachingDefs() {
160 // Iterate until the reaching definitions set doesn't change anymore.
161 // (See Cooper & Torczon, "Engineering a Compiler", second edition, page 487)
162 bool changed = true;
163 int iteration = 0;
164 while (changed && (iteration < MAX_REACHING_DEF_ITERERATIONS)) {
165 iteration++;
166 changed = false;
167 // TODO: optimize the ordering if this becomes performance bottleneck.
168 for (std::vector<Region*>::iterator regions_it = regions_.begin();
169 regions_it != regions_.end();
170 regions_it++) {
171 changed |= (*regions_it)->UpdateReachingDefs();
172 }
173 }
174 DCHECK(!changed) << "Reaching definitions computation did not reach a fixed point.";
175}
176
177
Brian Carlstrom1db91132013-07-12 18:05:20 -0700178void SeaGraph::BuildMethodSeaGraph(const art::DexFile::CodeItem* code_item,
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700179 const art::DexFile& dex_file, uint32_t class_def_idx,
180 uint32_t method_idx, uint32_t method_access_flags) {
181 code_item_ = code_item;
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700182 class_def_idx_ = class_def_idx;
183 method_idx_ = method_idx;
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700184 method_access_flags_ = method_access_flags;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 const uint16_t* code = code_item->insns_;
186 const size_t size_in_code_units = code_item->insns_size_in_code_units_;
Brian Carlstrom1db91132013-07-12 18:05:20 -0700187 // This maps target instruction pointers to their corresponding region objects.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 std::map<const uint16_t*, Region*> target_regions;
189 size_t i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 // Pass: Find the start instruction of basic blocks
191 // by locating targets and flow-though instructions of branches.
192 while (i < size_in_code_units) {
193 const art::Instruction* inst = art::Instruction::At(&code[i]);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700194 if (inst->IsBranch() || inst->IsUnconditional()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 int32_t offset = inst->GetTargetOffset();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700196 if (target_regions.end() == target_regions.find(&code[i + offset])) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700198 target_regions.insert(std::pair<const uint16_t*, Region*>(&code[i + offset], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700200 if (inst->CanFlowThrough()
201 && (target_regions.end() == target_regions.find(&code[i + inst->SizeInCodeUnits()]))) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700202 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700203 target_regions.insert(
204 std::pair<const uint16_t*, Region*>(&code[i + inst->SizeInCodeUnits()], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 }
206 }
207 i += inst->SizeInCodeUnits();
208 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700209
210
211 Region* r = GetNewRegion();
212 // Insert one SignatureNode per function argument,
213 // to serve as placeholder definitions in dataflow analysis.
214 for (unsigned int crt_offset = 0; crt_offset < code_item->ins_size_; crt_offset++) {
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700215 int position = crt_offset; // TODO: Is this the correct offset in the signature?
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700216 SignatureNode* parameter_def_node =
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700217 new sea_ir::SignatureNode(code_item->registers_size_ - 1 - crt_offset, position);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700218 AddParameterNode(parameter_def_node);
219 r->AddChild(parameter_def_node);
220 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700221 // Pass: Assign instructions to region nodes and
222 // assign branches their control flow successors.
223 i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 sea_ir::InstructionNode* last_node = NULL;
225 sea_ir::InstructionNode* node = NULL;
226 while (i < size_in_code_units) {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700227 const art::Instruction* inst = art::Instruction::At(&code[i]);
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700228 std::vector<InstructionNode*> sea_instructions_for_dalvik =
229 sea_ir::InstructionNode::Create(inst);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700230 for (std::vector<InstructionNode*>::const_iterator cit = sea_instructions_for_dalvik.begin();
231 sea_instructions_for_dalvik.end() != cit; ++cit) {
232 last_node = node;
233 node = *cit;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700235 if (inst->IsBranch() || inst->IsUnconditional()) {
236 int32_t offset = inst->GetTargetOffset();
237 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i + offset]);
238 DCHECK(it != target_regions.end());
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700239 AddEdge(r, it->second); // Add edge to branch target.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700241 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i]);
242 if (target_regions.end() != it) {
243 // Get the already created region because this is a branch target.
244 Region* nextRegion = it->second;
245 if (last_node->GetInstruction()->IsBranch()
246 && last_node->GetInstruction()->CanFlowThrough()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700247 AddEdge(r, it->second); // Add flow-through edge.
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700248 }
249 r = nextRegion;
250 }
Dragos Sbirlea64479192013-08-01 15:38:43 -0700251 r->AddChild(node);
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700252 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 i += inst->SizeInCodeUnits();
254 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700255}
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256
Brian Carlstrom1db91132013-07-12 18:05:20 -0700257void SeaGraph::ComputeRPO() {
258 int rpo_id = regions_.size() - 1;
259 for (std::vector<Region*>::const_iterator crt_it = regions_.begin(); crt_it != regions_.end();
260 ++crt_it) {
261 if ((*crt_it)->GetPredecessors()->size() == 0) {
262 ComputeRPO(*crt_it, rpo_id);
263 }
264 }
265}
266
267// Performs the renaming phase in traditional SSA transformations.
268// See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
269void SeaGraph::RenameAsSSA() {
270 utils::ScopedHashtable<int, InstructionNode*> scoped_table;
271 scoped_table.OpenScope();
272 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
273 region_it++) {
274 if ((*region_it)->GetIDominator() == *region_it) {
275 RenameAsSSA(*region_it, &scoped_table);
276 }
277 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700278 scoped_table.CloseScope();
279}
280
281void SeaGraph::ConvertToSSA() {
282 // Pass: find global names.
283 // The map @block maps registers to the blocks in which they are defined.
284 std::map<int, std::set<Region*> > blocks;
285 // The set @globals records registers whose use
286 // is in a different block than the corresponding definition.
287 std::set<int> globals;
288 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
289 region_it++) {
290 std::set<int> var_kill;
291 std::vector<InstructionNode*>* instructions = (*region_it)->GetInstructions();
292 for (std::vector<InstructionNode*>::iterator inst_it = instructions->begin();
293 inst_it != instructions->end(); inst_it++) {
294 std::vector<int> used_regs = (*inst_it)->GetUses();
295 for (std::size_t i = 0; i < used_regs.size(); i++) {
296 int used_reg = used_regs[i];
297 if (var_kill.find(used_reg) == var_kill.end()) {
298 globals.insert(used_reg);
299 }
300 }
301 const int reg_def = (*inst_it)->GetResultRegister();
302 if (reg_def != NO_REGISTER) {
303 var_kill.insert(reg_def);
304 }
305
306 blocks.insert(std::pair<int, std::set<Region*> >(reg_def, std::set<Region*>()));
307 std::set<Region*>* reg_def_blocks = &(blocks.find(reg_def)->second);
308 reg_def_blocks->insert(*region_it);
309 }
310 }
311
312 // Pass: Actually add phi-nodes to regions.
313 for (std::set<int>::const_iterator globals_it = globals.begin();
314 globals_it != globals.end(); globals_it++) {
315 int global = *globals_it;
316 // Copy the set, because we will modify the worklist as we go.
317 std::set<Region*> worklist((*(blocks.find(global))).second);
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700318 for (std::set<Region*>::const_iterator b_it = worklist.begin();
319 b_it != worklist.end(); b_it++) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700320 std::set<Region*>* df = (*b_it)->GetDominanceFrontier();
321 for (std::set<Region*>::const_iterator df_it = df->begin(); df_it != df->end(); df_it++) {
322 if ((*df_it)->InsertPhiFor(global)) {
323 // Check that the dominance frontier element is in the worklist already
324 // because we only want to break if the element is actually not there yet.
325 if (worklist.find(*df_it) == worklist.end()) {
326 worklist.insert(*df_it);
327 b_it = worklist.begin();
328 break;
329 }
330 }
331 }
332 }
333 }
334 // Pass: Build edges to the definition corresponding to each use.
335 // (This corresponds to the renaming phase in traditional SSA transformations.
336 // See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
337 RenameAsSSA();
338}
339
340void SeaGraph::RenameAsSSA(Region* crt_region,
341 utils::ScopedHashtable<int, InstructionNode*>* scoped_table) {
342 scoped_table->OpenScope();
343 // Rename phi nodes defined in the current region.
344 std::vector<PhiInstructionNode*>* phis = crt_region->GetPhiNodes();
345 for (std::vector<PhiInstructionNode*>::iterator phi_it = phis->begin();
346 phi_it != phis->end(); phi_it++) {
347 int reg_no = (*phi_it)->GetRegisterNumber();
348 scoped_table->Add(reg_no, (*phi_it));
349 }
350 // Rename operands of instructions from the current region.
351 std::vector<InstructionNode*>* instructions = crt_region->GetInstructions();
352 for (std::vector<InstructionNode*>::const_iterator instructions_it = instructions->begin();
353 instructions_it != instructions->end(); instructions_it++) {
354 InstructionNode* current_instruction = (*instructions_it);
355 // Rename uses.
356 std::vector<int> used_regs = current_instruction->GetUses();
357 for (std::vector<int>::const_iterator reg_it = used_regs.begin();
358 reg_it != used_regs.end(); reg_it++) {
359 int current_used_reg = (*reg_it);
360 InstructionNode* definition = scoped_table->Lookup(current_used_reg);
361 current_instruction->RenameToSSA(current_used_reg, definition);
362 }
363 // Update scope table with latest definitions.
364 std::vector<int> def_regs = current_instruction->GetDefinitions();
365 for (std::vector<int>::const_iterator reg_it = def_regs.begin();
366 reg_it != def_regs.end(); reg_it++) {
367 int current_defined_reg = (*reg_it);
368 scoped_table->Add(current_defined_reg, current_instruction);
369 }
370 }
371 // Fill in uses of phi functions in CFG successor regions.
372 const std::vector<Region*>* successors = crt_region->GetSuccessors();
373 for (std::vector<Region*>::const_iterator successors_it = successors->begin();
374 successors_it != successors->end(); successors_it++) {
375 Region* successor = (*successors_it);
376 successor->SetPhiDefinitionsForUses(scoped_table, crt_region);
377 }
378
379 // Rename all successors in the dominators tree.
380 const std::set<Region*>* dominated_nodes = crt_region->GetIDominatedSet();
381 for (std::set<Region*>::const_iterator dominated_nodes_it = dominated_nodes->begin();
382 dominated_nodes_it != dominated_nodes->end(); dominated_nodes_it++) {
383 Region* dominated_node = (*dominated_nodes_it);
384 RenameAsSSA(dominated_node, scoped_table);
385 }
386 scoped_table->CloseScope();
387}
388
Dragos Sbirleabd136a22013-08-13 18:07:04 -0700389CodeGenData* SeaGraph::GenerateLLVM() {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700390 // Pass: Generate LLVM IR.
391 CodeGenPrepassVisitor code_gen_prepass_visitor;
392 std::cout << "Generating code..." << std::endl;
393 std::cout << "=== PRE VISITING ===" << std::endl;
394 Accept(&code_gen_prepass_visitor);
395 CodeGenVisitor code_gen_visitor(code_gen_prepass_visitor.GetData());
396 std::cout << "=== VISITING ===" << std::endl;
397 Accept(&code_gen_visitor);
398 std::cout << "=== POST VISITING ===" << std::endl;
399 CodeGenPostpassVisitor code_gen_postpass_visitor(code_gen_visitor.GetData());
400 Accept(&code_gen_postpass_visitor);
401 code_gen_postpass_visitor.Write(std::string("my_file.llvm"));
Dragos Sbirleabd136a22013-08-13 18:07:04 -0700402 return code_gen_postpass_visitor.GetData();
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700403}
404
Dragos Sbirleabd136a22013-08-13 18:07:04 -0700405CodeGenData* SeaGraph::CompileMethod(
406 const art::DexFile::CodeItem* code_item, uint32_t class_def_idx,
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700407 uint32_t method_idx, uint32_t method_access_flags, const art::DexFile& dex_file) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700408 // Two passes: Builds the intermediate structure (non-SSA) of the sea-ir for the function.
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700409 BuildMethodSeaGraph(code_item, dex_file, class_def_idx, method_idx, method_access_flags);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700410 // Pass: Compute reverse post-order of regions.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700411 ComputeRPO();
412 // Multiple passes: compute immediate dominators.
413 ComputeIDominators();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414 // Pass: compute downward-exposed definitions.
415 ComputeDownExposedDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700416 // Multiple Passes (iterative fixed-point algorithm): Compute reaching definitions
Brian Carlstrom7940e442013-07-12 13:46:57 -0700417 ComputeReachingDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700418 // Pass (O(nlogN)): Compute the dominance frontier for region nodes.
419 ComputeDominanceFrontier();
420 // Two Passes: Phi node insertion.
421 ConvertToSSA();
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700422 // Pass: type inference
Dragos Sbirlea64479192013-08-01 15:38:43 -0700423 ti_->ComputeTypes(this);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700424 // Pass: Generate LLVM IR.
Dragos Sbirleabd136a22013-08-13 18:07:04 -0700425 CodeGenData* cgd = GenerateLLVM();
426 return cgd;
Brian Carlstrom1db91132013-07-12 18:05:20 -0700427}
428
Brian Carlstrom1db91132013-07-12 18:05:20 -0700429void SeaGraph::ComputeDominanceFrontier() {
430 for (std::vector<Region*>::iterator region_it = regions_.begin();
431 region_it != regions_.end(); region_it++) {
432 std::vector<Region*>* preds = (*region_it)->GetPredecessors();
433 if (preds->size() > 1) {
434 for (std::vector<Region*>::iterator pred_it = preds->begin();
435 pred_it != preds->end(); pred_it++) {
436 Region* runner = *pred_it;
437 while (runner != (*region_it)->GetIDominator()) {
438 runner->AddToDominanceFrontier(*region_it);
439 runner = runner->GetIDominator();
440 }
441 }
442 }
443 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700444}
445
446Region* SeaGraph::GetNewRegion() {
447 Region* new_region = new Region();
448 AddRegion(new_region);
449 return new_region;
450}
451
452void SeaGraph::AddRegion(Region* r) {
453 DCHECK(r) << "Tried to add NULL region to SEA graph.";
454 regions_.push_back(r);
455}
456
Dragos Sbirlea64479192013-08-01 15:38:43 -0700457SeaGraph::SeaGraph(const art::DexFile& df)
458 :ti_(new TypeInference()), class_def_idx_(0), method_idx_(0), method_access_flags_(),
459 regions_(), parameters_(), dex_file_(df), code_item_(NULL) { }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700460
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461void Region::AddChild(sea_ir::InstructionNode* instruction) {
462 DCHECK(instruction) << "Tried to add NULL instruction to region node.";
463 instructions_.push_back(instruction);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700464 instruction->SetRegion(this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465}
466
467SeaNode* Region::GetLastChild() const {
468 if (instructions_.size() > 0) {
469 return instructions_.back();
470 }
471 return NULL;
472}
473
Brian Carlstrom7940e442013-07-12 13:46:57 -0700474void Region::ComputeDownExposedDefs() {
475 for (std::vector<InstructionNode*>::const_iterator inst_it = instructions_.begin();
476 inst_it != instructions_.end(); inst_it++) {
477 int reg_no = (*inst_it)->GetResultRegister();
478 std::map<int, InstructionNode*>::iterator res = de_defs_.find(reg_no);
479 if ((reg_no != NO_REGISTER) && (res == de_defs_.end())) {
480 de_defs_.insert(std::pair<int, InstructionNode*>(reg_no, *inst_it));
481 } else {
482 res->second = *inst_it;
483 }
484 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485 for (std::map<int, sea_ir::InstructionNode*>::const_iterator cit = de_defs_.begin();
486 cit != de_defs_.end(); cit++) {
487 (*cit).second->MarkAsDEDef();
488 }
489}
490
Brian Carlstrom7940e442013-07-12 13:46:57 -0700491const std::map<int, sea_ir::InstructionNode*>* Region::GetDownExposedDefs() const {
492 return &de_defs_;
493}
494
495std::map<int, std::set<sea_ir::InstructionNode*>* >* Region::GetReachingDefs() {
496 return &reaching_defs_;
497}
498
499bool Region::UpdateReachingDefs() {
500 std::map<int, std::set<sea_ir::InstructionNode*>* > new_reaching;
501 for (std::vector<Region*>::const_iterator pred_it = predecessors_.begin();
502 pred_it != predecessors_.end(); pred_it++) {
503 // The reaching_defs variable will contain reaching defs __for current predecessor only__
504 std::map<int, std::set<sea_ir::InstructionNode*>* > reaching_defs;
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700505 std::map<int, std::set<sea_ir::InstructionNode*>* >* pred_reaching =
506 (*pred_it)->GetReachingDefs();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700507 const std::map<int, InstructionNode*>* de_defs = (*pred_it)->GetDownExposedDefs();
508
509 // The definitions from the reaching set of the predecessor
510 // may be shadowed by downward exposed definitions from the predecessor,
511 // otherwise the defs from the reaching set are still good.
512 for (std::map<int, InstructionNode*>::const_iterator de_def = de_defs->begin();
513 de_def != de_defs->end(); de_def++) {
514 std::set<InstructionNode*>* solo_def;
515 solo_def = new std::set<InstructionNode*>();
516 solo_def->insert(de_def->second);
517 reaching_defs.insert(
518 std::pair<int const, std::set<InstructionNode*>*>(de_def->first, solo_def));
519 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700520 reaching_defs.insert(pred_reaching->begin(), pred_reaching->end());
521
522 // Now we combine the reaching map coming from the current predecessor (reaching_defs)
523 // with the accumulated set from all predecessors so far (from new_reaching).
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700524 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it =
525 reaching_defs.begin();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700526 for (; reaching_it != reaching_defs.end(); reaching_it++) {
527 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator crt_entry =
528 new_reaching.find(reaching_it->first);
529 if (new_reaching.end() != crt_entry) {
530 crt_entry->second->insert(reaching_it->second->begin(), reaching_it->second->end());
531 } else {
532 new_reaching.insert(
533 std::pair<int, std::set<sea_ir::InstructionNode*>*>(
534 reaching_it->first,
535 reaching_it->second) );
536 }
537 }
538 }
539 bool changed = false;
540 // Because the sets are monotonically increasing,
541 // we can compare sizes instead of using set comparison.
542 // TODO: Find formal proof.
543 int old_size = 0;
544 if (-1 == reaching_defs_size_) {
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700545 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it =
546 reaching_defs_.begin();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547 for (; reaching_it != reaching_defs_.end(); reaching_it++) {
548 old_size += (*reaching_it).second->size();
549 }
550 } else {
551 old_size = reaching_defs_size_;
552 }
553 int new_size = 0;
554 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it = new_reaching.begin();
555 for (; reaching_it != new_reaching.end(); reaching_it++) {
556 new_size += (*reaching_it).second->size();
557 }
558 if (old_size != new_size) {
559 changed = true;
560 }
561 if (changed) {
562 reaching_defs_ = new_reaching;
563 reaching_defs_size_ = new_size;
564 }
565 return changed;
566}
567
Brian Carlstrom1db91132013-07-12 18:05:20 -0700568bool Region::InsertPhiFor(int reg_no) {
569 if (!ContainsPhiFor(reg_no)) {
570 phi_set_.insert(reg_no);
571 PhiInstructionNode* new_phi = new PhiInstructionNode(reg_no);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700572 new_phi->SetRegion(this);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700573 phi_instructions_.push_back(new_phi);
574 return true;
575 }
576 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577}
578
Brian Carlstrom1db91132013-07-12 18:05:20 -0700579void Region::SetPhiDefinitionsForUses(
580 const utils::ScopedHashtable<int, InstructionNode*>* scoped_table, Region* predecessor) {
581 int predecessor_id = -1;
582 for (unsigned int crt_pred_id = 0; crt_pred_id < predecessors_.size(); crt_pred_id++) {
583 if (predecessors_.at(crt_pred_id) == predecessor) {
584 predecessor_id = crt_pred_id;
585 }
586 }
587 DCHECK_NE(-1, predecessor_id);
588 for (std::vector<PhiInstructionNode*>::iterator phi_it = phi_instructions_.begin();
589 phi_it != phi_instructions_.end(); phi_it++) {
590 PhiInstructionNode* phi = (*phi_it);
591 int reg_no = phi->GetRegisterNumber();
592 InstructionNode* definition = scoped_table->Lookup(reg_no);
593 phi->RenameToSSA(reg_no, definition, predecessor_id);
594 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595}
596
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700597std::vector<InstructionNode*> InstructionNode::Create(const art::Instruction* in) {
598 std::vector<InstructionNode*> sea_instructions;
599 switch (in->Opcode()) {
600 case art::Instruction::CONST_4:
601 sea_instructions.push_back(new ConstInstructionNode(in));
602 break;
603 case art::Instruction::RETURN:
604 sea_instructions.push_back(new ReturnInstructionNode(in));
605 break;
606 case art::Instruction::IF_NE:
607 sea_instructions.push_back(new IfNeInstructionNode(in));
608 break;
609 case art::Instruction::ADD_INT_LIT8:
610 sea_instructions.push_back(new UnnamedConstInstructionNode(in, in->VRegB_22b()));
611 sea_instructions.push_back(new AddIntLitInstructionNode(in));
612 break;
613 case art::Instruction::MOVE_RESULT:
614 sea_instructions.push_back(new MoveResultInstructionNode(in));
615 break;
616 case art::Instruction::INVOKE_STATIC:
617 sea_instructions.push_back(new InvokeStaticInstructionNode(in));
618 break;
619 case art::Instruction::ADD_INT:
620 sea_instructions.push_back(new AddIntInstructionNode(in));
621 break;
622 case art::Instruction::GOTO:
623 sea_instructions.push_back(new GotoInstructionNode(in));
624 break;
625 case art::Instruction::IF_EQZ:
626 sea_instructions.push_back(new IfEqzInstructionNode(in));
627 break;
628 default:
629 // Default, generic IR instruction node; default case should never be reached
630 // when support for all instructions ahs been added.
631 sea_instructions.push_back(new InstructionNode(in));
632 }
633 return sea_instructions;
634}
635
Brian Carlstrom1db91132013-07-12 18:05:20 -0700636void InstructionNode::MarkAsDEDef() {
637 de_def_ = true;
638}
639
640int InstructionNode::GetResultRegister() const {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700641 if (instruction_->HasVRegA() && InstructionTools::IsDefinition(instruction_)) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700642 return instruction_->VRegA();
643 }
644 return NO_REGISTER;
645}
646
647std::vector<int> InstructionNode::GetDefinitions() const {
648 // TODO: Extend this to handle instructions defining more than one register (if any)
649 // The return value should be changed to pointer to field then; for now it is an object
650 // so that we avoid possible memory leaks from allocating objects dynamically.
651 std::vector<int> definitions;
652 int result = GetResultRegister();
653 if (NO_REGISTER != result) {
654 definitions.push_back(result);
655 }
656 return definitions;
657}
658
Dragos Sbirlea64479192013-08-01 15:38:43 -0700659std::vector<int> InstructionNode::GetUses() const {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700660 std::vector<int> uses; // Using vector<> instead of set<> because order matters.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700661 if (!InstructionTools::IsDefinition(instruction_) && (instruction_->HasVRegA())) {
662 int vA = instruction_->VRegA();
663 uses.push_back(vA);
664 }
665 if (instruction_->HasVRegB()) {
666 int vB = instruction_->VRegB();
667 uses.push_back(vB);
668 }
669 if (instruction_->HasVRegC()) {
670 int vC = instruction_->VRegC();
671 uses.push_back(vC);
672 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700673 return uses;
674}
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700675} // namespace sea_ir