summaryrefslogtreecommitdiff
path: root/AspectC++/ClangASTConsumer.cc
blob: 7287150e935bcffeaaf337f184fa67aec41452ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
// This file is part of the AspectC++ compiler 'ac++'.
// Copyright (C) 1999-2013  The 'ac++' developers (see aspectc.org)
//
// This program is free software;  you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free
// Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
// MA  02111-1307  USA

#include "ClangASTConsumer.h"
#include "clang/Basic/Version.h"
#include "clang/AST/ASTContext.h"
#include <iostream>
#include "ClangAnnotation.h"
#include "version.h"

using namespace clang;


bool ClangASTConsumer::isInProject(clang::Decl *D) {
  PresumedLoc PL = _sm->getPresumedLoc(D->getLocation());
  StringRef Name = PL.getFilename();
  StringRef BufferName = _sm->getBufferName(D->getLocation());
  assert(!Name.startswith("<intro") || BufferName.startswith("<intro"));
  return BufferName.startswith("<intro") ||
         (!Name.empty() && _model.get_project().isBelow(Name.str().c_str()));
}

void ClangASTConsumer::Initialize(ASTContext &Context) {
  _sm = &Context.getSourceManager();
  _parent_map[Context.getTranslationUnitDecl()] =
      _model.register_namespace1(0, "::");
}

bool ClangASTConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
  for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i)
    TraverseDecl(*i);

  return true;
}

void ClangASTConsumer::DeclContextStack::updateContextWithCurrentElement( clang::Decl *decl, ACM_Name *element ) {
  assert( decl && element );
  assert( _decl_map.count( decl ) == 0 ); // information should only go in once

  if(!_outer._decl_stack.empty()
      &&  _outer._decl_stack.back().first == decl ) { // only the keep information for elements on stack
                                                      // updates should only occur for recent element
    _decl_map[ decl ] = element;
    if( DeclContext *dc = dyn_cast<DeclContext>( decl ) )
      _outer._parent_map[ dc ] = element;
  }
}

bool ClangASTConsumer::DeclContextStack::isCurrentContextValid() {
  // current decl context does not exist inside of project
  if( _outer._decl_stack.empty() || ! _outer.isInProject( _outer._decl_stack.back().first ) )
    return false;

  return true;
}

ClangASTConsumer::JPContext ClangASTConsumer::DeclContextStack::getJPContext() {
  assert( ! _outer._decl_stack.empty() );
  ClangASTConsumer::JPContext ctx;

  clang::Decl *decl = _outer._decl_stack.back().first;
  ctx.parent_decl = decl;

  if( FunctionDecl *fd = dyn_cast<FunctionDecl>( decl ) )
    ctx.parent = _outer._parent_map[fd];
  else if( RecordDecl *rd = dyn_cast<RecordDecl>( decl ) )
    ctx.parent = _outer._parent_map[rd];
  else if( VarDecl *vd = dyn_cast<VarDecl>( decl ) )
    ctx.parent = _decl_map[vd];
  else // should not happen => abort
    assert( false && "This should not happen: programming error !" );

  ctx.local_id = _outer._last_fn_local_id++;
  return ctx;
}

clang::Decl *ClangASTConsumer::DeclContextStack::getCurrentDecl() {
  assert( ! _outer._decl_stack.empty() );
  return _outer._decl_stack.back().first;
}

bool ClangASTConsumer::VisitType(clang::Type *Ty) {
  // Revisit template instances, there may be new ones we didn't see the first
  // time.
  if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
    if (ClassTemplateSpecializationDecl *CTSD =
            dyn_cast<ClassTemplateSpecializationDecl>(RD))
#if CLANG_VERSION_NUMBER <= VERSION_NUMBER_3_5_2
      if (!_parent_map.count(CTSD) && _seen_specs.insert(CTSD))
#else // C++ 11 interface
      if (!_parent_map.count(CTSD) && _seen_specs.insert(CTSD).second)
#endif
        return TraverseCXXRecordDecl(CTSD);

  return true;
}

bool ClangASTConsumer::VisitNamespaceDecl(NamespaceDecl *D) {
  ACM_Name *parent = _parent_map[D->getDeclContext()];
  TU_Namespace *nameSp = _model.register_namespace(D, parent);
  _parent_map[D] = nameSp;
  return true;
}

bool ClangASTConsumer::VisitCXXRecordDecl(CXXRecordDecl *D) {
  if (!isInProject(D) || D->isLocalClass ())
    return true;

//  D = D->getDefinition();
//  if (!D)
//    return true;
//
  ACM_Name *parent = _parent_map[D->getDeclContext()];

  ACM_Class *jpl_class = _model.register_aspect(D, parent);
  if (!jpl_class)
    jpl_class = _model.register_class(D, parent);

  if (!jpl_class)
    return true;

  _parent_map[D] = jpl_class;

  if (D->isThisDeclarationADefinition() && jpl_class->type_val () == JPT_Aspect) {
    ACM_Aspect *jpl_aspect = (ACM_Aspect*)jpl_class;
    //_vm << (is_abstract (*jpl_aspect) ? "Abstract" : "Concrete")
    //  << " aspect " << signature (*jpl_aspect) << endvm;
    //_vm++;
    _model.advice_infos (jpl_aspect);
    //_vm--;
  }

  return true;
}

