Incorporate failed predicates in weights
[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                 FuncInst * func_inst = get_inst(act);
188                 void * loc = act->get_location();
189
190                 if (func_inst == NULL)
191                         continue;
192
193                 inst_list.push_back(func_inst);
194                 bool act_added = false;
195
196                 if (act->is_write()) {
197                         rw_act_list.push_back(act);
198                         act_added = true;
199                         if (!write_locations->contains(loc)) {
200                                 write_locations->add(loc);
201                                 history->update_loc_wr_func_nodes_map(loc, this);
202                         }
203                 }
204
205                 if (act->is_read()) {
206                         if (!act_added)
207                                 rw_act_list.push_back(act);
208
209                         /* If func_inst may only read_from a single location, then:
210                          *
211                          * The first time an action reads from some location,
212                          * import all the values that have been written to this
213                          * location from ModelHistory and notify ModelHistory
214                          * that this FuncNode may read from this location.
215                          */
216                         if (!read_locations->contains(loc) && func_inst->is_single_location()) {
217                                 read_locations->add(loc);
218                                 value_set_t * write_values = write_history->get(loc);
219                                 add_to_val_loc_map(write_values, loc);
220                                 history->update_loc_rd_func_nodes_map(loc, this);
221                         }
222                 }
223         }
224
225 //      model_print("function %s\n", func_name);
226 //      print_val_loc_map();
227
228         update_inst_tree(&inst_list);
229         update_predicate_tree(&rw_act_list);
230
231 //      print_predicate_tree();
232 }
233
234 /**
235  * @brief Link FuncInsts in inst_list  - add one FuncInst to another's predecessors and successors
236  * @param inst_list A list of FuncInsts
237  */
238 void FuncNode::update_inst_tree(func_inst_list_t * inst_list)
239 {
240         if (inst_list == NULL)
241                 return;
242         else if (inst_list->size() == 0)
243                 return;
244
245         /* start linking */
246         sllnode<FuncInst *>* it = inst_list->begin();
247         sllnode<FuncInst *>* prev;
248
249         /* add the first instruction to the list of entry insts */
250         FuncInst * entry_inst = it->getVal();
251         add_entry_inst(entry_inst);
252
253         it = it->getNext();
254         while (it != NULL) {
255                 prev = it->getPrev();
256
257                 FuncInst * prev_inst = prev->getVal();
258                 FuncInst * curr_inst = it->getVal();
259
260                 prev_inst->add_succ(curr_inst);
261                 curr_inst->add_pred(prev_inst);
262
263                 it = it->getNext();
264         }
265 }
266
267 void FuncNode::update_predicate_tree(action_list_t * act_list)
268 {
269         if (act_list == NULL || act_list->size() == 0)
270                 return;
271
272         incr_marker();
273         uint32_t inst_counter = 0;
274
275         // Clear hashtables
276         loc_act_map.reset();
277         inst_pred_map.reset();
278         inst_id_map.reset();
279
280         // Clear the set of leaves encountered in this path
281         leaves_tmp_storage.clear();
282
283         sllnode<ModelAction *> *it = act_list->begin();
284         Predicate * curr_pred = predicate_tree_entry;
285         while (it != NULL) {
286                 ModelAction * next_act = it->getVal();
287                 FuncInst * next_inst = get_inst(next_act);
288                 next_inst->set_associated_act(next_act, marker);
289
290                 Predicate * unset_predicate = NULL;
291                 bool branch_found = follow_branch(&curr_pred, next_inst, next_act, &unset_predicate);
292
293                 // A branch with unset predicate expression is detected
294                 if (!branch_found && unset_predicate != NULL) {
295                         bool amended = amend_predicate_expr(curr_pred, next_inst, next_act);
296                         if (amended)
297                                 continue;
298                         else {
299                                 curr_pred = unset_predicate;
300                                 branch_found = true;
301                         }
302                 }
303
304                 // Detect loops
305                 if (!branch_found && inst_id_map.contains(next_inst)) {
306                         FuncInst * curr_inst = curr_pred->get_func_inst();
307                         uint32_t curr_id = inst_id_map.get(curr_inst);
308                         uint32_t next_id = inst_id_map.get(next_inst);
309
310                         if (curr_id >= next_id) {
311                                 Predicate * old_pred = inst_pred_map.get(next_inst);
312                                 Predicate * back_pred = old_pred->get_parent();
313
314                                 // For updating weights
315                                 leaves_tmp_storage.push_back(curr_pred);
316
317                                 // Add to the set of backedges
318                                 curr_pred->add_backedge(back_pred);
319                                 curr_pred = back_pred;
320                                 continue;
321                         }
322                 }
323
324                 // Generate new branches
325                 if (!branch_found) {
326                         SnapVector<struct half_pred_expr *> half_pred_expressions;
327                         infer_predicates(next_inst, next_act, &half_pred_expressions);
328                         generate_predicates(curr_pred, next_inst, &half_pred_expressions);
329                         continue;
330                 }
331
332                 if (next_act->is_write())
333                         curr_pred->set_write(true);
334
335                 if (next_act->is_read()) {
336                         /* Only need to store the locations of read actions */
337                         loc_act_map.put(next_act->get_location(), next_act);
338                 }
339
340                 inst_pred_map.put(next_inst, curr_pred);
341                 if (!inst_id_map.contains(next_inst))
342                         inst_id_map.put(next_inst, inst_counter++);
343
344                 it = it->getNext();
345                 curr_pred->incr_expl_count();
346         }
347
348         if (curr_pred->get_exit() == NULL) {
349                 // Exit predicate is unset yet
350                 curr_pred->set_exit(predicate_tree_exit);
351         }
352
353         leaves_tmp_storage.push_back(curr_pred);
354         update_predicate_tree_weight();
355 }
356
357 /* Given curr_pred and next_inst, find the branch following curr_pred that
358  * contains next_inst and the correct predicate.
359  * @return true if branch found, false otherwise.
360  */
361 bool FuncNode::follow_branch(Predicate ** curr_pred, FuncInst * next_inst,
362 ModelAction * next_act, Predicate ** unset_predicate)
363 {
364         /* Check if a branch with func_inst and corresponding predicate exists */
365         bool branch_found = false;
366         ModelVector<Predicate *> * branches = (*curr_pred)->get_children();
367         for (uint i = 0;i < branches->size();i++) {
368                 Predicate * branch = (*branches)[i];
369                 if (branch->get_func_inst() != next_inst)
370                         continue;
371
372                 /* Check against predicate expressions */
373                 bool predicate_correct = true;
374                 PredExprSet * pred_expressions = branch->get_pred_expressions();
375
376                 /* Only read and rmw actions my have unset predicate expressions */
377                 if (pred_expressions->getSize() == 0) {
378                         predicate_correct = false;
379                         if (*unset_predicate == NULL)
380                                 *unset_predicate = branch;
381                         else
382                                 ASSERT(false);
383
384                         continue;
385                 }
386
387                 PredExprSetIter * pred_expr_it = pred_expressions->iterator();
388                 while (pred_expr_it->hasNext()) {
389                         pred_expr * pred_expression = pred_expr_it->next();
390                         uint64_t last_read, next_read;
391                         bool equality;
392
393                         switch(pred_expression->token) {
394                                 case NOPREDICATE:
395                                         predicate_correct = true;
396                                         break;
397                                 case EQUALITY:
398                                         FuncInst * to_be_compared;
399                                         ModelAction * last_act;
400
401                                         to_be_compared = pred_expression->func_inst;
402                                         last_act = to_be_compared->get_associated_act(marker);
403
404                                         last_read = last_act->get_reads_from_value();
405                                         next_read = next_act->get_reads_from_value();
406                                         equality = (last_read == next_read);
407                                         if (equality != pred_expression->value)
408                                                 predicate_correct = false;
409
410                                         break;
411                                 case NULLITY:
412                                         next_read = next_act->get_reads_from_value();
413                                         // TODO: implement likely to be null
414                                         equality = ( (void*) (next_read & 0xffffffff) == NULL);
415                                         if (equality != pred_expression->value)
416                                                 predicate_correct = false;
417                                         break;
418                                 default:
419                                         predicate_correct = false;
420                                         model_print("unkown predicate token\n");
421                                         break;
422                         }
423                 }
424
425                 delete pred_expr_it;
426
427                 if (predicate_correct) {
428                         *curr_pred = branch;
429                         branch_found = true;
430                         break;
431                 }
432         }
433
434         return branch_found;
435 }
436
437 /* Infer predicate expressions, which are generated in FuncNode::generate_predicates */
438 void FuncNode::infer_predicates(FuncInst * next_inst, ModelAction * next_act,
439 SnapVector<struct half_pred_expr *> * half_pred_expressions)
440 {
441         void * loc = next_act->get_location();
442
443         if (next_inst->is_read()) {
444                 /* read + rmw */
445                 if ( loc_act_map.contains(loc) ) {
446                         ModelAction * last_act = loc_act_map.get(loc);
447                         FuncInst * last_inst = get_inst(last_act);
448                         struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
449                         half_pred_expressions->push_back(expression);
450                 } else if ( next_inst->is_single_location() ) {
451                         loc_set_t * loc_may_equal = loc_may_equal_map->get(loc);
452
453                         if (loc_may_equal != NULL) {
454                                 loc_set_iter * loc_it = loc_may_equal->iterator();
455                                 while (loc_it->hasNext()) {
456                                         void * neighbor = loc_it->next();
457                                         if (loc_act_map.contains(neighbor)) {
458                                                 ModelAction * last_act = loc_act_map.get(neighbor);
459                                                 FuncInst * last_inst = get_inst(last_act);
460
461                                                 struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
462                                                 half_pred_expressions->push_back(expression);
463                                         }
464                                 }
465
466                                 delete loc_it;
467                         }
468                 } else {
469                         // next_inst is not single location
470                         uint64_t read_val = next_act->get_reads_from_value();
471
472                         // only infer NULLITY predicate when it is actually NULL.
473                         if ( (void*)read_val == NULL) {
474                                 struct half_pred_expr * expression = new half_pred_expr(NULLITY, NULL);
475                                 half_pred_expressions->push_back(expression);
476                         }
477                 }
478         } else {
479                 /* Pure writes */
480                 // TODO: do anything here?
481         }
482 }
483
484 /* Able to generate complex predicates when there are multiple predciate expressions */
485 void FuncNode::generate_predicates(Predicate * curr_pred, FuncInst * next_inst,
486 SnapVector<struct half_pred_expr *> * half_pred_expressions)
487 {
488         if (half_pred_expressions->size() == 0) {
489                 Predicate * new_pred = new Predicate(next_inst);
490                 curr_pred->add_child(new_pred);
491                 new_pred->set_parent(curr_pred);
492
493                 /* Maintain predicate leaves */
494                 predicate_leaves.add(new_pred);
495                 predicate_leaves.remove(curr_pred);
496
497                 /* entry predicates and predicates containing pure write actions
498                  * have no predicate expressions */
499                 if ( curr_pred->is_entry_predicate() )
500                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
501                 else if (next_inst->is_write()) {
502                         /* next_inst->is_write() <==> pure writes */
503                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
504                 }
505
506                 return;
507         }
508
509         SnapVector<Predicate *> predicates;
510
511         struct half_pred_expr * half_expr = (*half_pred_expressions)[0];
512         predicates.push_back(new Predicate(next_inst));
513         predicates.push_back(new Predicate(next_inst));
514
515         predicates[0]->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
516         predicates[1]->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
517
518         for (uint i = 1;i < half_pred_expressions->size();i++) {
519                 half_expr = (*half_pred_expressions)[i];
520
521                 uint old_size = predicates.size();
522                 for (uint j = 0;j < old_size;j++) {
523                         Predicate * pred = predicates[j];
524                         Predicate * new_pred = new Predicate(next_inst);
525                         new_pred->copy_predicate_expr(pred);
526
527                         pred->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
528                         new_pred->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
529
530                         predicates.push_back(new_pred);
531                 }
532         }
533
534         for (uint i = 0;i < predicates.size();i++) {
535                 Predicate * pred= predicates[i];
536                 curr_pred->add_child(pred);
537                 pred->set_parent(curr_pred);
538
539                 /* Add new predicate leaves */
540                 predicate_leaves.add(pred);
541         }
542
543         /* Remove predicate node that has children */
544         predicate_leaves.remove(curr_pred);
545
546         /* Free memories allocated by infer_predicate */
547         for (uint i = 0;i < half_pred_expressions->size();i++) {
548                 struct half_pred_expr * tmp = (*half_pred_expressions)[i];
549                 snapshot_free(tmp);
550         }
551 }
552
553 /* Amend predicates that contain no predicate expressions. Currenlty only amend with NULLITY predicates */
554 bool FuncNode::amend_predicate_expr(Predicate * curr_pred, FuncInst * next_inst, ModelAction * next_act)
555 {
556         ModelVector<Predicate *> * children = curr_pred->get_children();
557         ASSERT(children->size() == 1);
558
559         // there should only be only child
560         Predicate * unset_pred = (*children)[0];
561         uint64_t read_val = next_act->get_reads_from_value();
562
563         // only generate NULLITY predicate when it is actually NULL.
564         if ( !next_inst->is_single_location() && (void*)read_val == NULL ) {
565                 Predicate * new_pred = new Predicate(next_inst);
566
567                 curr_pred->add_child(new_pred);
568                 new_pred->set_parent(curr_pred);
569
570                 unset_pred->add_predicate_expr(NULLITY, NULL, false);
571                 new_pred->add_predicate_expr(NULLITY, NULL, true);
572
573                 return true;
574         }
575
576         return false;
577 }
578
579 void FuncNode::add_to_val_loc_map(uint64_t val, void * loc)
580 {
581         loc_set_t * locations = val_loc_map->get(val);
582
583         if (locations == NULL) {
584                 locations = new loc_set_t();
585                 val_loc_map->put(val, locations);
586         }
587
588         update_loc_may_equal_map(loc, locations);
589         locations->add(loc);
590         // values_may_read_from->add(val);
591 }
592
593 void FuncNode::add_to_val_loc_map(value_set_t * values, void * loc)
594 {
595         if (values == NULL)
596                 return;
597
598         value_set_iter * it = values->iterator();
599         while (it->hasNext()) {
600                 uint64_t val = it->next();
601                 add_to_val_loc_map(val, loc);
602         }
603
604         delete it;
605 }
606
607 void FuncNode::update_loc_may_equal_map(void * new_loc, loc_set_t * old_locations)
608 {
609         if ( old_locations->contains(new_loc) )
610                 return;
611
612         loc_set_t * neighbors = loc_may_equal_map->get(new_loc);
613
614         if (neighbors == NULL) {
615                 neighbors = new loc_set_t();
616                 loc_may_equal_map->put(new_loc, neighbors);
617         }
618
619         loc_set_iter * loc_it = old_locations->iterator();
620         while (loc_it->hasNext()) {
621                 // new_loc: { old_locations, ... }
622                 void * member = loc_it->next();
623                 neighbors->add(member);
624
625                 // for each i in old_locations, i : { new_loc, ... }
626                 loc_set_t * _neighbors = loc_may_equal_map->get(member);
627                 if (_neighbors == NULL) {
628                         _neighbors = new loc_set_t();
629                         loc_may_equal_map->put(member, _neighbors);
630                 }
631                 _neighbors->add(new_loc);
632         }
633
634         delete loc_it;
635 }
636
637 /* Every time a thread enters a function, set its position to the predicate tree entry */
638 void FuncNode::init_predicate_tree_position(thread_id_t tid)
639 {
640         int thread_id = id_to_int(tid);
641         if (predicate_tree_position.size() <= (uint) thread_id)
642                 predicate_tree_position.resize(thread_id + 1);
643
644         predicate_tree_position[thread_id] = predicate_tree_entry;
645 }
646
647 void FuncNode::set_predicate_tree_position(thread_id_t tid, Predicate * pred)
648 {
649         int thread_id = id_to_int(tid);
650         predicate_tree_position[thread_id] = pred;
651 }
652
653 /* @return The position of a thread in a predicate tree */
654 Predicate * FuncNode::get_predicate_tree_position(thread_id_t tid)
655 {
656         int thread_id = id_to_int(tid);
657         return predicate_tree_position[thread_id];
658 }
659
660 /* Make sure elements of thrd_inst_act_map are initialized properly when threads enter functions */
661 void FuncNode::init_inst_act_map(thread_id_t tid)
662 {
663         int thread_id = id_to_int(tid);
664         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
665         uint old_size = thrd_inst_act_map->size();
666
667         if (thrd_inst_act_map->size() <= (uint) thread_id) {
668                 uint new_size = thread_id + 1;
669                 thrd_inst_act_map->resize(new_size);
670
671                 for (uint i = old_size;i < new_size;i++)
672                         (*thrd_inst_act_map)[i] = new inst_act_map_t(128);
673         }
674 }
675
676 /* Reset elements of thrd_inst_act_map when threads exit functions */
677 void FuncNode::reset_inst_act_map(thread_id_t tid)
678 {
679         int thread_id = id_to_int(tid);
680         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
681
682         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
683         map->reset();
684 }
685
686 void FuncNode::update_inst_act_map(thread_id_t tid, ModelAction * read_act)
687 {
688         int thread_id = id_to_int(tid);
689         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
690
691         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
692         FuncInst * read_inst = get_inst(read_act);
693         map->put(read_inst, read_act);
694 }
695
696 inst_act_map_t * FuncNode::get_inst_act_map(thread_id_t tid)
697 {
698         int thread_id = id_to_int(tid);
699         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
700
701         return (*thrd_inst_act_map)[thread_id];
702 }
703
704 /* Add FuncNodes that this node may follow */
705 void FuncNode::add_out_edge(FuncNode * other)
706 {
707         if ( !edge_table.contains(other) ) {
708                 edge_table.put(other, OUT_EDGE);
709                 out_edges.push_back(other);
710                 return;
711         }
712
713         edge_type_t edge = edge_table.get(other);
714         if (edge == IN_EDGE) {
715                 edge_table.put(other, BI_EDGE);
716                 out_edges.push_back(other);
717         }
718 }
719
720 /* Compute the distance between this FuncNode and the target node.
721  * Return -1 if the target node is unreachable or the actual distance
722  * is greater than max_step.
723  */
724 int FuncNode::compute_distance(FuncNode * target, int max_step)
725 {
726         if (target == NULL)
727                 return -1;
728         else if (target == this)
729                 return 0;
730
731         SnapList<FuncNode *> queue;
732         HashTable<FuncNode *, int, uintptr_t, 0> distances(128);
733
734         queue.push_back(this);
735         distances.put(this, 0);
736
737         while (!queue.empty()) {
738                 FuncNode * curr = queue.front();
739                 queue.pop_front();
740                 int dist = distances.get(curr);
741
742                 if (max_step <= dist)
743                         return -1;
744
745                 ModelList<FuncNode *> * outEdges = curr->get_out_edges();
746                 mllnode<FuncNode *> * it;
747                 for (it = outEdges->begin();it != NULL;it = it->getNext()) {
748                         FuncNode * out_node = it->getVal();
749
750                         /* This node has not been visited before */
751                         if ( !distances.contains(out_node) ) {
752                                 if (out_node == target)
753                                         return dist + 1;
754
755                                 queue.push_back(out_node);
756                                 distances.put(out_node, dist + 1);
757                         }
758                 }
759         }
760
761         /* Target node is unreachable */
762         return -1;
763 }
764
765 void FuncNode::add_failed_predicate(Predicate * pred)
766 {
767         failed_predicates.add(pred);
768 }
769
770 /* Implement quick sort to sort leaves before assigning base scores */
771 template<typename _Tp>
772 static int partition(ModelVector<_Tp *> * arr, int low, int high)
773 {
774         unsigned int pivot = (*arr)[high]->get_depth();
775         int i = low - 1;
776
777         for (int j = low; j <= high - 1; j++) {
778                 if ( (*arr)[j]->get_depth() < pivot ) {
779                         i++;
780                         _Tp * tmp = (*arr)[i];
781                         (*arr)[i] = (*arr)[j];
782                         (*arr)[j] = tmp;
783                 }
784         }
785
786         _Tp * tmp = (*arr)[i + 1];
787         (*arr)[i + 1] = (*arr)[high];
788         (*arr)[high] = tmp;
789
790         return i + 1;
791 }
792
793 /* Implement quick sort to sort leaves before assigning base scores */
794 template<typename _Tp>
795 static void quickSort(ModelVector<_Tp *> * arr, int low, int high)
796 {
797         if (low < high) {
798                 int pi = partition(arr, low, high);
799
800                 quickSort(arr, low, pi - 1);
801                 quickSort(arr, pi + 1, high);
802         }
803 }
804
805 void FuncNode::assign_initial_weight()
806 {
807         PredSetIter * it = predicate_leaves.iterator();
808         leaves_tmp_storage.clear();
809
810         while (it->hasNext()) {
811                 Predicate * pred = it->next();
812                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
813                 pred->set_weight(weight);
814                 leaves_tmp_storage.push_back(pred);
815         }
816         delete it;
817
818         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
819
820         // assign scores for internal nodes;
821         while ( !leaves_tmp_storage.empty() ) {
822                 Predicate * leaf = leaves_tmp_storage.back();
823                 leaves_tmp_storage.pop_back();
824
825                 Predicate * curr = leaf->get_parent();
826                 while (curr != NULL) {
827                         if (curr->get_weight() != 0) {
828                                 // Has been exlpored
829                                 break;
830                         }
831
832                         ModelVector<Predicate *> * children = curr->get_children();
833                         double weight_sum = 0;
834                         bool has_unassigned_node = false;
835
836                         for (uint i = 0; i < children->size(); i++) {
837                                 Predicate * child = (*children)[i];
838
839                                 // If a child has unassigned weight
840                                 double weight = child->get_weight();
841                                 if (weight == 0) {
842                                         has_unassigned_node = true;
843                                         break;
844                                 } else
845                                         weight_sum += weight;
846                         }
847
848                         if (!has_unassigned_node) {
849                                 double average_weight = (double) weight_sum / (double) children->size();
850                                 double weight = average_weight * pow(0.9, curr->get_depth());
851                                 curr->set_weight(weight);
852                         } else
853                                 break;
854
855                         curr = curr->get_parent();
856                 }
857         }
858 }
859
860 void FuncNode::update_predicate_tree_weight()
861 {
862         if (marker == 2) {
863                 // Predicate tree is initially built
864                 assign_initial_weight();
865                 return;
866         }
867
868         weight_debug_vec.clear();
869
870         PredSetIter * it = failed_predicates.iterator();
871         while (it->hasNext()) {
872                 Predicate * pred = it->next();
873                 leaves_tmp_storage.push_back(pred);
874         }
875         delete it;
876         failed_predicates.reset();
877
878         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
879         for (uint i = 0; i < leaves_tmp_storage.size(); i++) {
880                 Predicate * pred = leaves_tmp_storage[i];
881                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
882                 pred->set_weight(weight);
883         }
884
885         // Update weights in internal nodes
886         while ( !leaves_tmp_storage.empty() ) {
887                 Predicate * leaf = leaves_tmp_storage.back();
888                 leaves_tmp_storage.pop_back();
889
890                 Predicate * curr = leaf->get_parent();
891                 while (curr != NULL) {
892                         ModelVector<Predicate *> * children = curr->get_children();
893                         double weight_sum = 0;
894                         bool has_unassigned_node = false;
895
896                         for (uint i = 0; i < children->size(); i++) {
897                                 Predicate * child = (*children)[i];
898
899                                 double weight = child->get_weight();
900                                 if (weight != 0)
901                                         weight_sum += weight;
902                                 else if ( predicate_leaves.contains(child) ) {
903                                         // If this child is a leaf
904                                         double weight = 100.0 / sqrt(child->get_expl_count() + 1);
905                                         child->set_weight(weight);
906                                         weight_sum += weight;
907                                 } else {
908                                         has_unassigned_node = true;
909                                         weight_debug_vec.push_back(child);      // For debugging purpose
910                                         break;
911                                 }
912                         }
913
914                         if (!has_unassigned_node) {
915                                 double average_weight = (double) weight_sum / (double) children->size();
916                                 double weight = average_weight * pow(0.9, curr->get_depth());
917                                 curr->set_weight(weight);
918                         } else
919                                 break;
920
921                         curr = curr->get_parent();
922                 }
923         }
924
925         for (uint i = 0; i < weight_debug_vec.size(); i++) {
926                 Predicate * tmp = weight_debug_vec[i];
927                 ASSERT( tmp->get_weight() != 0 );
928         }
929 }
930
931 void FuncNode::print_predicate_tree()
932 {
933         model_print("digraph function_%s {\n", func_name);
934         predicate_tree_entry->print_pred_subtree();
935         predicate_tree_exit->print_predicate();
936         model_print("}\n");     // end of graph
937 }