blob: 585b2aa83ce2cad5b76a458d00618326de499631 [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070017#include "file_output_stream.h"
Brian Carlstrom1db91132013-07-12 18:05:20 -070018#include "instruction_tools.h"
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070019#include "sea.h"
20#include "code_gen.h"
Dragos Sbirleab40eddf2013-07-31 13:37:31 -070021#include "types/type_inference.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#define MAX_REACHING_DEF_ITERERATIONS (10)
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070024// TODO: When development is done, this define should not
25// be needed, it is currently used as a cutoff
26// for cases where the iterative fixed point algorithm
27// does not reach a fixed point because of a bug.
Brian Carlstrom7940e442013-07-12 13:46:57 -070028
29namespace sea_ir {
30
Brian Carlstrom7940e442013-07-12 13:46:57 -070031int SeaNode::current_max_node_id_ = 0;
32
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070033void IRVisitor::Traverse(Region* region) {
34 std::vector<PhiInstructionNode*>* phis = region->GetPhiNodes();
35 for (std::vector<PhiInstructionNode*>::const_iterator cit = phis->begin();
36 cit != phis->end(); cit++) {
37 (*cit)->Accept(this);
38 }
39
40 std::vector<InstructionNode*>* instructions = region->GetInstructions();
41 for (std::vector<InstructionNode*>::const_iterator cit = instructions->begin();
42 cit != instructions->end(); cit++) {
43 (*cit)->Accept(this);
44 }
45}
46
47void IRVisitor::Traverse(SeaGraph* graph) {
48 for (std::vector<Region*>::const_iterator cit = ordered_regions_.begin();
49 cit != ordered_regions_.end(); cit++ ) {
50 (*cit)->Accept(this);
51 }
52}
Brian Carlstrom7940e442013-07-12 13:46:57 -070053
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070054SeaGraph* SeaGraph::GetCurrentGraph(const art::DexFile& dex_file) {
55 return new SeaGraph(dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -070056}
57
58void SeaGraph::DumpSea(std::string filename) const {
Brian Carlstrom1db91132013-07-12 18:05:20 -070059 LOG(INFO) << "Starting to write SEA string to file.";
Brian Carlstrom7940e442013-07-12 13:46:57 -070060 std::string result;
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070061 result += "digraph seaOfNodes {\ncompound=true\n";
Brian Carlstrom7940e442013-07-12 13:46:57 -070062 for (std::vector<Region*>::const_iterator cit = regions_.begin(); cit != regions_.end(); cit++) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070063 (*cit)->ToDot(result, dex_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -070064 }
65 result += "}\n";
66 art::File* file = art::OS::OpenFile(filename.c_str(), true, true);
67 art::FileOutputStream fos(file);
68 fos.WriteFully(result.c_str(), result.size());
69 LOG(INFO) << "Written SEA string to file.";
70}
71
72void SeaGraph::AddEdge(Region* src, Region* dst) const {
73 src->AddSuccessor(dst);
74 dst->AddPredecessor(src);
75}
76
Brian Carlstrom1db91132013-07-12 18:05:20 -070077void SeaGraph::ComputeRPO(Region* current_region, int& current_rpo) {
78 current_region->SetRPO(VISITING);
79 std::vector<sea_ir::Region*>* succs = current_region->GetSuccessors();
80 for (std::vector<sea_ir::Region*>::iterator succ_it = succs->begin();
81 succ_it != succs->end(); ++succ_it) {
82 if (NOT_VISITED == (*succ_it)->GetRPO()) {
83 SeaGraph::ComputeRPO(*succ_it, current_rpo);
84 }
85 }
86 current_region->SetRPO(current_rpo--);
87}
88
89void SeaGraph::ComputeIDominators() {
90 bool changed = true;
91 while (changed) {
92 changed = false;
93 // Entry node has itself as IDOM.
94 std::vector<Region*>::iterator crt_it;
95 std::set<Region*> processedNodes;
96 // Find and mark the entry node(s).
97 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
98 if ((*crt_it)->GetPredecessors()->size() == 0) {
99 processedNodes.insert(*crt_it);
100 (*crt_it)->SetIDominator(*crt_it);
101 }
102 }
103 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
104 if ((*crt_it)->GetPredecessors()->size() == 0) {
105 continue;
106 }
107 // NewIDom = first (processed) predecessor of b.
108 Region* new_dom = NULL;
109 std::vector<Region*>* preds = (*crt_it)->GetPredecessors();
110 DCHECK(NULL != preds);
111 Region* root_pred = NULL;
112 for (std::vector<Region*>::iterator pred_it = preds->begin();
113 pred_it != preds->end(); ++pred_it) {
114 if (processedNodes.end() != processedNodes.find((*pred_it))) {
115 root_pred = *pred_it;
116 new_dom = root_pred;
117 break;
118 }
119 }
120 // For all other predecessors p of b, if idom is not set,
121 // then NewIdom = Intersect(p, NewIdom)
122 for (std::vector<Region*>::const_iterator pred_it = preds->begin();
123 pred_it != preds->end(); ++pred_it) {
124 DCHECK(NULL != *pred_it);
125 // if IDOMS[p] != UNDEFINED
126 if ((*pred_it != root_pred) && (*pred_it)->GetIDominator() != NULL) {
127 DCHECK(NULL != new_dom);
128 new_dom = SeaGraph::Intersect(*pred_it, new_dom);
129 }
130 }
131 DCHECK(NULL != *crt_it);
132 if ((*crt_it)->GetIDominator() != new_dom) {
133 (*crt_it)->SetIDominator(new_dom);
134 changed = true;
135 }
136 processedNodes.insert(*crt_it);
137 }
138 }
139
140 // For easily ordering of regions we need edges dominator->dominated.
141 for (std::vector<Region*>::iterator region_it = regions_.begin();
142 region_it != regions_.end(); region_it++) {
143 Region* idom = (*region_it)->GetIDominator();
144 if (idom != *region_it) {
145 idom->AddToIDominatedSet(*region_it);
146 }
147 }
148}
149
150Region* SeaGraph::Intersect(Region* i, Region* j) {
151 Region* finger1 = i;
152 Region* finger2 = j;
153 while (finger1 != finger2) {
154 while (finger1->GetRPO() > finger2->GetRPO()) {
155 DCHECK(NULL != finger1);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700156 finger1 = finger1->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700157 DCHECK(NULL != finger1);
158 }
159 while (finger1->GetRPO() < finger2->GetRPO()) {
160 DCHECK(NULL != finger2);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700161 finger2 = finger2->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700162 DCHECK(NULL != finger2);
163 }
164 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700165 return finger1; // finger1 should be equal to finger2 at this point.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700166}
167
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168void SeaGraph::ComputeDownExposedDefs() {
169 for (std::vector<Region*>::iterator region_it = regions_.begin();
170 region_it != regions_.end(); region_it++) {
171 (*region_it)->ComputeDownExposedDefs();
172 }
173}
174
175void SeaGraph::ComputeReachingDefs() {
176 // Iterate until the reaching definitions set doesn't change anymore.
177 // (See Cooper & Torczon, "Engineering a Compiler", second edition, page 487)
178 bool changed = true;
179 int iteration = 0;
180 while (changed && (iteration < MAX_REACHING_DEF_ITERERATIONS)) {
181 iteration++;
182 changed = false;
183 // TODO: optimize the ordering if this becomes performance bottleneck.
184 for (std::vector<Region*>::iterator regions_it = regions_.begin();
185 regions_it != regions_.end();
186 regions_it++) {
187 changed |= (*regions_it)->UpdateReachingDefs();
188 }
189 }
190 DCHECK(!changed) << "Reaching definitions computation did not reach a fixed point.";
191}
192
193
Brian Carlstrom1db91132013-07-12 18:05:20 -0700194void SeaGraph::BuildMethodSeaGraph(const art::DexFile::CodeItem* code_item,
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700195 const art::DexFile& dex_file, uint32_t class_def_idx,
196 uint32_t method_idx, uint32_t method_access_flags) {
197 code_item_ = code_item;
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700198 class_def_idx_ = class_def_idx;
199 method_idx_ = method_idx;
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700200 method_access_flags_ = method_access_flags;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 const uint16_t* code = code_item->insns_;
202 const size_t size_in_code_units = code_item->insns_size_in_code_units_;
Brian Carlstrom1db91132013-07-12 18:05:20 -0700203 // This maps target instruction pointers to their corresponding region objects.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700204 std::map<const uint16_t*, Region*> target_regions;
205 size_t i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700206 // Pass: Find the start instruction of basic blocks
207 // by locating targets and flow-though instructions of branches.
208 while (i < size_in_code_units) {
209 const art::Instruction* inst = art::Instruction::At(&code[i]);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700210 if (inst->IsBranch() || inst->IsUnconditional()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700211 int32_t offset = inst->GetTargetOffset();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700212 if (target_regions.end() == target_regions.find(&code[i + offset])) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700214 target_regions.insert(std::pair<const uint16_t*, Region*>(&code[i + offset], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700215 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700216 if (inst->CanFlowThrough()
217 && (target_regions.end() == target_regions.find(&code[i + inst->SizeInCodeUnits()]))) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700219 target_regions.insert(
220 std::pair<const uint16_t*, Region*>(&code[i + inst->SizeInCodeUnits()], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700221 }
222 }
223 i += inst->SizeInCodeUnits();
224 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700225
226
227 Region* r = GetNewRegion();
228 // Insert one SignatureNode per function argument,
229 // to serve as placeholder definitions in dataflow analysis.
230 for (unsigned int crt_offset = 0; crt_offset < code_item->ins_size_; crt_offset++) {
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700231 int position = crt_offset; // TODO: Is this the correct offset in the signature?
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700232 SignatureNode* parameter_def_node =
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700233 new sea_ir::SignatureNode(code_item->registers_size_ - 1 - crt_offset, position);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700234 AddParameterNode(parameter_def_node);
235 r->AddChild(parameter_def_node);
236 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 // Pass: Assign instructions to region nodes and
238 // assign branches their control flow successors.
239 i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 sea_ir::InstructionNode* last_node = NULL;
241 sea_ir::InstructionNode* node = NULL;
242 while (i < size_in_code_units) {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700243 const art::Instruction* inst = art::Instruction::At(&code[i]);
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700244 std::vector<InstructionNode*> sea_instructions_for_dalvik =
245 sea_ir::InstructionNode::Create(inst);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700246 for (std::vector<InstructionNode*>::const_iterator cit = sea_instructions_for_dalvik.begin();
247 sea_instructions_for_dalvik.end() != cit; ++cit) {
248 last_node = node;
249 node = *cit;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700250
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700251 if (inst->IsBranch() || inst->IsUnconditional()) {
252 int32_t offset = inst->GetTargetOffset();
253 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i + offset]);
254 DCHECK(it != target_regions.end());
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700255 AddEdge(r, it->second); // Add edge to branch target.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700257 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i]);
258 if (target_regions.end() != it) {
259 // Get the already created region because this is a branch target.
260 Region* nextRegion = it->second;
261 if (last_node->GetInstruction()->IsBranch()
262 && last_node->GetInstruction()->CanFlowThrough()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700263 AddEdge(r, it->second); // Add flow-through edge.
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700264 }
265 r = nextRegion;
266 }
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700267 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700268 i += inst->SizeInCodeUnits();
269 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700270}
Brian Carlstrom7940e442013-07-12 13:46:57 -0700271
Brian Carlstrom1db91132013-07-12 18:05:20 -0700272void SeaGraph::ComputeRPO() {
273 int rpo_id = regions_.size() - 1;
274 for (std::vector<Region*>::const_iterator crt_it = regions_.begin(); crt_it != regions_.end();
275 ++crt_it) {
276 if ((*crt_it)->GetPredecessors()->size() == 0) {
277 ComputeRPO(*crt_it, rpo_id);
278 }
279 }
280}
281
282// Performs the renaming phase in traditional SSA transformations.
283// See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
284void SeaGraph::RenameAsSSA() {
285 utils::ScopedHashtable<int, InstructionNode*> scoped_table;
286 scoped_table.OpenScope();
287 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
288 region_it++) {
289 if ((*region_it)->GetIDominator() == *region_it) {
290 RenameAsSSA(*region_it, &scoped_table);
291 }
292 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700293 scoped_table.CloseScope();
294}
295
296void SeaGraph::ConvertToSSA() {
297 // Pass: find global names.
298 // The map @block maps registers to the blocks in which they are defined.
299 std::map<int, std::set<Region*> > blocks;
300 // The set @globals records registers whose use
301 // is in a different block than the corresponding definition.
302 std::set<int> globals;
303 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
304 region_it++) {
305 std::set<int> var_kill;
306 std::vector<InstructionNode*>* instructions = (*region_it)->GetInstructions();
307 for (std::vector<InstructionNode*>::iterator inst_it = instructions->begin();
308 inst_it != instructions->end(); inst_it++) {
309 std::vector<int> used_regs = (*inst_it)->GetUses();
310 for (std::size_t i = 0; i < used_regs.size(); i++) {
311 int used_reg = used_regs[i];
312 if (var_kill.find(used_reg) == var_kill.end()) {
313 globals.insert(used_reg);
314 }
315 }
316 const int reg_def = (*inst_it)->GetResultRegister();
317 if (reg_def != NO_REGISTER) {
318 var_kill.insert(reg_def);
319 }
320
321 blocks.insert(std::pair<int, std::set<Region*> >(reg_def, std::set<Region*>()));
322 std::set<Region*>* reg_def_blocks = &(blocks.find(reg_def)->second);
323 reg_def_blocks->insert(*region_it);
324 }
325 }
326
327 // Pass: Actually add phi-nodes to regions.
328 for (std::set<int>::const_iterator globals_it = globals.begin();
329 globals_it != globals.end(); globals_it++) {
330 int global = *globals_it;
331 // Copy the set, because we will modify the worklist as we go.
332 std::set<Region*> worklist((*(blocks.find(global))).second);
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700333 for (std::set<Region*>::const_iterator b_it = worklist.begin();
334 b_it != worklist.end(); b_it++) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700335 std::set<Region*>* df = (*b_it)->GetDominanceFrontier();
336 for (std::set<Region*>::const_iterator df_it = df->begin(); df_it != df->end(); df_it++) {
337 if ((*df_it)->InsertPhiFor(global)) {
338 // Check that the dominance frontier element is in the worklist already
339 // because we only want to break if the element is actually not there yet.
340 if (worklist.find(*df_it) == worklist.end()) {
341 worklist.insert(*df_it);
342 b_it = worklist.begin();
343 break;
344 }
345 }
346 }
347 }
348 }
349 // Pass: Build edges to the definition corresponding to each use.
350 // (This corresponds to the renaming phase in traditional SSA transformations.
351 // See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
352 RenameAsSSA();
353}
354
355void SeaGraph::RenameAsSSA(Region* crt_region,
356 utils::ScopedHashtable<int, InstructionNode*>* scoped_table) {
357 scoped_table->OpenScope();
358 // Rename phi nodes defined in the current region.
359 std::vector<PhiInstructionNode*>* phis = crt_region->GetPhiNodes();
360 for (std::vector<PhiInstructionNode*>::iterator phi_it = phis->begin();
361 phi_it != phis->end(); phi_it++) {
362 int reg_no = (*phi_it)->GetRegisterNumber();
363 scoped_table->Add(reg_no, (*phi_it));
364 }
365 // Rename operands of instructions from the current region.
366 std::vector<InstructionNode*>* instructions = crt_region->GetInstructions();
367 for (std::vector<InstructionNode*>::const_iterator instructions_it = instructions->begin();
368 instructions_it != instructions->end(); instructions_it++) {
369 InstructionNode* current_instruction = (*instructions_it);
370 // Rename uses.
371 std::vector<int> used_regs = current_instruction->GetUses();
372 for (std::vector<int>::const_iterator reg_it = used_regs.begin();
373 reg_it != used_regs.end(); reg_it++) {
374 int current_used_reg = (*reg_it);
375 InstructionNode* definition = scoped_table->Lookup(current_used_reg);
376 current_instruction->RenameToSSA(current_used_reg, definition);
377 }
378 // Update scope table with latest definitions.
379 std::vector<int> def_regs = current_instruction->GetDefinitions();
380 for (std::vector<int>::const_iterator reg_it = def_regs.begin();
381 reg_it != def_regs.end(); reg_it++) {
382 int current_defined_reg = (*reg_it);
383 scoped_table->Add(current_defined_reg, current_instruction);
384 }
385 }
386 // Fill in uses of phi functions in CFG successor regions.
387 const std::vector<Region*>* successors = crt_region->GetSuccessors();
388 for (std::vector<Region*>::const_iterator successors_it = successors->begin();
389 successors_it != successors->end(); successors_it++) {
390 Region* successor = (*successors_it);
391 successor->SetPhiDefinitionsForUses(scoped_table, crt_region);
392 }
393
394 // Rename all successors in the dominators tree.
395 const std::set<Region*>* dominated_nodes = crt_region->GetIDominatedSet();
396 for (std::set<Region*>::const_iterator dominated_nodes_it = dominated_nodes->begin();
397 dominated_nodes_it != dominated_nodes->end(); dominated_nodes_it++) {
398 Region* dominated_node = (*dominated_nodes_it);
399 RenameAsSSA(dominated_node, scoped_table);
400 }
401 scoped_table->CloseScope();
402}
403
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700404void SeaGraph::GenerateLLVM() {
405 // Pass: Generate LLVM IR.
406 CodeGenPrepassVisitor code_gen_prepass_visitor;
407 std::cout << "Generating code..." << std::endl;
408 std::cout << "=== PRE VISITING ===" << std::endl;
409 Accept(&code_gen_prepass_visitor);
410 CodeGenVisitor code_gen_visitor(code_gen_prepass_visitor.GetData());
411 std::cout << "=== VISITING ===" << std::endl;
412 Accept(&code_gen_visitor);
413 std::cout << "=== POST VISITING ===" << std::endl;
414 CodeGenPostpassVisitor code_gen_postpass_visitor(code_gen_visitor.GetData());
415 Accept(&code_gen_postpass_visitor);
416 code_gen_postpass_visitor.Write(std::string("my_file.llvm"));
417}
418
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700419void SeaGraph::CompileMethod(const art::DexFile::CodeItem* code_item, uint32_t class_def_idx,
420 uint32_t method_idx, uint32_t method_access_flags, const art::DexFile& dex_file) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700421 // Two passes: Builds the intermediate structure (non-SSA) of the sea-ir for the function.
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700422 BuildMethodSeaGraph(code_item, dex_file, class_def_idx, method_idx, method_access_flags);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700423 // Pass: Compute reverse post-order of regions.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700424 ComputeRPO();
425 // Multiple passes: compute immediate dominators.
426 ComputeIDominators();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 // Pass: compute downward-exposed definitions.
428 ComputeDownExposedDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700429 // Multiple Passes (iterative fixed-point algorithm): Compute reaching definitions
Brian Carlstrom7940e442013-07-12 13:46:57 -0700430 ComputeReachingDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700431 // Pass (O(nlogN)): Compute the dominance frontier for region nodes.
432 ComputeDominanceFrontier();
433 // Two Passes: Phi node insertion.
434 ConvertToSSA();
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700435 // Pass: type inference
436 TypeInference ti = TypeInference();
437 ti.ComputeTypes(this);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700438 // Pass: Generate LLVM IR.
439 GenerateLLVM();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700440}
441
Brian Carlstrom1db91132013-07-12 18:05:20 -0700442void SeaGraph::ComputeDominanceFrontier() {
443 for (std::vector<Region*>::iterator region_it = regions_.begin();
444 region_it != regions_.end(); region_it++) {
445 std::vector<Region*>* preds = (*region_it)->GetPredecessors();
446 if (preds->size() > 1) {
447 for (std::vector<Region*>::iterator pred_it = preds->begin();
448 pred_it != preds->end(); pred_it++) {
449 Region* runner = *pred_it;
450 while (runner != (*region_it)->GetIDominator()) {
451 runner->AddToDominanceFrontier(*region_it);
452 runner = runner->GetIDominator();
453 }
454 }
455 }
456 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457}
458
459Region* SeaGraph::GetNewRegion() {
460 Region* new_region = new Region();
461 AddRegion(new_region);
462 return new_region;
463}
464
465void SeaGraph::AddRegion(Region* r) {
466 DCHECK(r) << "Tried to add NULL region to SEA graph.";
467 regions_.push_back(r);
468}
469
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700470/*
Brian Carlstrom1db91132013-07-12 18:05:20 -0700471void SeaNode::AddSuccessor(Region* successor) {
472 DCHECK(successor) << "Tried to add NULL successor to SEA node.";
473 successors_.push_back(successor);
474 return;
475}
476
477void SeaNode::AddPredecessor(Region* predecessor) {
478 DCHECK(predecessor) << "Tried to add NULL predecessor to SEA node.";
479 predecessors_.push_back(predecessor);
480}
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700481*/
Brian Carlstrom7940e442013-07-12 13:46:57 -0700482void Region::AddChild(sea_ir::InstructionNode* instruction) {
483 DCHECK(instruction) << "Tried to add NULL instruction to region node.";
484 instructions_.push_back(instruction);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700485 instruction->SetRegion(this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486}
487
488SeaNode* Region::GetLastChild() const {
489 if (instructions_.size() > 0) {
490 return instructions_.back();
491 }
492 return NULL;
493}
494
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700495void Region::ToDot(std::string& result, const art::DexFile& dex_file) const {
496 result += "\n// Region: \nsubgraph " + StringId() + " { label=\"region " + StringId() + "(rpo=";
Dragos Sbirleadb063062013-07-23 16:29:09 -0700497 result += art::StringPrintf("%d", rpo_number_);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700498 if (NULL != GetIDominator()) {
499 result += " dom=" + GetIDominator()->StringId();
500 }
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700501 result += ")\";\n";
502
503 for (std::vector<PhiInstructionNode*>::const_iterator cit = phi_instructions_.begin();
504 cit != phi_instructions_.end(); cit++) {
505 result += (*cit)->StringId() +";\n";
506 }
507
508 for (std::vector<InstructionNode*>::const_iterator cit = instructions_.begin();
509 cit != instructions_.end(); cit++) {
510 result += (*cit)->StringId() +";\n";
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700511 }
512
513 result += "} // End Region.\n";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700514
515 // Save phi-nodes.
516 for (std::vector<PhiInstructionNode*>::const_iterator cit = phi_instructions_.begin();
517 cit != phi_instructions_.end(); cit++) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700518 (*cit)->ToDot(result, dex_file);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700519 }
520
521 // Save instruction nodes.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700522 for (std::vector<InstructionNode*>::const_iterator cit = instructions_.begin();
523 cit != instructions_.end(); cit++) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700524 (*cit)->ToDot(result, dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700525 }
526
527 for (std::vector<Region*>::const_iterator cit = successors_.begin(); cit != successors_.end();
528 cit++) {
529 DCHECK(NULL != *cit) << "Null successor found for SeaNode" << GetLastChild()->StringId() << ".";
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700530 result += GetLastChild()->StringId() + " -> " + (*cit)->GetLastChild()->StringId() +
531 "[lhead=" + (*cit)->StringId() + ", " + "ltail=" + StringId() + "];\n\n";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700532 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700533}
534
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535void Region::ComputeDownExposedDefs() {
536 for (std::vector<InstructionNode*>::const_iterator inst_it = instructions_.begin();
537 inst_it != instructions_.end(); inst_it++) {
538 int reg_no = (*inst_it)->GetResultRegister();
539 std::map<int, InstructionNode*>::iterator res = de_defs_.find(reg_no);
540 if ((reg_no != NO_REGISTER) && (res == de_defs_.end())) {
541 de_defs_.insert(std::pair<int, InstructionNode*>(reg_no, *inst_it));
542 } else {
543 res->second = *inst_it;
544 }
545 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700546 for (std::map<int, sea_ir::InstructionNode*>::const_iterator cit = de_defs_.begin();
547 cit != de_defs_.end(); cit++) {
548 (*cit).second->MarkAsDEDef();
549 }
550}
551
Brian Carlstrom7940e442013-07-12 13:46:57 -0700552const std::map<int, sea_ir::InstructionNode*>* Region::GetDownExposedDefs() const {
553 return &de_defs_;
554}
555
556std::map<int, std::set<sea_ir::InstructionNode*>* >* Region::GetReachingDefs() {
557 return &reaching_defs_;
558}
559
560bool Region::UpdateReachingDefs() {
561 std::map<int, std::set<sea_ir::InstructionNode*>* > new_reaching;
562 for (std::vector<Region*>::const_iterator pred_it = predecessors_.begin();
563 pred_it != predecessors_.end(); pred_it++) {
564 // The reaching_defs variable will contain reaching defs __for current predecessor only__
565 std::map<int, std::set<sea_ir::InstructionNode*>* > reaching_defs;
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700566 std::map<int, std::set<sea_ir::InstructionNode*>* >* pred_reaching =
567 (*pred_it)->GetReachingDefs();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700568 const std::map<int, InstructionNode*>* de_defs = (*pred_it)->GetDownExposedDefs();
569
570 // The definitions from the reaching set of the predecessor
571 // may be shadowed by downward exposed definitions from the predecessor,
572 // otherwise the defs from the reaching set are still good.
573 for (std::map<int, InstructionNode*>::const_iterator de_def = de_defs->begin();
574 de_def != de_defs->end(); de_def++) {
575 std::set<InstructionNode*>* solo_def;
576 solo_def = new std::set<InstructionNode*>();
577 solo_def->insert(de_def->second);
578 reaching_defs.insert(
579 std::pair<int const, std::set<InstructionNode*>*>(de_def->first, solo_def));
580 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700581 reaching_defs.insert(pred_reaching->begin(), pred_reaching->end());
582
583 // Now we combine the reaching map coming from the current predecessor (reaching_defs)
584 // with the accumulated set from all predecessors so far (from new_reaching).
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700585 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it =
586 reaching_defs.begin();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700587 for (; reaching_it != reaching_defs.end(); reaching_it++) {
588 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator crt_entry =
589 new_reaching.find(reaching_it->first);
590 if (new_reaching.end() != crt_entry) {
591 crt_entry->second->insert(reaching_it->second->begin(), reaching_it->second->end());
592 } else {
593 new_reaching.insert(
594 std::pair<int, std::set<sea_ir::InstructionNode*>*>(
595 reaching_it->first,
596 reaching_it->second) );
597 }
598 }
599 }
600 bool changed = false;
601 // Because the sets are monotonically increasing,
602 // we can compare sizes instead of using set comparison.
603 // TODO: Find formal proof.
604 int old_size = 0;
605 if (-1 == reaching_defs_size_) {
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700606 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it =
607 reaching_defs_.begin();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700608 for (; reaching_it != reaching_defs_.end(); reaching_it++) {
609 old_size += (*reaching_it).second->size();
610 }
611 } else {
612 old_size = reaching_defs_size_;
613 }
614 int new_size = 0;
615 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it = new_reaching.begin();
616 for (; reaching_it != new_reaching.end(); reaching_it++) {
617 new_size += (*reaching_it).second->size();
618 }
619 if (old_size != new_size) {
620 changed = true;
621 }
622 if (changed) {
623 reaching_defs_ = new_reaching;
624 reaching_defs_size_ = new_size;
625 }
626 return changed;
627}
628
Brian Carlstrom1db91132013-07-12 18:05:20 -0700629bool Region::InsertPhiFor(int reg_no) {
630 if (!ContainsPhiFor(reg_no)) {
631 phi_set_.insert(reg_no);
632 PhiInstructionNode* new_phi = new PhiInstructionNode(reg_no);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700633 new_phi->SetRegion(this);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700634 phi_instructions_.push_back(new_phi);
635 return true;
636 }
637 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700638}
639
Brian Carlstrom1db91132013-07-12 18:05:20 -0700640void Region::SetPhiDefinitionsForUses(
641 const utils::ScopedHashtable<int, InstructionNode*>* scoped_table, Region* predecessor) {
642 int predecessor_id = -1;
643 for (unsigned int crt_pred_id = 0; crt_pred_id < predecessors_.size(); crt_pred_id++) {
644 if (predecessors_.at(crt_pred_id) == predecessor) {
645 predecessor_id = crt_pred_id;
646 }
647 }
648 DCHECK_NE(-1, predecessor_id);
649 for (std::vector<PhiInstructionNode*>::iterator phi_it = phi_instructions_.begin();
650 phi_it != phi_instructions_.end(); phi_it++) {
651 PhiInstructionNode* phi = (*phi_it);
652 int reg_no = phi->GetRegisterNumber();
653 InstructionNode* definition = scoped_table->Lookup(reg_no);
654 phi->RenameToSSA(reg_no, definition, predecessor_id);
655 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700656}
657
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700658std::vector<InstructionNode*> InstructionNode::Create(const art::Instruction* in) {
659 std::vector<InstructionNode*> sea_instructions;
660 switch (in->Opcode()) {
661 case art::Instruction::CONST_4:
662 sea_instructions.push_back(new ConstInstructionNode(in));
663 break;
664 case art::Instruction::RETURN:
665 sea_instructions.push_back(new ReturnInstructionNode(in));
666 break;
667 case art::Instruction::IF_NE:
668 sea_instructions.push_back(new IfNeInstructionNode(in));
669 break;
670 case art::Instruction::ADD_INT_LIT8:
671 sea_instructions.push_back(new UnnamedConstInstructionNode(in, in->VRegB_22b()));
672 sea_instructions.push_back(new AddIntLitInstructionNode(in));
673 break;
674 case art::Instruction::MOVE_RESULT:
675 sea_instructions.push_back(new MoveResultInstructionNode(in));
676 break;
677 case art::Instruction::INVOKE_STATIC:
678 sea_instructions.push_back(new InvokeStaticInstructionNode(in));
679 break;
680 case art::Instruction::ADD_INT:
681 sea_instructions.push_back(new AddIntInstructionNode(in));
682 break;
683 case art::Instruction::GOTO:
684 sea_instructions.push_back(new GotoInstructionNode(in));
685 break;
686 case art::Instruction::IF_EQZ:
687 sea_instructions.push_back(new IfEqzInstructionNode(in));
688 break;
689 default:
690 // Default, generic IR instruction node; default case should never be reached
691 // when support for all instructions ahs been added.
692 sea_instructions.push_back(new InstructionNode(in));
693 }
694 return sea_instructions;
695}
696
Dragos Sbirleae2245322013-07-29 14:16:14 -0700697void InstructionNode::ToDotSSAEdges(std::string& result) const {
698 // SSA definitions:
699 for (std::map<int, InstructionNode*>::const_iterator def_it = definition_edges_.begin();
700 def_it != definition_edges_.end(); def_it++) {
701 if (NULL != def_it->second) {
702 result += def_it->second->StringId() + " -> " + StringId() + "[color=gray,label=\"";
703 result += art::StringPrintf("vR = %d", def_it->first);
704 result += "\"] ; // ssa edge\n";
705 }
706 }
707
708 // SSA used-by:
709 if (DotConversion::SaveUseEdges()) {
Dragos Sbirleab4dcf652013-07-29 16:49:56 -0700710 for (std::vector<InstructionNode*>::const_iterator cit = used_in_.begin();
711 cit != used_in_.end(); cit++) {
Dragos Sbirleae2245322013-07-29 14:16:14 -0700712 result += (*cit)->StringId() + " -> " + StringId() + "[color=gray,label=\"";
713 result += "\"] ; // SSA used-by edge\n";
714 }
715 }
716}
717
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700718void InstructionNode::ToDot(std::string& result, const art::DexFile& dex_file) const {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700719 result += "// Instruction ("+StringId()+"): \n" + StringId() +
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700720 " [label=\"" + instruction_->DumpString(&dex_file) + "\"";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700721 if (de_def_) {
722 result += "style=bold";
723 }
724 result += "];\n";
Dragos Sbirleae2245322013-07-29 14:16:14 -0700725
726 ToDotSSAEdges(result);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700727}
728
729void InstructionNode::MarkAsDEDef() {
730 de_def_ = true;
731}
732
733int InstructionNode::GetResultRegister() const {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700734 if (instruction_->HasVRegA() && InstructionTools::IsDefinition(instruction_)) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700735 return instruction_->VRegA();
736 }
737 return NO_REGISTER;
738}
739
740std::vector<int> InstructionNode::GetDefinitions() const {
741 // TODO: Extend this to handle instructions defining more than one register (if any)
742 // The return value should be changed to pointer to field then; for now it is an object
743 // so that we avoid possible memory leaks from allocating objects dynamically.
744 std::vector<int> definitions;
745 int result = GetResultRegister();
746 if (NO_REGISTER != result) {
747 definitions.push_back(result);
748 }
749 return definitions;
750}
751
752std::vector<int> InstructionNode::GetUses() {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700753 std::vector<int> uses; // Using vector<> instead of set<> because order matters.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700754 if (!InstructionTools::IsDefinition(instruction_) && (instruction_->HasVRegA())) {
755 int vA = instruction_->VRegA();
756 uses.push_back(vA);
757 }
758 if (instruction_->HasVRegB()) {
759 int vB = instruction_->VRegB();
760 uses.push_back(vB);
761 }
762 if (instruction_->HasVRegC()) {
763 int vC = instruction_->VRegC();
764 uses.push_back(vC);
765 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700766 return uses;
767}
768
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700769void PhiInstructionNode::ToDot(std::string& result, const art::DexFile& dex_file) const {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700770 result += "// PhiInstruction: \n" + StringId() +
771 " [label=\"" + "PHI(";
Dragos Sbirlea81f79a62013-07-23 14:31:47 -0700772 result += art::StringPrintf("%d", register_no_);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700773 result += ")\"";
774 result += "];\n";
Dragos Sbirleae2245322013-07-29 14:16:14 -0700775 ToDotSSAEdges(result);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700776}
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700777} // namespace sea_ir