bool ClangASTConsumer::VisitFunctionDecl(FunctionDecl *D) {
  if (!isInProject(D))
    return true;

  // functions defined in local classes must be ignored
  clang::CXXRecordDecl *cd = clang::dyn_cast<clang::CXXRecordDecl>(D->getDeclContext());
  if (cd && cd->isLocalClass ())
    return true;

  // ignore local function declarations
  if (D->getLexicalParent ()->isFunctionOrMethod ())
    return true;

  // functions that are template instances or members of template instances
  // must be ignored
  // strange: an instance node should not be visited anyway!
  if (D->getInstantiatedFromMemberFunction ())
    return true;

//  cout << "VisitFunctionDecl " << D->getQualifiedNameAsString() << endl;
  ACM_Name *parent = _parent_map[D->getDeclContext()];
  _parent_map[D] = _model.register_attrdecl(D, parent);
  if (!_parent_map[D]) {
    _parent_map[D] = _model.register_pointcut(D, parent);
    if (!_parent_map[D]) {
      if (TU_Function *func = _model.register_function(D, parent)) {
        // There may be a new redeclaration, add it.
        func->add_decl(D);
        _parent_map[D] = func;
      }
    }
  }
  return true;
}

bool ClangASTConsumer::VisitVarDecl( VarDecl *VD ) {
  if( ! isInProject( VD ) )
    return true;

  if( VD->getType()->isReferenceType() && ! VD->isFileVarDecl() )
    return true; // skip references for now, but only if they are not on the top level as we need these as context for joinpoints

#if 0
  const clang::Expr *init_expr = VD->getInit();
  if (init_expr && VD->getInitStyle() == clang::VarDecl::CInit) {
    if (dyn_cast<clang::InitListExpr>(init_expr))
      cout << "initialized var" << VD->getNameAsString () << endl;
  }
#endif

  ACM_Name *parent = _parent_map[VD->getDeclContext()];
  if( parent && parent->type_val() == JPT_Function )
    return true;// skip local variables for now
  if( TU_Variable *var = _model.register_variable( VD, parent ) ) {
    // remember model object, we might need it as context
    _context_stack.updateContextWithCurrentElement( VD, var );
  }
  return true;
}

bool ClangASTConsumer::VisitFieldDecl( clang::FieldDecl *FD ) {
  if( ! isInProject( FD ) )
    return true;

  if( FD->getType()->isReferenceType() )
    return true; // skip references for now

  ACM_Name *parent = _parent_map[FD->getDeclContext()];
  _model.register_variable( FD, parent );

  return true;
}


bool ClangASTConsumer::VisitDeclRefExpr( clang::DeclRefExpr *RE ) {
  if( ! _model.conf().data_joinpoints() ) // only data joinpoints need this information so far, so supress handling if not required
    return true;

  if( !_expr_stack.considerSubtree() || _expr_stack.empty() || ! _expr_stack.peek().isValidSubExpr() )
    return true; // skip as nobody is interested in the information

  // ignore invalid scope
  if( ! _context_stack.isCurrentContextValid() )
    return true;

  clang::VarDecl *VD = clang::dyn_cast_or_null<clang::VarDecl>( RE->getDecl() );
  clang::FunctionDecl *FD = clang::dyn_cast_or_null<clang::FunctionDecl>( RE->getDecl() );

  if( VD ) {
    if( ! isInProject( VD ) )
      return true;

    bool is_ref = VD->getType()->isReferenceType();

    TU_Variable *var = 0;
    if( ! is_ref ) {
      var = _model.register_variable( VD );
      if( !var )
        return true;
    }

    // push collected information to expr traversal stack to be processed when all informations there
    if( ! _expr_stack.empty() && _expr_stack.peek().isValidSubExpr() ) {
      _expr_stack.peek().pushEntityRefNode( RE );
      if( ! is_ref )
        _expr_stack.peek().pushEntityInfo( var, VD );
    }
  }
  else if( FD ) {
    // currently we need only the RefNode for some check in call context
    // full handling has to be added later

    // push collected information to expr traversal stack to be processed when all informations there
    if( ! _expr_stack.empty() && _expr_stack.peek().isValidSubExpr() ) {
      _expr_stack.peek().pushEntityRefNode( RE );
    }
  }

  return true;
}

// find member entities
// further we need to act as context for the base expr traversal
// we dont care for information from it yet,
// but else other data is corrupted
bool ClangASTConsumer::TraverseMemberExpr( clang::MemberExpr *ME ) {
  // only consider evaluated subtrees and additionally: only data joinpoints need this information so far, so supress handling if not required
  if( ! _expr_stack.considerSubtree() || ! _model.conf().data_joinpoints() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseMemberExpr( ME );

  DummyContext ctx( *this );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseMemberExpr( ME );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();

  // ignore invalid scope
  if( ! _context_stack.isCurrentContextValid() )
    return result;

  clang::DeclaratorDecl *DD = clang::dyn_cast_or_null<clang::DeclaratorDecl>( ME->getMemberDecl() ); // maybe refine because IndirectFieldDecl / EnumConstant
  if( ! DD )
    return result;

  if( llvm::isa<VarDecl>( DD ) || llvm::isa<FieldDecl>( DD ) ) {
    if( ! isInProject( DD ) )
      return result;

    bool is_ref = DD->getType()->isReferenceType();

    TU_Variable *var = 0;
    if( ! is_ref ) {
      var = _model.register_variable( DD );
      if( !var )
        return result;
    }

    // push collected information to expr traversal stack to be processed when all informations are collected
    if( ! _expr_stack.empty() && _expr_stack.peek().isValidSubExpr() ) {
      _expr_stack.peek().pushEntityRefNode( ME );
      if( ! is_ref )
        _expr_stack.peek().pushEntityInfo( var, DD );
    }
  }
  else if( llvm::isa<FunctionDecl>( DD ) ) {
    // currently we need only the RefNode for some check in call context
    // full handling has to be added later

    // push collected information to expr traversal stack to be processed when all informations there
    if( ! _expr_stack.empty() && _expr_stack.peek().isValidSubExpr() ) {
      _expr_stack.peek().pushEntityRefNode( ME );
    }
  }

  return result;
}

// on traversing an array access we need to find the var reference in base
bool ClangASTConsumer::TraverseArraySubscriptExpr( clang::ArraySubscriptExpr *ASE ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseArraySubscriptExpr( ASE );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseArraySubscriptExpr( ASE );
    handle_built_in_operator_traverse( ASE );
    return result;
  }

  ArrayAccessContext ctx( *this, ASE );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseArraySubscriptExpr( ASE );
  TU_Builtin *op = handle_built_in_operator_traverse( ASE );

  if( op )
    ctx.updateOperator( op );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();

  if( ! op ) // return early if the element where not registered
    return result;

  // push info about forwarder onto stack
  if( ! _expr_stack.empty() && _expr_stack.peek().isValidSubExpr() ) {
    _expr_stack.peek().pushEntityForwardingJP( op );
  }

  return result;
}

