Improve the algorithm that marks which actions are needed by FuncNode
[c11tester.git] / funcnode.cc
1 #include "action.h"
2 #include "history.h"
3 #include "funcnode.h"
4 #include "funcinst.h"
5 #include "predicate.h"
6 #include "concretepredicate.h"
7
8 #include "model.h"
9 #include <cmath>
10
11 FuncNode::FuncNode(ModelHistory * history) :
12         history(history),
13         exit_count(0),
14         marker(1),
15         func_inst_map(),
16         inst_list(),
17         entry_insts(),
18         inst_pred_map(128),
19         inst_id_map(128),
20         loc_act_map(128),
21         predicate_tree_position(),
22         predicate_leaves(),
23         leaves_tmp_storage(),
24         weight_debug_vec(),
25         failed_predicates(),
26         edge_table(32),
27         out_edges()
28 {
29         predicate_tree_entry = new Predicate(NULL, true);
30         predicate_tree_entry->add_predicate_expr(NOPREDICATE, NULL, true);
31
32         predicate_tree_exit = new Predicate(NULL, false, true);
33         predicate_tree_exit->set_depth(MAX_DEPTH);
34
35         /* Snapshot data structures below */
36         action_list_buffer = new SnapList<action_list_t *>();
37         read_locations = new loc_set_t();
38         write_locations = new loc_set_t();
39         val_loc_map = new HashTable<uint64_t, loc_set_t *, uint64_t, 0, snapshot_malloc, snapshot_calloc, snapshot_free, int64_hash>();
40         loc_may_equal_map = new HashTable<void *, loc_set_t *, uintptr_t, 0>();
41
42         //values_may_read_from = new value_set_t();
43 }
44
45 /* Reallocate snapshotted memories when new executions start */
46 void FuncNode::set_new_exec_flag()
47 {
48         action_list_buffer = new SnapList<action_list_t *>();
49         read_locations = new loc_set_t();
50         write_locations = new loc_set_t();
51         val_loc_map = new HashTable<uint64_t, loc_set_t *, uint64_t, 0, snapshot_malloc, snapshot_calloc, snapshot_free, int64_hash>();
52         loc_may_equal_map = new HashTable<void *, loc_set_t *, uintptr_t, 0>();
53
54         //values_may_read_from = new value_set_t();
55 }
56
57 /* Check whether FuncInst with the same type, position, and location
58  * as act has been added to func_inst_map or not. If not, add it.
59  */
60 void FuncNode::add_inst(ModelAction *act)
61 {
62         ASSERT(act);
63         const char * position = act->get_position();
64
65         /* THREAD* actions, ATOMIC_LOCK, ATOMIC_TRYLOCK, and ATOMIC_UNLOCK
66          * actions are not tagged with their source line numbers
67          */
68         if (position == NULL)
69                 return;
70
71         FuncInst * func_inst = func_inst_map.get(position);
72
73         /* This position has not been inserted into hashtable before */
74         if (func_inst == NULL) {
75                 func_inst = create_new_inst(act);
76                 func_inst_map.put(position, func_inst);
77                 return;
78         }
79
80         /* Volatile variables that use ++ or -- syntax may result in read and write actions with the same position */
81         if (func_inst->get_type() != act->get_type()) {
82                 FuncInst * collision_inst = func_inst->search_in_collision(act);
83
84                 if (collision_inst == NULL) {
85                         collision_inst = create_new_inst(act);
86                         func_inst->add_to_collision(collision_inst);
87                         return;
88                 } else {
89                         func_inst = collision_inst;
90                 }
91         }
92
93         ASSERT(func_inst->get_type() == act->get_type());
94         int curr_execution_number = model->get_execution_number();
95
96         /* Reset locations when new executions start */
97         if (func_inst->get_execution_number() != curr_execution_number) {
98                 func_inst->set_location(act->get_location());
99                 func_inst->set_execution_number(curr_execution_number);
100         }
101
102         /* Mark the memory location of such inst as not unique */
103         if (func_inst->get_location() != act->get_location())
104                 func_inst->not_single_location();
105 }
106
107 FuncInst * FuncNode::create_new_inst(ModelAction * act)
108 {
109         FuncInst * func_inst = new FuncInst(act, this);
110         int exec_num = model->get_execution_number();
111         func_inst->set_execution_number(exec_num);
112
113         inst_list.push_back(func_inst);
114
115         return func_inst;
116 }
117
118
119 /* Get the FuncInst with the same type, position, and location
120  * as act
121  *
122  * @return FuncInst with the same type, position, and location as act */
123 FuncInst * FuncNode::get_inst(ModelAction *act)
124 {
125         ASSERT(act);
126         const char * position = act->get_position();
127
128         /* THREAD* actions, ATOMIC_LOCK, ATOMIC_TRYLOCK, and ATOMIC_UNLOCK
129          * actions are not tagged with their source line numbers
130          */
131         if (position == NULL)
132                 return NULL;
133
134         FuncInst * inst = func_inst_map.get(position);
135         if (inst == NULL)
136                 return NULL;
137
138         action_type inst_type = inst->get_type();
139         action_type act_type = act->get_type();
140
141         if (inst_type == act_type) {
142                 return inst;
143         }
144         /* RMWRCAS actions are converted to RMW or READ actions */
145         else if (inst_type == ATOMIC_RMWRCAS &&
146                                          (act_type == ATOMIC_RMW || act_type == ATOMIC_READ)) {
147                 return inst;
148         }
149         /* Return the FuncInst in the collision list */
150         else {
151                 return inst->search_in_collision(act);
152         }
153 }
154
155
156 void FuncNode::add_entry_inst(FuncInst * inst)
157 {
158         if (inst == NULL)
159                 return;
160
161         mllnode<FuncInst *> * it;
162         for (it = entry_insts.begin();it != NULL;it = it->getNext()) {
163                 if (inst == it->getVal())
164                         return;
165         }
166
167         entry_insts.push_back(inst);
168 }
169
170 /**
171  * @brief Convert ModelAdtion list to FuncInst list
172  * @param act_list A list of ModelActions
173  */
174 void FuncNode::update_tree(action_list_t * act_list)
175 {
176         if (act_list == NULL || act_list->size() == 0)
177                 return;
178
179         HashTable<void *, value_set_t *, uintptr_t, 0> * write_history = history->getWriteHistory();
180
181         /* build inst_list from act_list for later processing */
182         func_inst_list_t inst_list;
183         action_list_t rw_act_list;
184
185         for (sllnode<ModelAction *> * it = act_list->begin();it != NULL;it = it->getNext()) {
186                 ModelAction * act = it->getVal();
187
188                 // Only ATOMIC_RMW or ATOMIC_WRITE may be swapped with their original types,
189                 // which are later added to rw_act_list. Therefore, it is safe to only revert
190                 // back action types for actions in rw_act_list whose types have been swapped.
191                 if (act->get_original_type() != ATOMIC_NOP && act->get_swap_flag() == false)
192                         act->use_original_type();
193
194                 // Remove func_act_ref so that actions can be deleted by Execution::collectActions
195                 act->setFuncActRef(NULL);
196                 if (act->is_read()) {
197                         // For every read or rmw actions in this list, the reads_from is not deleted.
198                         // So it is safe to call get_reads_from
199                         ModelAction * rf = act->get_reads_from();
200                         rf->setFuncActRef(NULL);
201                 }
202
203                 FuncInst * func_inst = get_inst(act);
204                 void * loc = act->get_location();
205
206                 if (func_inst == NULL)
207                         continue;
208
209                 inst_list.push_back(func_inst);
210                 bool act_added = false;
211
212                 if (act->is_write()) {
213                         rw_act_list.push_back(act);
214                         act_added = true;
215                         if (!write_locations->contains(loc)) {
216                                 write_locations->add(loc);
217                                 history->update_loc_wr_func_nodes_map(loc, this);
218                         }
219                 }
220
221                 if (act->is_read()) {
222                         if (!act_added)
223                                 rw_act_list.push_back(act);
224
225                         /* If func_inst may only read_from a single location, then:
226                          *
227                          * The first time an action reads from some location,
228                          * import all the values that have been written to this
229                          * location from ModelHistory and notify ModelHistory
230                          * that this FuncNode may read from this location.
231                          */
232                         if (!read_locations->contains(loc) && func_inst->is_single_location()) {
233                                 read_locations->add(loc);
234                                 value_set_t * write_values = write_history->get(loc);
235                                 add_to_val_loc_map(write_values, loc);
236                                 history->update_loc_rd_func_nodes_map(loc, this);
237                         }
238                 }
239         }
240
241         update_inst_tree(&inst_list);
242         update_predicate_tree(&rw_act_list);
243
244         // Revert back action types and free
245         for (sllnode<ModelAction *> * it = act_list->begin(); it != NULL; it = it->getNext()) {
246                 ModelAction * act = it->getVal();
247
248                 // Revert back action types for actions whose types have been changed. 
249                 if (act->get_swap_flag() == true)
250                         act->use_original_type();
251
252                 /**  Free actions
253                  * case 1. READY_FREE -> delete
254                  * case 2. Read action whose read from is READY_FREE -> delete both actions
255                  * In both cases, the actions have already been removed from core model
256                  * action lists.
257                  */
258
259                 /* Problematic: could double free actions
260                 if (act->is_free()) {
261                         model_print("delete free act %d\n", act->get_seq_number());
262                         delete act;
263                 } else if (act->is_read()) {
264                         ModelAction * rf = act->get_reads_from();
265                         if (rf->is_free()) {
266                                 model_print("delete act %d\n", act->get_seq_number());
267                                 model_print("delete act %d\n", rf->get_seq_number());
268                                 delete rf;
269                                 delete act;
270                         }
271                 }*/
272         }
273
274 //      print_predicate_tree();
275 }
276
277 /**
278  * @brief Link FuncInsts in inst_list  - add one FuncInst to another's predecessors and successors
279  * @param inst_list A list of FuncInsts
280  */
281 void FuncNode::update_inst_tree(func_inst_list_t * inst_list)
282 {
283         if (inst_list == NULL)
284                 return;
285         else if (inst_list->size() == 0)
286                 return;
287
288         /* start linking */
289         sllnode<FuncInst *>* it = inst_list->begin();
290         sllnode<FuncInst *>* prev;
291
292         /* add the first instruction to the list of entry insts */
293         FuncInst * entry_inst = it->getVal();
294         add_entry_inst(entry_inst);
295
296         it = it->getNext();
297         while (it != NULL) {
298                 prev = it->getPrev();
299
300                 FuncInst * prev_inst = prev->getVal();
301                 FuncInst * curr_inst = it->getVal();
302
303                 prev_inst->add_succ(curr_inst);
304                 curr_inst->add_pred(prev_inst);
305
306                 it = it->getNext();
307         }
308 }
309
310 void FuncNode::update_predicate_tree(action_list_t * act_list)
311 {
312         if (act_list == NULL || act_list->size() == 0)
313                 return;
314
315         incr_marker();
316         uint32_t inst_counter = 0;
317
318         // Clear hashtables
319         loc_act_map.reset();
320         inst_pred_map.reset();
321         inst_id_map.reset();
322
323         // Clear the set of leaves encountered in this path
324         leaves_tmp_storage.clear();
325
326         sllnode<ModelAction *> *it = act_list->begin();
327         Predicate * curr_pred = predicate_tree_entry;
328         while (it != NULL) {
329                 ModelAction * next_act = it->getVal();
330                 FuncInst * next_inst = get_inst(next_act);
331                 next_inst->set_associated_act(next_act, marker);
332
333                 Predicate * unset_predicate = NULL;
334                 bool branch_found = follow_branch(&curr_pred, next_inst, next_act, &unset_predicate);
335
336                 // A branch with unset predicate expression is detected
337                 if (!branch_found && unset_predicate != NULL) {
338                         bool amended = amend_predicate_expr(curr_pred, next_inst, next_act);
339                         if (amended)
340                                 continue;
341                         else {
342                                 curr_pred = unset_predicate;
343                                 branch_found = true;
344                         }
345                 }
346
347                 // Detect loops
348                 if (!branch_found && inst_id_map.contains(next_inst)) {
349                         FuncInst * curr_inst = curr_pred->get_func_inst();
350                         uint32_t curr_id = inst_id_map.get(curr_inst);
351                         uint32_t next_id = inst_id_map.get(next_inst);
352
353                         if (curr_id >= next_id) {
354                                 Predicate * old_pred = inst_pred_map.get(next_inst);
355                                 Predicate * back_pred = old_pred->get_parent();
356
357                                 // For updating weights
358                                 leaves_tmp_storage.push_back(curr_pred);
359
360                                 // Add to the set of backedges
361                                 curr_pred->add_backedge(back_pred);
362                                 curr_pred = back_pred;
363                                 continue;
364                         }
365                 }
366
367                 // Generate new branches
368                 if (!branch_found) {
369                         SnapVector<struct half_pred_expr *> half_pred_expressions;
370                         infer_predicates(next_inst, next_act, &half_pred_expressions);
371                         generate_predicates(curr_pred, next_inst, &half_pred_expressions);
372                         continue;
373                 }
374
375                 if (next_act->is_write())
376                         curr_pred->set_write(true);
377
378                 if (next_act->is_read()) {
379                         /* Only need to store the locations of read actions */
380                         loc_act_map.put(next_act->get_location(), next_act);
381                 }
382
383                 inst_pred_map.put(next_inst, curr_pred);
384                 if (!inst_id_map.contains(next_inst))
385                         inst_id_map.put(next_inst, inst_counter++);
386
387                 it = it->getNext();
388                 curr_pred->incr_expl_count();
389         }
390
391         if (curr_pred->get_exit() == NULL) {
392                 // Exit predicate is unset yet
393                 curr_pred->set_exit(predicate_tree_exit);
394         }
395
396         leaves_tmp_storage.push_back(curr_pred);
397         update_predicate_tree_weight();
398 }
399
400 /* Given curr_pred and next_inst, find the branch following curr_pred that
401  * contains next_inst and the correct predicate.
402  * @return true if branch found, false otherwise.
403  */
404 bool FuncNode::follow_branch(Predicate ** curr_pred, FuncInst * next_inst,
405                                                                                                                  ModelAction * next_act, Predicate ** unset_predicate)
406 {
407         /* Check if a branch with func_inst and corresponding predicate exists */
408         bool branch_found = false;
409         ModelVector<Predicate *> * branches = (*curr_pred)->get_children();
410         for (uint i = 0;i < branches->size();i++) {
411                 Predicate * branch = (*branches)[i];
412                 if (branch->get_func_inst() != next_inst)
413                         continue;
414
415                 /* Check against predicate expressions */
416                 bool predicate_correct = true;
417                 PredExprSet * pred_expressions = branch->get_pred_expressions();
418
419                 /* Only read and rmw actions my have unset predicate expressions */
420                 if (pred_expressions->getSize() == 0) {
421                         predicate_correct = false;
422                         if (*unset_predicate == NULL)
423                                 *unset_predicate = branch;
424                         else
425                                 ASSERT(false);
426
427                         continue;
428                 }
429
430                 PredExprSetIter * pred_expr_it = pred_expressions->iterator();
431                 while (pred_expr_it->hasNext()) {
432                         pred_expr * pred_expression = pred_expr_it->next();
433                         uint64_t last_read, next_read;
434                         bool equality;
435
436                         switch(pred_expression->token) {
437                         case NOPREDICATE:
438                                 predicate_correct = true;
439                                 break;
440                         case EQUALITY:
441                                 FuncInst * to_be_compared;
442                                 ModelAction * last_act;
443
444                                 to_be_compared = pred_expression->func_inst;
445                                 last_act = to_be_compared->get_associated_act(marker);
446
447                                 last_read = last_act->get_reads_from_value();
448                                 next_read = next_act->get_reads_from_value();
449                                 equality = (last_read == next_read);
450                                 if (equality != pred_expression->value)
451                                         predicate_correct = false;
452
453                                 break;
454                         case NULLITY:
455                                 next_read = next_act->get_reads_from_value();
456                                 // TODO: implement likely to be null
457                                 equality = ( (void*) (next_read & 0xffffffff) == NULL);
458                                 if (equality != pred_expression->value)
459                                         predicate_correct = false;
460                                 break;
461                         default:
462                                 predicate_correct = false;
463                                 model_print("unkown predicate token\n");
464                                 break;
465                         }
466                 }
467
468                 delete pred_expr_it;
469
470                 if (predicate_correct) {
471                         *curr_pred = branch;
472                         branch_found = true;
473                         break;
474                 }
475         }
476
477         return branch_found;
478 }
479
480 /* Infer predicate expressions, which are generated in FuncNode::generate_predicates */
481 void FuncNode::infer_predicates(FuncInst * next_inst, ModelAction * next_act,
482                                                                                                                                 SnapVector<struct half_pred_expr *> * half_pred_expressions)
483 {
484         void * loc = next_act->get_location();
485
486         if (next_inst->is_read()) {
487                 /* read + rmw */
488                 if ( loc_act_map.contains(loc) ) {
489                         ModelAction * last_act = loc_act_map.get(loc);
490                         FuncInst * last_inst = get_inst(last_act);
491                         struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
492                         half_pred_expressions->push_back(expression);
493                 } else if ( next_inst->is_single_location() ) {
494                         loc_set_t * loc_may_equal = loc_may_equal_map->get(loc);
495
496                         if (loc_may_equal != NULL) {
497                                 loc_set_iter * loc_it = loc_may_equal->iterator();
498                                 while (loc_it->hasNext()) {
499                                         void * neighbor = loc_it->next();
500                                         if (loc_act_map.contains(neighbor)) {
501                                                 ModelAction * last_act = loc_act_map.get(neighbor);
502                                                 FuncInst * last_inst = get_inst(last_act);
503
504                                                 struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
505                                                 half_pred_expressions->push_back(expression);
506                                         }
507                                 }
508
509                                 delete loc_it;
510                         }
511                 } else {
512                         // next_inst is not single location
513                         uint64_t read_val = next_act->get_reads_from_value();
514
515                         // only infer NULLITY predicate when it is actually NULL.
516                         if ( (void*)read_val == NULL) {
517                                 struct half_pred_expr * expression = new half_pred_expr(NULLITY, NULL);
518                                 half_pred_expressions->push_back(expression);
519                         }
520                 }
521         } else {
522                 /* Pure writes */
523                 // TODO: do anything here?
524         }
525 }
526
527 /* Able to generate complex predicates when there are multiple predciate expressions */
528 void FuncNode::generate_predicates(Predicate * curr_pred, FuncInst * next_inst,
529                                                                                                                                          SnapVector<struct half_pred_expr *> * half_pred_expressions)
530 {
531         if (half_pred_expressions->size() == 0) {
532                 Predicate * new_pred = new Predicate(next_inst);
533                 curr_pred->add_child(new_pred);
534                 new_pred->set_parent(curr_pred);
535
536                 /* Maintain predicate leaves */
537                 predicate_leaves.add(new_pred);
538                 predicate_leaves.remove(curr_pred);
539
540                 /* entry predicates and predicates containing pure write actions
541                  * have no predicate expressions */
542                 if ( curr_pred->is_entry_predicate() )
543                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
544                 else if (next_inst->is_write()) {
545                         /* next_inst->is_write() <==> pure writes */
546                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
547                 }
548
549                 return;
550         }
551
552         SnapVector<Predicate *> predicates;
553
554         struct half_pred_expr * half_expr = (*half_pred_expressions)[0];
555         predicates.push_back(new Predicate(next_inst));
556         predicates.push_back(new Predicate(next_inst));
557
558         predicates[0]->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
559         predicates[1]->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
560
561         for (uint i = 1;i < half_pred_expressions->size();i++) {
562                 half_expr = (*half_pred_expressions)[i];
563
564                 uint old_size = predicates.size();
565                 for (uint j = 0;j < old_size;j++) {
566                         Predicate * pred = predicates[j];
567                         Predicate * new_pred = new Predicate(next_inst);
568                         new_pred->copy_predicate_expr(pred);
569
570                         pred->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
571                         new_pred->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
572
573                         predicates.push_back(new_pred);
574                 }
575         }
576
577         for (uint i = 0;i < predicates.size();i++) {
578                 Predicate * pred= predicates[i];
579                 curr_pred->add_child(pred);
580                 pred->set_parent(curr_pred);
581
582                 /* Add new predicate leaves */
583                 predicate_leaves.add(pred);
584         }
585
586         /* Remove predicate node that has children */
587         predicate_leaves.remove(curr_pred);
588
589         /* Free memories allocated by infer_predicate */
590         for (uint i = 0;i < half_pred_expressions->size();i++) {
591                 struct half_pred_expr * tmp = (*half_pred_expressions)[i];
592                 snapshot_free(tmp);
593         }
594 }
595
596 /* Amend predicates that contain no predicate expressions. Currenlty only amend with NULLITY predicates */
597 bool FuncNode::amend_predicate_expr(Predicate * curr_pred, FuncInst * next_inst, ModelAction * next_act)
598 {
599         ModelVector<Predicate *> * children = curr_pred->get_children();
600
601         Predicate * unset_pred = NULL;
602         for (uint i = 0;i < children->size();i++) {
603                 Predicate * child = (*children)[i];
604                 if (child->get_func_inst() == next_inst) {
605                         unset_pred = child;
606                         break;
607                 }
608         }
609
610         uint64_t read_val = next_act->get_reads_from_value();
611
612         // only generate NULLITY predicate when it is actually NULL.
613         if ( !next_inst->is_single_location() && (void*)read_val == NULL ) {
614                 Predicate * new_pred = new Predicate(next_inst);
615
616                 curr_pred->add_child(new_pred);
617                 new_pred->set_parent(curr_pred);
618
619                 unset_pred->add_predicate_expr(NULLITY, NULL, false);
620                 new_pred->add_predicate_expr(NULLITY, NULL, true);
621
622                 return true;
623         }
624
625         return false;
626 }
627
628 void FuncNode::add_to_val_loc_map(uint64_t val, void * loc)
629 {
630         loc_set_t * locations = val_loc_map->get(val);
631
632         if (locations == NULL) {
633                 locations = new loc_set_t();
634                 val_loc_map->put(val, locations);
635         }
636
637         update_loc_may_equal_map(loc, locations);
638         locations->add(loc);
639         // values_may_read_from->add(val);
640 }
641
642 void FuncNode::add_to_val_loc_map(value_set_t * values, void * loc)
643 {
644         if (values == NULL)
645                 return;
646
647         value_set_iter * it = values->iterator();
648         while (it->hasNext()) {
649                 uint64_t val = it->next();
650                 add_to_val_loc_map(val, loc);
651         }
652
653         delete it;
654 }
655
656 void FuncNode::update_loc_may_equal_map(void * new_loc, loc_set_t * old_locations)
657 {
658         if ( old_locations->contains(new_loc) )
659                 return;
660
661         loc_set_t * neighbors = loc_may_equal_map->get(new_loc);
662
663         if (neighbors == NULL) {
664                 neighbors = new loc_set_t();
665                 loc_may_equal_map->put(new_loc, neighbors);
666         }
667
668         loc_set_iter * loc_it = old_locations->iterator();
669         while (loc_it->hasNext()) {
670                 // new_loc: { old_locations, ... }
671                 void * member = loc_it->next();
672                 neighbors->add(member);
673
674                 // for each i in old_locations, i : { new_loc, ... }
675                 loc_set_t * _neighbors = loc_may_equal_map->get(member);
676                 if (_neighbors == NULL) {
677                         _neighbors = new loc_set_t();
678                         loc_may_equal_map->put(member, _neighbors);
679                 }
680                 _neighbors->add(new_loc);
681         }
682
683         delete loc_it;
684 }
685
686 /* Every time a thread enters a function, set its position to the predicate tree entry */
687 void FuncNode::init_predicate_tree_position(thread_id_t tid)
688 {
689         int thread_id = id_to_int(tid);
690         if (predicate_tree_position.size() <= (uint) thread_id)
691                 predicate_tree_position.resize(thread_id + 1);
692
693         predicate_tree_position[thread_id] = predicate_tree_entry;
694 }
695
696 void FuncNode::set_predicate_tree_position(thread_id_t tid, Predicate * pred)
697 {
698         int thread_id = id_to_int(tid);
699         predicate_tree_position[thread_id] = pred;
700 }
701
702 /* @return The position of a thread in a predicate tree */
703 Predicate * FuncNode::get_predicate_tree_position(thread_id_t tid)
704 {
705         int thread_id = id_to_int(tid);
706         return predicate_tree_position[thread_id];
707 }
708
709 /* Make sure elements of thrd_inst_act_map are initialized properly when threads enter functions */
710 void FuncNode::init_inst_act_map(thread_id_t tid)
711 {
712         int thread_id = id_to_int(tid);
713         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
714         uint old_size = thrd_inst_act_map->size();
715
716         if (thrd_inst_act_map->size() <= (uint) thread_id) {
717                 uint new_size = thread_id + 1;
718                 thrd_inst_act_map->resize(new_size);
719
720                 for (uint i = old_size;i < new_size;i++)
721                         (*thrd_inst_act_map)[i] = new inst_act_map_t(128);
722         }
723 }
724
725 /* Reset elements of thrd_inst_act_map when threads exit functions */
726 void FuncNode::reset_inst_act_map(thread_id_t tid)
727 {
728         int thread_id = id_to_int(tid);
729         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
730
731         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
732         map->reset();
733 }
734
735 void FuncNode::update_inst_act_map(thread_id_t tid, ModelAction * read_act)
736 {
737         int thread_id = id_to_int(tid);
738         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
739
740         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
741         FuncInst * read_inst = get_inst(read_act);
742         map->put(read_inst, read_act);
743 }
744
745 inst_act_map_t * FuncNode::get_inst_act_map(thread_id_t tid)
746 {
747         int thread_id = id_to_int(tid);
748         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
749
750         return (*thrd_inst_act_map)[thread_id];
751 }
752
753 /* Add FuncNodes that this node may follow */
754 void FuncNode::add_out_edge(FuncNode * other)
755 {
756         if ( !edge_table.contains(other) ) {
757                 edge_table.put(other, OUT_EDGE);
758                 out_edges.push_back(other);
759                 return;
760         }
761
762         edge_type_t edge = edge_table.get(other);
763         if (edge == IN_EDGE) {
764                 edge_table.put(other, BI_EDGE);
765                 out_edges.push_back(other);
766         }
767 }
768
769 /* Compute the distance between this FuncNode and the target node.
770  * Return -1 if the target node is unreachable or the actual distance
771  * is greater than max_step.
772  */
773 int FuncNode::compute_distance(FuncNode * target, int max_step)
774 {
775         if (target == NULL)
776                 return -1;
777         else if (target == this)
778                 return 0;
779
780         SnapList<FuncNode *> queue;
781         HashTable<FuncNode *, int, uintptr_t, 0> distances(128);
782
783         queue.push_back(this);
784         distances.put(this, 0);
785
786         while (!queue.empty()) {
787                 FuncNode * curr = queue.front();
788                 queue.pop_front();
789                 int dist = distances.get(curr);
790
791                 if (max_step <= dist)
792                         return -1;
793
794                 ModelList<FuncNode *> * outEdges = curr->get_out_edges();
795                 mllnode<FuncNode *> * it;
796                 for (it = outEdges->begin();it != NULL;it = it->getNext()) {
797                         FuncNode * out_node = it->getVal();
798
799                         /* This node has not been visited before */
800                         if ( !distances.contains(out_node) ) {
801                                 if (out_node == target)
802                                         return dist + 1;
803
804                                 queue.push_back(out_node);
805                                 distances.put(out_node, dist + 1);
806                         }
807                 }
808         }
809
810         /* Target node is unreachable */
811         return -1;
812 }
813
814 void FuncNode::add_failed_predicate(Predicate * pred)
815 {
816         failed_predicates.add(pred);
817 }
818
819 /* Implement quick sort to sort leaves before assigning base scores */
820 template<typename _Tp>
821 static int partition(ModelVector<_Tp *> * arr, int low, int high)
822 {
823         unsigned int pivot = (*arr)[high] -> get_depth();
824         int i = low - 1;
825
826         for (int j = low;j <= high - 1;j ++) {
827                 if ( (*arr)[j] -> get_depth() < pivot ) {
828                         i ++;
829                         _Tp * tmp = (*arr)[i];
830                         (*arr)[i] = (*arr)[j];
831                         (*arr)[j] = tmp;
832                 }
833         }
834
835         _Tp * tmp = (*arr)[i + 1];
836         (*arr)[i + 1] = (*arr)[high];
837         (*arr)[high] = tmp;
838
839         return i + 1;
840 }
841
842 /* Implement quick sort to sort leaves before assigning base scores */
843 template<typename _Tp>
844 static void quickSort(ModelVector<_Tp *> * arr, int low, int high)
845 {
846         if (low < high) {
847                 int pi = partition(arr, low, high);
848
849                 quickSort(arr, low, pi - 1);
850                 quickSort(arr, pi + 1, high);
851         }
852 }
853
854 void FuncNode::assign_initial_weight()
855 {
856         PredSetIter * it = predicate_leaves.iterator();
857         leaves_tmp_storage.clear();
858
859         while (it->hasNext()) {
860                 Predicate * pred = it->next();
861                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
862                 pred->set_weight(weight);
863                 leaves_tmp_storage.push_back(pred);
864         }
865         delete it;
866
867         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
868
869         // assign scores for internal nodes;
870         while ( !leaves_tmp_storage.empty() ) {
871                 Predicate * leaf = leaves_tmp_storage.back();
872                 leaves_tmp_storage.pop_back();
873
874                 Predicate * curr = leaf->get_parent();
875                 while (curr != NULL) {
876                         if (curr->get_weight() != 0) {
877                                 // Has been exlpored
878                                 break;
879                         }
880
881                         ModelVector<Predicate *> * children = curr->get_children();
882                         double weight_sum = 0;
883                         bool has_unassigned_node = false;
884
885                         for (uint i = 0;i < children->size();i++) {
886                                 Predicate * child = (*children)[i];
887
888                                 // If a child has unassigned weight
889                                 double weight = child->get_weight();
890                                 if (weight == 0) {
891                                         has_unassigned_node = true;
892                                         break;
893                                 } else
894                                         weight_sum += weight;
895                         }
896
897                         if (!has_unassigned_node) {
898                                 double average_weight = (double) weight_sum / (double) children->size();
899                                 double weight = average_weight * pow(0.9, curr->get_depth());
900                                 curr->set_weight(weight);
901                         } else
902                                 break;
903
904                         curr = curr->get_parent();
905                 }
906         }
907 }
908
909 void FuncNode::update_predicate_tree_weight()
910 {
911         if (marker == 2) {
912                 // Predicate tree is initially built
913                 assign_initial_weight();
914                 return;
915         }
916
917         weight_debug_vec.clear();
918
919         PredSetIter * it = failed_predicates.iterator();
920         while (it->hasNext()) {
921                 Predicate * pred = it->next();
922                 leaves_tmp_storage.push_back(pred);
923         }
924         delete it;
925         failed_predicates.reset();
926
927         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
928         for (uint i = 0;i < leaves_tmp_storage.size();i++) {
929                 Predicate * pred = leaves_tmp_storage[i];
930                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
931                 pred->set_weight(weight);
932         }
933
934         // Update weights in internal nodes
935         while ( !leaves_tmp_storage.empty() ) {
936                 Predicate * leaf = leaves_tmp_storage.back();
937                 leaves_tmp_storage.pop_back();
938
939                 Predicate * curr = leaf->get_parent();
940                 while (curr != NULL) {
941                         ModelVector<Predicate *> * children = curr->get_children();
942                         double weight_sum = 0;
943                         bool has_unassigned_node = false;
944
945                         for (uint i = 0;i < children->size();i++) {
946                                 Predicate * child = (*children)[i];
947
948                                 double weight = child->get_weight();
949                                 if (weight != 0)
950                                         weight_sum += weight;
951                                 else if ( predicate_leaves.contains(child) ) {
952                                         // If this child is a leaf
953                                         double weight = 100.0 / sqrt(child->get_expl_count() + 1);
954                                         child->set_weight(weight);
955                                         weight_sum += weight;
956                                 } else {
957                                         has_unassigned_node = true;
958                                         weight_debug_vec.push_back(child);      // For debugging purpose
959                                         break;
960                                 }
961                         }
962
963                         if (!has_unassigned_node) {
964                                 double average_weight = (double) weight_sum / (double) children->size();
965                                 double weight = average_weight * pow(0.9, curr->get_depth());
966                                 curr->set_weight(weight);
967                         } else
968                                 break;
969
970                         curr = curr->get_parent();
971                 }
972         }
973
974         for (uint i = 0;i < weight_debug_vec.size();i++) {
975                 Predicate * tmp = weight_debug_vec[i];
976                 ASSERT( tmp->get_weight() != 0 );
977         }
978 }
979
980 void FuncNode::print_predicate_tree()
981 {
982         model_print("digraph function_%s {\n", func_name);
983         predicate_tree_entry->print_pred_subtree();
984         predicate_tree_exit->print_predicate();
985         model_print("}\n");     // end of graph
986 }