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