// Override Traverse functions to build an expression stack for EntityReference classification
// checking which subExpr we are in, normally we could use TraverseExpr(...) but that does not exists
bool ClangASTConsumer::TraverseStmt( clang::Stmt* S ) {
  clang::Expr *E = 0;
  if( _model.conf().data_joinpoints() && _expr_stack.considerSubtree() && ! _expr_stack.empty() && _expr_stack.peek().isSearching() ) {
    if( ( E = dyn_cast_or_null<clang::Expr>( S ) ) ) {
      _expr_stack.peek().enterSubExpr( E );
    }
  }

  clang::AttributedStmt *AS = 0;
  clang::FunctionDecl *FD = 0;
  if (S) // don't know how that is possible, but S can be 0!
    AS = llvm::dyn_cast<clang::AttributedStmt>(S);
  if (_context_stack.isCurrentContextValid())
    FD = llvm::dyn_cast<clang::FunctionDecl>( _context_stack.getCurrentDecl() );
  bool handle_attr_stmt = false;
  if (AS && FD && isInProject(FD)) {
    handle_attr_stmt = true;
    ACM_Statement *stmt =
        _model.register_statement(AS, _stmt_stack.empty() ? _parent_map[FD] : _stmt_stack.back());
    _stmt_stack.push_back (stmt);
  }

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseStmt( S );

  if (handle_attr_stmt)
    _stmt_stack.pop_back();

  if( E ) {
    assert( ! _expr_stack.empty() );
    _expr_stack.peek().registerJPforSubExpr();
    _expr_stack.peek().leaveSubExpr( E );
  }

  return result;
}

// build the context handlers on the traversal stack as place to collect information about EntityReferences
bool ClangASTConsumer::TraverseImplicitCastExpr( clang::ImplicitCastExpr *ICE ) {
  if( ! _model.conf().data_joinpoints() || ! _expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseImplicitCastExpr( ICE );

  bool result;
  if( ICE->getCastKind() == clang::CK_LValueToRValue ) {
    SingleGetContext ctx( *this, ICE, ICE->getSubExpr() );
    _expr_stack.push( ctx );

    result = RecursiveASTVisitor<ClangASTConsumer>::TraverseImplicitCastExpr( ICE );

    assert( &_expr_stack.peek() == &ctx );
    _expr_stack.drop();
    ctx.registerJPforContext();
  }
  else if( ICE->getCastKind() == clang::CK_ArrayToPointerDecay && ! ( ! _expr_stack.empty() && _expr_stack.peek().suppressDecayJPs() ) ) {
    SingleRefContext ctx( *this, ICE, ICE->getSubExpr() );
    _expr_stack.push( ctx );

    result = RecursiveASTVisitor<ClangASTConsumer>::TraverseImplicitCastExpr( ICE );

    assert( &_expr_stack.peek() == &ctx );
    _expr_stack.drop();
    ctx.registerJPforContext();
  }
  else
    result = RecursiveASTVisitor<ClangASTConsumer>::TraverseImplicitCastExpr( ICE );

  return result;
}

bool ClangASTConsumer::TraverseUnaryAddrOf( clang::UnaryOperator *UO ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseUnaryAddrOf( UO );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseUnaryAddrOf( UO );
    handle_built_in_operator_traverse( UO );
    return result;
  }

  SingleRefContext ctx( *this, UO, UO->getSubExpr() );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseUnaryAddrOf( UO );
  TU_Builtin *op = handle_built_in_operator_traverse( UO );

  if( op )
    ctx.updateOperator( op );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

bool ClangASTConsumer::TraverseReturnStmt( clang::ReturnStmt *RS ) {
  clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>( _context_stack.getCurrentDecl() );
  if( ! _model.conf().data_joinpoints() || ! _expr_stack.considerSubtree() ||
      ! FD->getReturnType().getTypePtr()->isReferenceType() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseReturnStmt( RS );

  SingleRefContext ctx( *this, RS->getRetValue(), RS->getRetValue() );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseReturnStmt( RS );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

bool ClangASTConsumer::TraverseUnaryDeref( clang::UnaryOperator *UO ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseUnaryDeref( UO );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseUnaryDeref( UO );
    handle_built_in_operator_traverse( UO );
    return result;
  }

  DummyContext ctx( *this );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseUnaryDeref( UO );
  handle_built_in_operator_traverse( UO );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();

  // ignore invalid scope
  if( ! _context_stack.isCurrentContextValid() )
    return result;

  // push collected information to expr traversal stack to be processed when all informations are collected
  if( ! _expr_stack.empty() && _expr_stack.peek().isValidSubExpr() ) {
    _expr_stack.peek().pushEntityRefNode( UO );
  }

  return result;
}

bool ClangASTConsumer::TraverseBinComma( clang::BinaryOperator *BO ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseBinComma( BO );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinComma( BO );
    // disable short-circuit evalaluating operator
    // handle_built_in_operator_traverse( BO );
    return result;
  }

  BinaryForwardContext ctx( *this, BO->getLHS(), BO->getRHS(), BinaryForwardContext::SEI_RHS );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinComma( BO );
// disable left-to-right evalaluating operator
//  handle_built_in_operator_traverse( BO );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();

  return result;
}

bool ClangASTConsumer::TraverseBinAssign( clang::BinaryOperator *BO ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseBinAssign( BO );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinAssign( BO );
    handle_built_in_operator_traverse( BO );
    return result;
  }

  AssignmentContext ctx( *this, BO );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinAssign( BO );
  TU_Builtin *op = handle_built_in_operator_traverse( BO );

  if( op )
    ctx.updateOperator( op );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

#if FRONTEND_CLANG < 38
bool ClangASTConsumer::hookTraverseCompoundAssign( FwdCall_CAssign fwd, clang::CompoundAssignOperator *CAO ) {
#else
bool ClangASTConsumer::hookTraverseCompoundAssign( FwdCall_CAssign fwd, clang::CompoundAssignOperator *CAO, DataRecursionQueue *Q ) {
#endif
  if( !_expr_stack.considerSubtree() )
#if FRONTEND_CLANG < 38
    return (this->*fwd)( CAO );
#else
    return (this->*fwd)( CAO, Q );
#endif

  if( ! _model.conf().data_joinpoints() ) {
#if FRONTEND_CLANG < 38
    bool result = (this->*fwd)( CAO );
#else
    bool result = (this->*fwd)( CAO, Q );
#endif
    handle_built_in_operator_traverse( CAO );
    return result;
  }

  AssignmentContext ctx( *this, CAO );
  _expr_stack.push( ctx );

#if FRONTEND_CLANG < 38
  bool result = (this->*fwd)( CAO );
#else
  bool result = (this->*fwd)( CAO, Q );
#endif
  TU_Builtin *op = handle_built_in_operator_traverse( CAO );

  if( op )
    ctx.updateOperator( op );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

#if FRONTEND_CLANG < 38
bool ClangASTConsumer::hookTraversePrePost( FwdCall_PrePost fwd, clang::UnaryOperator *UO ) {
#else
bool ClangASTConsumer::hookTraversePrePost( FwdCall_PrePost fwd, clang::UnaryOperator *UO, DataRecursionQueue *Q ) {
#endif
  if( !_expr_stack.considerSubtree() )
#if FRONTEND_CLANG < 38
    return (this->*fwd)( UO );
#else
    return (this->*fwd)( UO, Q );
#endif

  if( ! _model.conf().data_joinpoints() ) {
#if FRONTEND_CLANG < 38
    bool result = (this->*fwd)( UO );
#else
    bool result = (this->*fwd)( UO, Q );
#endif
    handle_built_in_operator_traverse( UO );
    return result;
  }

  AssignmentContext ctx( *this, UO );
  _expr_stack.push( ctx );

#if FRONTEND_CLANG < 38
  bool result = (this->*fwd)( UO );
#else
  bool result = (this->*fwd)( UO, Q );
#endif
  TU_Builtin *op = handle_built_in_operator_traverse( UO );

  if( op )
    ctx.updateOperator( op );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

bool ClangASTConsumer::TraverseConditionalOperator( clang::ConditionalOperator* CO ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseConditionalOperator( CO );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseConditionalOperator( CO );
    handle_built_in_operator_traverse( CO );
    return result;
  }

  DummyContext ctx( *this );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseConditionalOperator( CO );

  handle_built_in_operator_traverse( CO );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();

  return result;
}

bool ClangASTConsumer::TraverseBinPtrMemD( clang::BinaryOperator *BO ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseBinPtrMemD( BO );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinPtrMemD( BO );
    handle_built_in_operator_traverse( BO );
    return result;
  }

  DummyContext ctx( *this );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinPtrMemD( BO );
  handle_built_in_operator_traverse( BO );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();

  return result;
}

bool ClangASTConsumer::TraverseBinPtrMemI( clang::BinaryOperator *BO ) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseBinPtrMemI( BO );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinPtrMemI( BO );
    handle_built_in_operator_traverse( BO );
    return result;
  }

  DummyContext ctx( *this );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseBinPtrMemI( BO );
  handle_built_in_operator_traverse( BO );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();

  return result;
}

bool ClangASTConsumer::TraverseUnaryExprOrTypeTraitExpr( clang::UnaryExprOrTypeTraitExpr *subtree ) {
  _expr_stack.beginIgnoreTree();

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseUnaryExprOrTypeTraitExpr( subtree );

  _expr_stack.endIgnoreTree();

  return result;
}

// enable dummy mode if ParmVar is assosiated with already handled function tree
bool ClangASTConsumer::TraverseParmVarDecl( clang::ParmVarDecl *VD ) {
  // check if the current (function-)declaration is a redeclaration
  // if so we enable dummymode as we have already processed the default argument tree
  bool enable_DM = ! _dummy_mode && ( ! _decl_stack.empty() && _decl_stack.back().first->getPreviousDecl() != 0 );

  if( enable_DM )
    _dummy_mode = true;

  bool result;
  if( _model.conf().data_joinpoints() && _expr_stack.considerSubtree() && VD->hasInit() && VD->getType().getTypePtr()->isReferenceType() ) {
    SingleRefContext ctx( *this, VD->getDefaultArg(), VD->getDefaultArg() );
    ctx.ignoreTypeInfo( VD->getTypeSourceInfo() );
    _expr_stack.push( ctx );

    result = RecursiveASTVisitor<ClangASTConsumer>::TraverseParmVarDecl( VD );

    assert( &_expr_stack.peek() == &ctx );
    _expr_stack.drop();
    ctx.registerJPforContext();
  }
  else {
    result = RecursiveASTVisitor<ClangASTConsumer>::TraverseParmVarDecl( VD );
  }

  if( enable_DM ) // disable dummymode again if we enabled it
    _dummy_mode = false;

  return result;
}

// TraverseDeclaratorHelper is private, so we need to catch the cases here
bool ClangASTConsumer::TraverseTypeLoc( clang::TypeLoc TL ) {
  // check if we have to ignore the whole tree as parts of type references are off limits for weaving
  bool ignore = _expr_stack.considerSubtree() && ! _expr_stack.empty() && _expr_stack.peek().shouldIgnoreTypeInfo( TL );
  if( ignore )
    _expr_stack.beginIgnoreTree();

  bool result = RecursiveASTVisitor::TraverseTypeLoc( TL );

  if( ignore )
    _expr_stack.endIgnoreTree();

  return result;
}

// Override traverse functions so we can build up a stack of scopes.
bool ClangASTConsumer::TraverseVarDecl( clang::VarDecl *VD ) {
  // Only remember the scope for stand alone vardecls.
  if( VD->isFileVarDecl() )
    _decl_stack.push_back( std::make_pair( VD, _last_fn_local_id ) );

  bool result;
  if( _model.conf().data_joinpoints() && _expr_stack.considerSubtree() && VD->hasInit() && VD->getType().getTypePtr()->isReferenceType() ) {
    SingleRefContext ctx( *this, VD->getInit(), VD->getInit() );
    ctx.ignoreTypeInfo( VD->getTypeSourceInfo() );
    _expr_stack.push( ctx );

    result = RecursiveASTVisitor<ClangASTConsumer>::TraverseVarDecl( VD );

    assert( &_expr_stack.peek() == &ctx );
    _expr_stack.drop();
    ctx.registerJPforContext();
  }
  else {
    result = RecursiveASTVisitor<ClangASTConsumer>::TraverseVarDecl( VD );
  }

  if( VD->isFileVarDecl() )
    _decl_stack.pop_back();
  return result;
}

bool ClangASTConsumer::TraverseFunctionDecl(clang::FunctionDecl *FD) {
  _decl_stack.push_back(std::make_pair(FD, _last_fn_local_id));
  _last_fn_local_id = 0;
  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseFunctionDecl(FD);
  _last_fn_local_id = _decl_stack.pop_back_val().second;
  return result;
}

bool ClangASTConsumer::TraverseCXXMethodDecl(clang::CXXMethodDecl *FD) {
  _decl_stack.push_back(std::make_pair(FD, _last_fn_local_id));
  _last_fn_local_id = 0;
  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXMethodDecl(FD);
  _last_fn_local_id = _decl_stack.pop_back_val().second;
  return result;
}

bool ClangASTConsumer::TraverseCXXConstructorDecl(clang::CXXConstructorDecl *FD) {
  _decl_stack.push_back(std::make_pair(FD, _last_fn_local_id));
  _last_fn_local_id = 0;
  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXConstructorDecl(FD);
  _last_fn_local_id = _decl_stack.pop_back_val().second;
  return result;
}

bool ClangASTConsumer::TraverseCXXConversionDecl(clang::CXXConversionDecl *FD) {
  _decl_stack.push_back(std::make_pair(FD, _last_fn_local_id));
  _last_fn_local_id = 0;
  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXConversionDecl(FD);
  _last_fn_local_id = _decl_stack.pop_back_val().second;
  return result;
}

bool ClangASTConsumer::TraverseCXXDestructorDecl(clang::CXXDestructorDecl *FD) {
  _decl_stack.push_back(std::make_pair(FD, _last_fn_local_id));
  _last_fn_local_id = 0;
  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXDestructorDecl(FD);
  _last_fn_local_id = _decl_stack.pop_back_val().second;
  return result;
}

bool ClangASTConsumer::TraverseRecordDecl(clang::RecordDecl *RD) {
  _decl_stack.push_back(std::make_pair(RD, _last_fn_local_id));
  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseRecordDecl(RD);
  _decl_stack.pop_back();
  return result;
}

bool ClangASTConsumer::TraverseCXXRecordDecl(clang::CXXRecordDecl *RD) {
  _decl_stack.push_back(std::make_pair(RD, _last_fn_local_id));
  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXRecordDecl(RD);
  _decl_stack.pop_back();
  return result;
}

// defining Traverse... instead of VisitCallExpr guarantees that calls nested
// in argument lists, e.g. foo(nested()) are registered first.
bool ClangASTConsumer::TraverseCallExpr(clang::CallExpr *CE) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseCallExpr( CE );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCallExpr(CE);
    if (CE->getCallee()->IgnoreParenImpCasts()->getType()->isFunctionPointerType())
      handle_built_in_operator_traverse(CE); // handle as built-in dereference
    RegisterCallExpr(CE);
    return result;
  }

  CallContext ctx( *this, CE );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCallExpr(CE);
  if (CE->getCallee()->IgnoreParenImpCasts()->getType()->isFunctionPointerType())
    handle_built_in_operator_traverse(CE); // handle as built-in dereference
  RegisterCallExpr(CE);

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

bool ClangASTConsumer::TraverseCXXMemberCallExpr(clang::CXXMemberCallExpr *CE) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXMemberCallExpr( CE );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXMemberCallExpr(CE);
    RegisterCallExpr(CE);
    return result;
  }

  CallContext ctx( *this, CE );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXMemberCallExpr(CE);
  RegisterCallExpr(CE);

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

bool ClangASTConsumer::TraverseCXXOperatorCallExpr(clang::CXXOperatorCallExpr *CE) {
  if( !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXOperatorCallExpr( CE );

  if( ! _model.conf().data_joinpoints() ) {
    bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXOperatorCallExpr(CE);
    RegisterCallExpr(CE);
    return result;
  }

  CallContext ctx( *this, CE );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXOperatorCallExpr(CE);
  RegisterCallExpr(CE);

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

bool ClangASTConsumer::TraverseCXXTemporaryObjectExpr( clang::CXXTemporaryObjectExpr *TOE ) {
  if( ! _model.conf().data_joinpoints() || !_expr_stack.considerSubtree() )
    return RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXTemporaryObjectExpr( TOE );

  CallContext ctx( *this, TOE );
  _expr_stack.push( ctx );

  bool result = RecursiveASTVisitor<ClangASTConsumer>::TraverseCXXTemporaryObjectExpr( TOE );

  assert( &_expr_stack.peek() == &ctx );
  _expr_stack.drop();
  ctx.registerJPforContext();

  return result;
}

void ClangASTConsumer::RegisterCallExpr(CallExpr *CE) {
  if (CE && CE->getDirectCallee() && CE->getDirectCallee()->getIdentifier()
      && CE->getDirectCallee()->getName().startswith("__ac_attr")) {
    _model.register_annotation(CE);
    return;
  }

  // other calls are only relevant if we are in a function or variable initialization
  if (_decl_stack.empty())
    return;

  // Ignore CallExprs in (inline) functions outside of the project.
  if (!isInProject(_decl_stack.back().first))
    return;

  clang::FunctionDecl *Callee = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  if (Callee) {
    // Ignore explicit destructor calls
    // TODO: Is that really what the user wants?
    if (dyn_cast<CXXDestructorDecl> (Callee))
      return;

    // Ignore calls to functions with a local forward decl only.
    bool only_local_decls = true;
    for (clang::FunctionDecl::redecl_iterator ri = Callee->redecls_begin(),
                                              re = Callee->redecls_end();
         ri != re; ++ri) {
      if (!ri->getLexicalParent()->isFunctionOrMethod())
        only_local_decls = false;
    }
    if (only_local_decls)
      return;
  }

  if( ! _dummy_mode ) {
    DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(_decl_stack.back().first);
    if (DD) { // ignore calls without proper context, e.g. typedef decltype(somecall()) T;
      _model.register_call(Callee, CE, DD, _last_fn_local_id++,
          _stmt_stack.empty() ? 0 : _stmt_stack.back());
    }
  }
  else
    _last_fn_local_id++;
}

// This method handles a traverse over a built-in operator.
TU_Builtin * ClangASTConsumer::handle_built_in_operator_traverse(Expr* built_in_operator) {
  // Is the current scope valid?
  if( _decl_stack.empty() || ! isInProject(_decl_stack.back().first) )
    return 0;

  // Try to cast the clang::Decl to a clang::DeclaratorDecl ...
  clang::DeclaratorDecl* lexical_parent_decl = dyn_cast<DeclaratorDecl>(_decl_stack.back().first);
  // ... and only consider the declaration, if it came out of a declarator:
  if( ! lexical_parent_decl )
    return 0;

  // Registers the built-in-operator-call in the AspectC++-model
  if( ! _dummy_mode ) {
    return _model.register_builtin_operator_call(built_in_operator, lexical_parent_decl, _last_fn_local_id++,
        _stmt_stack.empty() ? 0 : _stmt_stack.back());
  }
  else {
    _last_fn_local_id++;
    return 0;
  }
}

void ClangASTConsumer::SingleAccessContext::enterSubExpr( clang::Expr *sub ) {
  assert( sub == _child );
  assert( getMode() == Mode_Search );

  setCurSubExprIndex( 0 );
}

void ClangASTConsumer::SingleAccessContext::leaveSubExpr( clang::Expr *sub ) {
  assert( sub == _child );
  assert( getCurSubExprIndex() == 0 );

  setMode( Mode_Done );
}

void ClangASTConsumer::SingleAccessContext::pushEntityRefNode( clang::Expr *RE ) {
  assert( isValidSubExpr() );

  // null values are not allowed, skip calling in that case
  assert( RE );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_info.ref_node );

  _var_info.ref_node = RE;
}

void ClangASTConsumer::SingleAccessContext::pushEntityInfo( ACM_Variable *var, clang::DeclaratorDecl *VD ) {
  assert( isValidSubExpr() );

  // null values are not allowed, skip calling in that case
  assert( var );
  assert( VD );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_info.element );
  assert( ! _var_info.decl );

  _var_info.element = var;
  _var_info.decl = VD;
}

void ClangASTConsumer::SingleAccessContext::pushEntityForwardingJP( TU_Builtin *JP ) {
  assert( isValidSubExpr() );

  // null values are not allowed, skip calling in that case
  assert( JP );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_src );

  _var_src = JP;
}

void ClangASTConsumer::SingleGetContext::registerJPforContext() {
  if( _var_info.ref_node ) { // check if we found some reference ...
    ClangModelBuilder::JoinpointContext ctx = _consumer._context_stack.getJPContext();
    if( ! _consumer._dummy_mode )
      _consumer._model.register_get( _var_info, ctx, _var_src ); // ... and register
  }
}

void ClangASTConsumer::SingleRefContext::registerJPforContext() {
  if( _var_info.element && _var_info.decl && _var_info.ref_node ) { // check if we found some reference ...
    ClangModelBuilder::JoinpointContext ctx = _consumer._context_stack.getJPContext();
    if( _op_call ) // on implicit joinpoints
      ctx.parent = _op_call; // change parent element to call node

    if( ! _consumer._dummy_mode )
      _consumer._model.register_ref( _var_info, ctx, _op_call ? _op_call : _var_src ); // ... and register
  }
}

void ClangASTConsumer::SingleRefContext::updateOperator( TU_Builtin *op ) {
  _op_call = op; // remember for implicit joinpoints

  op->forwarded_src( _var_src ); // remeber the dependency chain
}

void ClangASTConsumer::BinaryClassificationContext::enterSubExpr( clang::Expr *sub ) {
  assert( sub == _lhs || sub == _rhs );

  if( isSearching() ) {
    if( sub == _lhs )
      setCurSubExprIndex( SEI_LHS );
    else if( sub == _rhs )
      setCurSubExprIndex( SEI_RHS );
  }
}

void ClangASTConsumer::BinaryClassificationContext::leaveSubExpr( clang::Expr *sub ) {
  assert( getMode() == Mode_Done || ( sub == _lhs && getCurSubExprIndex() == SEI_LHS ) || ( sub == _rhs && getCurSubExprIndex() == SEI_RHS ) );

  setMode( Mode_Search );
}

void ClangASTConsumer::BinaryForwardContext::enterSubExpr( clang::Expr *sub ) {
  if( getParent() == 0 )
    setMode( Mode_Done ); // with nothing to forward to, we're done already
  else
    BinaryClassificationContext::enterSubExpr( sub );
}

void ClangASTConsumer::BinaryForwardContext::leaveSubExpr( clang::Expr *sub ) {
  bool done = ( getCurSubExprIndex() == _forward );

  BinaryClassificationContext::leaveSubExpr( sub );

  if( done )
    setMode( Mode_Done );
}

void ClangASTConsumer::BinaryForwardContext::pushEntityRefNode( clang::Expr *RE ) {
  // if already done just ignore new data
  if( getMode() == Mode_Done )
    return;

  assert( isValidSubExpr() );

  if( getCurSubExprIndex() == _forward ) { // only forward data from chosen subexpr
    getParent()->pushEntityRefNode( RE );
  }
}

void ClangASTConsumer::BinaryForwardContext::pushEntityInfo( ACM_Variable *var, clang::DeclaratorDecl *VD ) {
  // if already done just ignore new data
  if( getMode() == Mode_Done )
    return;

  assert( isValidSubExpr() );

  if( getCurSubExprIndex() == _forward ) { // only forward data from chosen subexpr
    getParent()->pushEntityInfo( var, VD );
  }
}

void ClangASTConsumer::BinaryForwardContext::pushEntityForwardingJP( TU_Builtin *JP ) {
  // if already done just ignore new data
  if( getMode() == Mode_Done )
    return;

  assert( isValidSubExpr() );

  if( getCurSubExprIndex() == _forward ) { // only forward data from chosen subexpr
    getParent()->pushEntityForwardingJP( JP );
  }
}

void ClangASTConsumer::ArrayAccessContext::pushEntityForwardingJP( TU_Builtin *JP ) {
  // if already done just ignore new data
  if( getMode() == Mode_Done )
    return;

  assert( isValidSubExpr() );

  assert( ! _var_src );
  assert( JP );

  if( getCurSubExprIndex() == SEI_LHS ) { // only remember data from base expr
    _var_src = JP;
  }
}

void ClangASTConsumer::ArrayAccessContext::updateOperator( TU_Builtin *op ) {
  op->forwarded_src( _var_src ); // remeber the dependency chain
}

void ClangASTConsumer::AssignmentContext::leaveSubExpr( clang::Expr *sub ) {
  bool done = ( getCurSubExprIndex() == SEI_LHS );

  BinaryClassificationContext::leaveSubExpr( sub );

  if( done )
    setMode( Mode_Done );
}

void ClangASTConsumer::AssignmentContext::pushEntityRefNode( clang::Expr *RE ) {
  // we only collect data for the assigned value
  if( getCurSubExprIndex() != SEI_LHS )
    return;

  // null values are not allowed, skip calling in that case
  assert( RE );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_info.ref_node );

  _var_info.ref_node = RE;
}

void ClangASTConsumer::AssignmentContext::pushEntityInfo( ACM_Variable *var, clang::DeclaratorDecl *VD ) {
  // we only collect data for the assigned value
  if( getCurSubExprIndex() != SEI_LHS )
    return;

  // null values are not allowed, skip calling in that case
  assert( var );
  assert( VD );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_info.element );
  assert( ! _var_info.decl );

  _var_info.element = var;
  _var_info.decl = VD;
}

void ClangASTConsumer::AssignmentContext::pushEntityForwardingJP( TU_Builtin *JP ) {
  // we only collect data for the assigned value
  if( getCurSubExprIndex() != SEI_LHS )
    return;

  // null values are not allowed, skip calling in that case
  assert( JP );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_src );

  _var_src = JP;
}

void ClangASTConsumer::AssignmentContext::registerJPforContext() {
  if( _var_info.ref_node ) { // check if we found some reference ...
    ClangModelBuilder::JoinpointContext ctx = _consumer._context_stack.getJPContext();
    if( _op_call ) // on implicit joinpoints
      ctx.parent = _op_call; // change parent element to call node

    // ... check for compound assignment and add a get joinpoint before ...
    if( _is_compound ) {
      if( ! _consumer._dummy_mode )
        _consumer._model.register_get( _var_info, ctx, _op_call );

      // create new context (old one can't be reused
      ctx = _consumer._context_stack.getJPContext();
      if( _op_call ) // on implicit joinpoints
        ctx.parent = _op_call; // change parent element to call node
    }

    if( ! _consumer._dummy_mode )
      _consumer._model.register_set( _var_info, ctx, _op_call ); // ... and register
  }

  // forward findings down the stack, as other joinpoints need the info too
  if( getParent() != 0 ) { // seems we have somebody interested in the information
    if( _var_info.ref_node )
      getParent()->pushEntityRefNode( _var_info.ref_node );
    if( _var_info.decl )
      getParent()->pushEntityInfo( _var_info.element, _var_info.decl );
    if( _op_call )
      getParent()->pushEntityForwardingJP( _op_call );
  }
}

void ClangASTConsumer::AssignmentContext::updateOperator( TU_Builtin *op ) {
  _op_call = op; // remember for implicit joinpoints

  op->forwarded_src( _var_src ); // remeber the dependency chain
}

void ClangASTConsumer::CallContext::enterSubExpr( clang::Expr *sub ) {
  if( isSearching() ) {
    if( _next_arg == 0 ) {
      if( _call->getCallee() == sub )
        setCurSubExprIndex( 0 );
    }
    else {
      unsigned int a;
      for( a = _next_arg - 1; a < getNumArgs(); a++ ) {
        if( getArg( a ) == sub )
          setCurSubExprIndex( a + 1 );
      }
      if( a >= getNumArgs() && _next_arg <= getNumArgs() )
        for( a = 0; a < _next_arg - 1; a++ ) {
          if( getArg( a ) == sub )
            setCurSubExprIndex( a + 1 );
        }

      _curarg_is_ref = false;
      if( _func_decl && ( a < _func_decl->getNumParams() ) )
        _curarg_is_ref = _func_decl->getParamDecl( a )->getType().getTypePtr()->isReferenceType();
      _var_info.tree_node = sub;
    }
  }
}

void ClangASTConsumer::CallContext::leaveSubExpr( clang::Expr *sub ) {
  _next_arg++;
  setMode( Mode_Search );
  clearVarInfo();
}

void ClangASTConsumer::CallContext::pushEntityRefNode( clang::Expr *RE ) {
  assert( getCurSubExprIndex() >= 0 );

  // null values are not allowed, skip calling in that case
  assert( RE );

  // check if we see the callee or an arg
  if( getCurSubExprIndex() == 0 ) {
    if( clang::DeclRefExpr *dre = llvm::dyn_cast<clang::DeclRefExpr>( RE ) )
      _func_decl = llvm::dyn_cast<clang::FunctionDecl>( dre->getDecl() ); // remember callee decl for type checking
    else if( clang::MemberExpr *me = llvm::dyn_cast<clang::MemberExpr>( RE ) )
      _func_decl = llvm::dyn_cast<clang::FunctionDecl>( me->getMemberDecl() ); // remember callee decl for type checking
  }
  else {
    if( _curarg_is_ref ) {
      // double calling is not allowed, it indicates some error in the AST traversal
      assert( ! _var_info.ref_node );

      _var_info.ref_node = RE;
    }
  }
}

void ClangASTConsumer::CallContext::pushEntityInfo( ACM_Variable *var, clang::DeclaratorDecl *DD ) {
  assert( getCurSubExprIndex() >= 0 );

  // we only collect data for ref args
  if( getCurSubExprIndex() == 0 || ! _curarg_is_ref )
    return;

  // null values are not allowed, skip calling in that case
  assert( var );
  assert( DD );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_info.element );
  assert( ! _var_info.decl );

  _var_info.element = var;
  _var_info.decl = DD;
}

void ClangASTConsumer::CallContext::pushEntityForwardingJP( TU_Builtin *JP ) {
  assert( getCurSubExprIndex() >= 0 );

  // we only collect data for ref args
  if( getCurSubExprIndex() == 0 || ! _curarg_is_ref )
    return;

  // null values are not allowed, skip calling in that case
  assert( JP );

  // double calling is not allowed, it indicates some error in the AST traversal
  assert( ! _var_src );

  _var_src = JP;
}

void ClangASTConsumer::CallContext::registerJPforContext() {
  // no joinpoint registration yet

  // ignore invalid scope
  if( ! _consumer._context_stack.isCurrentContextValid() )
    return;

  assert( _call || _constr );
  // only pushing info to parent
  if( getParent() && getParent()->isValidSubExpr() && _func_decl &&
      _func_decl->getReturnType().getTypePtr()->isReferenceType() )
    getParent()->pushEntityRefNode( _call ?
                                    llvm::dyn_cast<clang::Expr>( _call ) :
                                    llvm::dyn_cast<clang::Expr>(_constr) );
}

void ClangASTConsumer::CallContext::registerJPforSubExpr() {
  if( _var_info.element && _var_info.decl && _var_info.ref_node && _curarg_is_ref ) { // check if we found some reference ...
    ClangModelBuilder::JoinpointContext ctx = _consumer._context_stack.getJPContext();

    if( ! _consumer._dummy_mode )
      _consumer._model.register_ref( _var_info, ctx, _var_src ); // ... and register
  }
}