ClangVisitor.cpp 380 KB
Newer Older
1
2
3
4
/**************************************************************************/
/*                                                                        */
/*  This file is part of Frama-Clang                                      */
/*                                                                        */
Virgile Prevosto's avatar
Virgile Prevosto committed
5
/*  Copyright (C) 2012-2020                                               */
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*    CEA (Commissariat à l'énergie atomique et aux énergies              */
/*         alternatives)                                                  */
/*                                                                        */
/*  you can redistribute it and/or modify it under the terms of the GNU   */
/*  Lesser General Public License as published by the Free Software       */
/*  Foundation, version 2.1.                                              */
/*                                                                        */
/*  It 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 Lesser General Public License for more details.                   */
/*                                                                        */
/*  See the GNU Lesser General Public License version 2.1                 */
/*  for more details (enclosed in the file LICENSE).                      */
/*                                                                        */
/**************************************************************************/

//
// Description:
//   Definition of a translator clang -> intermediate_format (-> cabs -> cil).
//

28
#if defined(__GNUC__) && !defined(__clang__)
29
30
31
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/APValue.h"
#include "clang/Basic/FileManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/Utils.h"
#include "clang/Sema/Scope.h"
#include "Clang_utils.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Host.h"
#include "llvm/ADT/ArrayRef.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstddef>
#include <list>
50
#if defined(__GNUC__) && !defined(__clang__)
51
52
53
#pragma GCC diagnostic pop
#endif

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
#include "ClangVisitor.h"

void
AnnotationCommentList::add(AnnotationComment* comment,
    clang::SourceManager &sourceManager) {
  if (!comment || !comment->isValid())
    return;

  // Check if the comments are not in source order.
  while (!empty()
      && !sourceManager.isBeforeInTranslationUnit(
          back()->getSourceRange().getBegin(),
          comment->getSourceRange().getBegin())) {
    // If they are, just pop a few last comments that don't fit.
    // This happens if an \#include directive contains comments.
    back()->freeContent();
    delete back();
    pop_back();
  }
  push_back(comment);
}

std::unique_ptr<clang::ASTConsumer>
FramaCIRGenAction::CreateASTConsumer(clang::CompilerInstance& CI,
    clang::StringRef InFile)
{ FramacVisitor* vis = new FramacVisitor(_outFile, _compilerInstance);
  if (_annotError) vis->setAnnotError();
  if (_doesGenerateImplicitMethods) vis->setGenerateImplicitMethods();
  if (_isVerbose) vis->setVerbose();
  return std::unique_ptr<clang::ASTConsumer>(vis);
}

/**************************************************************/
/* Implementation of the class FramaCIRGenAction::DeclContext */
/**************************************************************/

void
FramaCIRGenAction::DeclContext::reopenLexicalHierarchy(
    FramacVisitor& visitor) {
  std::list<LexicalLocalDeclContext>::iterator
    iter = _lexicalParent.begin(),
    iterEnd = _lexicalParent.end();
  if (iter != iterEnd) {
    assert(iter->isNamespace());
    assert(llvm::dyn_cast<const clang::NamespaceDecl>(iter->getSynchro()));
    const clang::NamespaceDecl* namespaceDecl
      = static_cast<const clang::NamespaceDecl*>(iter->getSynchro());
    char* name=const_cast<char*>(copy_string(namespaceDecl->getName().str()));
    location loc = visitor.makeDeclLocation(*namespaceDecl);
    translation_unit_decl decl
      = translation_unit_decl_Namespace(loc, name, NULL);
    visitor._globals.insertContainer(decl);
    /* translation_unit_decl */ list* namespaceElements
      = &decl->cons_translation_unit_decl.Namespace.body;
    iter->resetNamespace(*namespaceElements, iter->getSynchro());
    LexicalLocalDeclContext* previous = &*iter;
    for (++iter; iter != iterEnd; ++iter) {
      assert(iter->isNamespace());
      assert(llvm::dyn_cast<const clang::NamespaceDecl>(iter->getSynchro()));
      const clang::NamespaceDecl* namespaceDecl
        = static_cast<const clang::NamespaceDecl*>(iter->getSynchro());
      char* name=const_cast<char*>(copy_string(namespaceDecl->getName().str()));
      location loc = visitor.makeLocation(namespaceDecl->getSourceRange());
      translation_unit_decl decl
        = translation_unit_decl_Namespace(loc, name, NULL);
      assert(!*namespaceElements);
      *namespaceElements = cons_container(decl, NULL);
      previous->getDeclarations().advanceToEnd();
      namespaceElements = &decl->cons_translation_unit_decl.Namespace.body;
      iter->resetNamespace(*namespaceElements, iter->getSynchro());
      previous = &*iter;
    };
  };
}

void
FramaCIRGenAction::DeclContext::pushFunctionBody(
    clang::FunctionDecl* functionDecl)
{ // see Sema::ActOnStartOfFunctionDef
  clang::Scope* scope = new clang::Scope(_scope,
    clang::Scope::FnScope | clang::Scope::DeclScope, _diags);
  _scope = scope;
  _sema->PushFunctionScope();
  // _sema->PushDeclContext(scope, functionDecl);
  _sema->EnterDeclaratorContext(scope, functionDecl);
  scope->AddDecl(functionDecl);
  for (unsigned p=0, NumParams = functionDecl->getNumParams();
      p < NumParams; ++p) {
    clang::ParmVarDecl *Param = functionDecl->getParamDecl(p);
    // If this has an identifier, add it to the scope stack.
    if (Param->getIdentifier())
      // scope->AddDecl(Param);
      _sema->PushOnScopeChains(Param, _scope, false);
  }
  pushCompoundScope();
  _currentFunctionBody = functionDecl;
}

void
FramaCIRGenAction::DeclContext::popFunctionBody(
    clang::FunctionDecl* functionDecl)
{ clang::Scope* scope = _scope->getParent();
  _sema->PopCompoundScope();
  _sema->ExitDeclaratorContext(_scope);
  assert(scope);
  delete _scope;
  _scope = scope;
  // _sema->PopDeclContext();
  _sema->PopFunctionScopeInfo(NULL, functionDecl);
  _currentFunctionBody = NULL;
}

void
FramaCIRGenAction::DeclContext::setLocalPush(
    const clang::DeclContext* parentDecl) {
  std::list<const clang::DeclContext*> reverseDecl;
  assert(!_semanticParent.empty());
  while (parentDecl && parentDecl != _semanticParent.back().getSynchro()) {
    reverseDecl.push_back(parentDecl);
    parentDecl = parentDecl->getParent();
  };
  assert(parentDecl && _localPush == 0);
  std::list<const clang::DeclContext*>::const_reverse_iterator
    iterEnd = reverseDecl.rend();
  for (std::list<const clang::DeclContext*>::const_reverse_iterator
      iter = reverseDecl.rbegin(); iter != iterEnd; ++iter) {
    _semanticParent.push_back(_semanticParent.back().findDecl(*iter));
    clang::Scope* scope = new clang::Scope(_scope, 0, _diags);
    _scope = scope;
    _sema->EnterDeclaratorContext(_scope,
        const_cast<clang::DeclContext*>(_semanticParent.back().getSynchro()));
    ++_localPush;
  };
}

/*
void
FramaCIRGenAction::DeclContext::setLocalPushInstantiation(
    option& declarations, const clang::DeclContext* classContext) {
  assert(_localPush == 0);
  bool hasFound = false;
  if (!_semanticParent.empty()) {
    LocalDeclContext found = _semanticParent.back().findDecl(classContext);
    if ((hasFound = found.isValid()) != false)
      _semanticParent.push_back(found);
  };
  if (!hasFound) {
    assert(classContext->isRecord());
    pushSemanticClass(declarations, classContext);
  };

  clang::Scope* scope = new clang::Scope(_scope, 0, _diags);
  _scope = scope;
  _sema->EnterDeclaratorContext(_scope,
      const_cast<clang::DeclContext*>(classContext));
  ++_localPush;
}
*/

void
FramaCIRGenAction::DeclContext::clearLocalPush() {
  while (_localPush > 0) {
    clang::Scope* scope = _scope->getParent();
    _sema->ExitDeclaratorContext(_scope);
    assert(scope);
    delete _scope;
    _scope = scope;
    _semanticParent.pop_back();
    --_localPush;
  };
}

void
FramaCIRGenAction::DeclContext::lexicalSynchronizeWith(
    const clang::DeclContext* parentDecl, FramacVisitor& visitor) {
  if (!parentDecl || !parentDecl->getLexicalParent()
      || parentDecl->getDeclKind()==clang::Decl::LinkageSpec) {
    size_t nbPops = _lexicalParent.size();
    if (nbPops > 0) {
      do {
        _lexicalParent.back().clear();
        _lexicalParent.pop_back();
      } while (--nbPops);
      assert(_lexicalParent.empty());
    };
  }
  else {
    assert(!_lexicalParent.empty());
    while (!parentDecl->Equals(_lexicalParent.back().getSynchro())) {
      _lexicalParent.back().clear();
      _lexicalParent.pop_back();
      if (_lexicalParent.empty()) {
         const clang::DeclContext* cursorDecl = parentDecl->getLexicalParent();
         while (cursorDecl->getLexicalParent()
             && (cursorDecl->getDeclKind()==clang::Decl::LinkageSpec))
           cursorDecl = cursorDecl->getLexicalParent();
         assert(!cursorDecl->getLexicalParent()
             && Clang_utils::isExternCContext(parentDecl));
         return;
      };
    };
  };
}

void
FramaCIRGenAction::DeclContext::semanticSynchronizeWith(
    const clang::DeclContext* parentDecl, FramacVisitor& visitor) {
  if (!parentDecl || !parentDecl->getParent()
      || parentDecl->getDeclKind()==clang::Decl::LinkageSpec) {
    size_t nbPops = _semanticParent.size();
    if (nbPops > 0) {
      do {
        _semanticParent.back().clear();
        _semanticParent.pop_back();
        clang::Scope* scope = _scope->getParent();
        _sema->ExitDeclaratorContext(_scope);
        assert(scope);
        delete _scope;
        _scope = scope;
        // _sema->PopDeclContext();
      } while (--nbPops);
      assert(_semanticParent.empty());
    };
  }
  else {
    assert(!_semanticParent.empty());
    while (!parentDecl->Equals(_semanticParent.back().getSynchro())) {
      clang::Scope* scope = _scope->getParent();
      _sema->ExitDeclaratorContext(_scope);
      assert(scope);
      delete _scope;
      _scope = scope;
      _semanticParent.back().clear();
      _semanticParent.pop_back();
      if (_semanticParent.empty()) {
         const clang::DeclContext* cursorDecl = parentDecl->getParent();
         while (cursorDecl->getParent()
             && (cursorDecl->getDeclKind()==clang::Decl::LinkageSpec))
           cursorDecl = cursorDecl->getParent();
         assert(!cursorDecl->getParent()
             && Clang_utils::isExternCContext(parentDecl));
         return;
      };
    };
  };
}

void
FramaCIRGenAction::DeclContext::clearLexical(FramacVisitor& visitor) {
  size_t nbPops = _lexicalParent.size();
  if (nbPops > 0) {
    do {
      _lexicalParent.back().clear();
      _lexicalParent.pop_back();
    } while (--nbPops);
    assert(_lexicalParent.empty());
  };
}

void
FramaCIRGenAction::DeclContext::clearSemantic(FramacVisitor& visitor) {
  size_t nbPops = _semanticParent.size();
  if (nbPops > 0) {
    do {
      _semanticParent.back().clear();
      _semanticParent.pop_back();
      clang::Scope* scope = _scope->getParent();
      _sema->ExitDeclaratorContext(_scope);
      assert(scope);
      delete _scope;
      _scope = scope;
      // _sema->PopDeclContext();
    } while (--nbPops);
    assert(_semanticParent.empty());
  };
}

/********************************************************/
/* Implementation of the class AnnotationCommentHandler */
/********************************************************/

bool
FramaCIRGenAction::AnnotationCommentHandler::HandleComment(
    clang::Preprocessor &PP, clang::SourceRange commentRange) {
  if (!_sourceManager)
    _sourceManager = &_compilerInstance.getSourceManager();
  if (!_sema) _sema = &_compilerInstance.getSema();

  AnnotationComment* comment = AnnotationCommentFactory
    ::createAnnotationComment(*_sourceManager, commentRange, _sema);
  if (!comment || !comment->isValid()) {
    if (comment) {
      comment->freeContent();
      delete comment;
    };
    return false;
  };
  _visitor._annotationCommentList.add(comment, *_sourceManager);
  return false;
}

/***************************************/
/* Implementation of the class Visitor */
/***************************************/

FramacVisitor::FramacVisitor(
  FILE* outstream, clang::CompilerInstance& compilerInstance)
  : _outFile(NULL), _sema(NULL), 
    _parents(compilerInstance.getDiagnostics()), _state(SSynchronized),
    _context(NULL), _implicitThisStar(NULL),
    _isImplicitThisBare(false),
    _ghost(false), _ghost_set(),
    _commentHandler(compilerInstance, *this), _commentIndex(-1),
    _templateCommentIndex(-2), _lexicalContextForPostVisit(NULL),
    _semanticContextForPostVisit(NULL),
    _typeFunctionResult(NULL),
    _generatedVaList(false),
    _templateContextsNumber(0)
{ _outFile = outstream;
  _clangUtils = new Clang_utils(NULL, this);
  _intermediateAST = (file)malloc(sizeof(*_intermediateAST));
  _intermediateAST->globals=NULL;
  _commentHandler.compilerInstance().getPreprocessor()
      .addCommentHandler(&_commentHandler);
  _globals = ForwardDoubleReferenceList(_intermediateAST->globals);
  _tableForWaitingDeclarations.setUtils(_clangUtils);
  struct _location loc = {"", 0, 0, "", 0, 0};
  _rttiTable.insertVMTAndRttiPrelude(_globals, &loc);
  memset(_generatedBuiltins, 0, SizeOfBuiltinArray*sizeof(unsigned));
}

void
FramacVisitor::HandleTranslationUnit(clang::ASTContext &context)
{ int numberOfErrors = _commentHandler.compilerInstance().getDiagnostics()
      .getClient()->getNumErrors();
  if (numberOfErrors > 0) {
    if (numberOfErrors == 1)
      std::cerr << "code generation aborted due to one compilation error";
    else
      std::cerr << "code generation aborted due to compilation errors";
    std::cerr << std::endl;
    exit(2);
  };
  _context = &context;
  _clangUtils->set_context(&context);
  _sema = &_commentHandler.compilerInstance().getSema();
  _parents.setTranlationUnit(context, *_sema);
  _state = SSynchronized;
  clang::SourceManager& sources = context.getSourceManager();
  auto fname = sources.getFileEntryForID(sources.getMainFileID())->getName();
  _intermediateAST->filename = fname.str().c_str();
  _lexicalContextForPostVisit = context.getTranslationUnitDecl();
  _semanticContextForPostVisit = context.getTranslationUnitDecl();
  TraverseDecl(context.getTranslationUnitDecl());
  handlePostVisit(context.getTranslationUnitDecl(),
    context.getTranslationUnitDecl());
  postHandleTranslationUnit();
  _lexicalContextForPostVisit = NULL;
  _semanticContextForPostVisit = NULL;
  bool haveWaitingDeclarationsBeenGenerated
    = _tableForWaitingDeclarations.isComplete();
  if (!_alternateInstanceContexts.empty()) {
     std::cerr << "Internal error in the visit of RecordDecl "
        "and friend declarations\n";
#if 1
     assert(false);
#endif
  };
  if (!haveWaitingDeclarationsBeenGenerated
      || _delayedImplementations.getFront()
      || !_immediateGlobalDependency.isEmpty()) {
    assert(_immediateGlobalDependency.isEmpty());
    if (!haveWaitingDeclarationsBeenGenerated) {
      std::cerr << "The following declarations have not been generated:\n";
      _tableForWaitingDeclarations.printIncompleteDeclarations(std::cerr);
    }
    else if (_delayedImplementations.getFront()) {
      auto current =
        ((translation_unit_decl)(*_delayedImplementations.getFront())
         .element.container)
        ->cons_translation_unit_decl.Function.fun_name
        ->cons_decl_or_impl_name.Implementation.name;
      std::cerr << "Assertion broken in:" <<
        current->decl_name << std::endl;
      std::cerr << "\n" ;
    }
#if 1
    assert(!haveWaitingDeclarationsBeenGenerated
      ? (bool) _delayedImplementations.getFront()
      : !_delayedImplementations.getFront());
#endif
  };
  assert(!_rttiTable.hasDelayedMethodCalls());
  assert(!_clangUtils->hasTemplateInstance());
  outputIntermediateFormat();
}

// [TODO] see the implementation of
//   RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const
//   for the header of ::Visitor::Visit... methods handling with comments.

// [TODO] see the implementation of
//   const RawComment *ASTContext::getRawCommentForAnyRedecl(
//       const Decl *D, const Decl **OriginalDecl) const
//   for the header of ::Visitor::Visit... methods handling with comments.

init_expr
FramacVisitor::makeInitExpr(
  const clang::QualType & typ, const clang::Expr* init, bool* shouldDelay) {
  if (init->getStmtClass() == clang::Stmt::ExprWithCleanupsClass) {
    const auto expr = llvm::dyn_cast<const clang::ExprWithCleanups>(init);
    // it might mask an InitListExpr. ExprWithCleanups does not have
    // reference to destructors to call at the end of the block (and more
    // importantly when to call them) and Frama-C 15 Silicium will be equipped
    // to deal with them anyways: nothing is really needed on the C++ side
    // of the plugin.
    return makeInitExpr(typ, expr->getSubExpr(), shouldDelay);
  }
  if (init->getStmtClass() == clang::Stmt::InitListExprClass) {
    assert (llvm::dyn_cast<const clang::InitListExpr>(init));
    clang::InitListExpr const *init_list
        = static_cast<const clang::InitListExpr*>(init);
    // Use the semantic form, where compound initialization is done
    // in appropriate order.
    if (!init_list->isSemanticForm() && init_list->getSemanticForm()) {
      init_list = init_list->getSemanticForm();
    }
    const clang::FieldDecl* union_field
      = init_list->getInitializedFieldInUnion();
    if (union_field) {
      const char* field_name = copy_string(union_field->getNameAsString());
      clang::QualType ctype = union_field->getType();
      qual_type field_type = makeDefaultType(union_field->getLocation(), ctype);
      clang::InitListExpr::const_iterator field_init = init_list->begin();
      clang::InitListExpr::const_iterator field_end = init_list->end();
      if (field_init+1 != field_end) {
        std::cerr << "More than one initializer for an union.\n";
491
492
493
#if CLANG_VERSION_MAJOR >= 11
        init->dump(llvm::errs(), *_context);
#else
494
        init->dump(llvm::errs(), _context->getSourceManager());
495
#endif
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
        std::cerr << "Aborting\n";
        exit(2);
      };
      init_expr definition = makeInitExpr(
          ctype, static_cast<clang::Expr const *>(*field_init), shouldDelay);
      return init_expr_Union_init(field_name,field_type,definition);
    }
    clang::InitListExpr::const_reverse_iterator current = init_list->rbegin();
    clang::InitListExpr::const_reverse_iterator end = init_list->rend();
    list /* init_expr */ inits = NULL;
    if (_implicitThisStar) {
      free_expression(_implicitThisStar);
      _implicitThisStar = NULL; // Compound initialization is a C thing
      _isImplicitThisBare = false;
    };
    while(current != end) {
      auto subinit = static_cast<const clang::Expr*>(*current);
      init_expr curr_init =
        makeInitExpr(subinit->getType(), subinit, shouldDelay);
      inits = cons_container(curr_init,inits);
      current++;
    }
    return init_expr_Compound_init(inits);
  };
  if (typ->isConstantArrayType() &&
      init->getStmtClass() == clang::Stmt::CXXConstructExprClass) {
    // array of objects initialized with default constructor.
    assert(_implicitThisStar);
    qualified_name idx = qualified_name_cons(NULL, "__fc_idx");
    _implicitThisStar =
      expression_cons(
        copy_loc(_implicitThisStar->eloc),
        exp_node_ArrayAccess(
          _implicitThisStar,
          expression_cons(
            copy_loc(_implicitThisStar->eloc),
            exp_node_Variable(variable_Local(idx)))));
    return
      init_expr_Array_init(
        qualified_name_dup(idx), makeLocExpression(init,shouldDelay));
  };
537
538
539
  if (clang::ImplicitValueInitExpr::classof(init)) {
    return init_expr_Implicit_init();
  }
540
541
542
543
544
545
546
547
548
549
550
  //TODO: there are other initializer classes.
  //Need to check whether they are used in the elaborated AST.
  // plain expression
   return init_expr_Single_init(makeLocExpression(init, shouldDelay));
}

init_expr FramacVisitor::make_explicit_initializer_list(const clang::Expr* e) {
  // It's likely that we'll always end up with a MaterializeTemporaryExpr,
  // but there might be cases where clang give the list directly in e.
  if (e->getStmtClass() == clang::Stmt::MaterializeTemporaryExprClass) {
    auto tmp = llvm::dyn_cast<const clang::MaterializeTemporaryExpr>(e);
551
552
553
#if CLANG_VERSION_MAJOR >= 10
    e = tmp->getSubExpr();
#else
554
    e = tmp->GetTemporaryExpr();
555
#endif
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
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
  }
  assert("Expecting an InitListExpr under a CXXStdInitializeListExpr"
         && e->getStmtClass() == clang::Stmt::InitListExprClass);
  auto list = llvm::dyn_cast<const clang::InitListExpr>(e);
  return makeInitExpr(list->getType(), list);
}

exp_node FramacVisitor::make_initializer_list(
  const clang::CXXStdInitializerListExpr* il) {
  const clang::QualType typ = il->getType();
  const clang::CXXRecordDecl* il_type = typ->getAsCXXRecordDecl();
  assert(il_type);
  auto il_inst =
    llvm::dyn_cast<const clang::ClassTemplateSpecializationDecl>(il_type);
  assert(il_inst);
  const clang::QualType elt_type =
    il_inst->getTemplateInstantiationArgs().get(0).getAsType();
  qual_type elt_type_trans =
    makeDefaultType(_clangUtils->getBeginLoc(*il), elt_type);
  init_expr init = make_explicit_initializer_list(il->getSubExpr());
  return exp_node_InitializerList(elt_type_trans, init);
}

exp_node FramacVisitor::make_lambda_expr(const clang::LambdaExpr* lam) {
  const clang::CXXMethodDecl* lam_meth = lam->getCallOperator();
  qual_type lam_rt =
    makeDefaultExternalNameType(
      lam_meth->getReturnTypeSourceRange().getBegin(),
      lam_meth->getReturnType());
  /* arg_decl */ list lam_args = NULL;
  auto args = lam_meth->parameters();
  for (auto it = args.rbegin(); it < args.rend(); it++) {
    std::string name = (*it)->getNameAsString();
    qual_type arg_type =
      makeDefaultExternalNameType(
        (*it)->getLocation(), (*it)->getOriginalType());
    location l = makeLocation((*it)->getSourceRange());
    lam_args =
      cons_container(arg_decl_cons(arg_type, copy_string(name), l),lam_args);
  }
  /* closure */ list lam_closure =
    _clangUtils->make_capture_list(lam->captures());
  /* statement */ list lam_body =
    makeCodeBlock(lam_meth->getBody(), lam_meth->getDeclContext(), lam_meth);
  return exp_node_LambdaExpr(lam_rt, lam_args, lam_closure, lam_body);
}

expression
FramacVisitor::makeLocExpression(
  const clang::Expr* expr, bool* shouldDelay, list* receiver) {
  exp_node node = makeExpression(expr, shouldDelay, receiver);
  location loc = makeLocation(expr->getSourceRange());
  return expression_cons(loc,node);
}

exp_node FramacVisitor::convert_result(
  FramaCIRGenAction::ExpressionGuard& guard, const clang::QualType& ret,
  exp_node call, const clang::Expr* expr) {
  exp_node result = call;
  if (ret->isReferenceType())
    result =
      exp_node_Dereference(
        expression_cons(makeLocation(expr->getSourceRange()), result));
  clang::CXXRecordDecl* class_decl = ret->getAsCXXRecordDecl();
  if (class_decl) {
    clang::CXXConstructorDecl* cons =
      _sema->LookupCopyingConstructor(
        class_decl,ret.getCVRQualifiers());
    if(!cons) {
      std::cerr << 
        "Not able to find an appropriate copy constructor for class "
                << class_decl->getNameAsString() << "\nAborting.\n";
      exit(2);
    }
    // create a temporary in case the address is taken
    // but do not use copy constructor, as clang has determined
    // that it can be elided (§12.8.32).
    const char* temp = mk_tmp_name ();
    qual_type typ =makeDefaultType(expr->getExprLoc(), ret);
    expression res =
      expression_cons(makeLocation(expr->getSourceRange()),result);
    result = exp_node_Temporary(temp,typ,init_expr_Single_init(res), false);
  }
  return guard.setAssignResult(result, expr);
}

exp_node FramacVisitor::makeTemporaryObjectExpression(
  const clang::CXXTemporaryObjectExpr* constructor,
  bool* shouldDelay, /* statement */ list* receiver)
{ clang::SourceLocation sloc = constructor->getExprLoc();
  location loc = makeLocation(constructor->getSourceRange());
  assert(llvm::dyn_cast<clang::FunctionDecl>(constructor->getConstructor()));
  const clang::FunctionDecl* function = static_cast<const clang
      ::FunctionDecl*>(constructor->getConstructor());
  tkind templateExtension = NULL;
  if (function->getTemplateSpecializationKind()
      >= clang::TSK_ImplicitInstantiation) {
    clang::FunctionTemplateSpecializationInfo* info
      = function->getTemplateSpecializationInfo();
    if (info)
      templateExtension=
        tkind_TTemplateInstance(_clangUtils->getTemplateExtension(info));
  };
  if (!templateExtension)
    templateExtension = tkind_TStandard();
  qualified_name name = _clangUtils->makeQualifiedName(*function);
  if (strlen(name->decl_name) == 0) {
    free(const_cast<char*>(name->decl_name));
    name->decl_name = strdup("constructor-special");
  };
  clang::CXXConstructExpr::const_arg_iterator argEnd = constructor->arg_end();
  list /* expression */ arguments = NULL;
  ForwardReferenceList forwardArguments(arguments);
  const char* temp = mk_tmp_name();
  // [TODO] declare tmpvar in the list of local variables ?
  expression tmpvar = expression_cons(loc, exp_node_Address(
      expression_cons(copy_loc(loc), exp_node_Variable(
        variable_Local(qualified_name_cons(NULL,temp))))));
  forwardArguments.insertContainer(tmpvar);
  for (clang::CXXConstructExpr::const_arg_iterator
      argIter = constructor->arg_begin(); argIter != argEnd; ++argIter) {
    exp_node argument = makeExpression(*argIter, shouldDelay,receiver);
    expression eargument = expression_cons(makeLocation(
          (*argIter)->getSourceRange()), argument);
    forwardArguments.insertContainer(eargument);
  };
  signature sig = _clangUtils->makeSignature(*constructor->getConstructor());
  exp_node call_node =
    exp_node_Static_call(
      name, sig, funkind_FKConstructor(true),
      arguments, templateExtension, false);
  expression call = expression_cons(copy_loc(loc),call_node);
  qual_type typ = makeDefaultType(sloc, constructor->getType());
  return exp_node_Temporary(strdup(temp), typ,
      init_expr_Single_init(call), false);
}

exp_node FramacVisitor::makeConstructExpression(
  const clang::CXXConstructExpr* constructor,
  bool* shouldDelay, /* statement */ list* receiver,
  bool hasImplicitThisStar,
  bool isImplicitThisBare,
  FramaCIRGenAction::ExpressionGuard& guard)
{ tkind templateExtension = NULL;
  if (constructor->isElidable() && constructor->getNumArgs() == 1) {
    // constructor can be omitted. Gain quite a few temporary variables
    // by doing it.
    // TODO: maybe some additional checks are needed before doing the elision.
    return makeExpression(constructor->getArg(0), shouldDelay, receiver);
  }
  assert(llvm::dyn_cast<clang::CXXMethodDecl>(constructor->getConstructor()));
  const clang::CXXMethodDecl* function = static_cast<const clang
      ::CXXMethodDecl*>(constructor->getConstructor());
  if (function->getParent()->isLambda() && constructor->getNumArgs() == 1) {
    // Some Lambda constructors are not seen as elidable. Nevertheless, we
    // use a custom translation mechanism there and bypass the constructor.
    return makeExpression(constructor->getArg(0), shouldDelay, receiver);
  }
  if (function->getTemplateSpecializationKind()
      >= clang::TSK_ImplicitInstantiation) {
    clang::FunctionTemplateSpecializationInfo* info
      = function->getTemplateSpecializationInfo();
    if (info)
      templateExtension=tkind_TTemplateInstance(
        _clangUtils->getTemplateExtension(info));
  };
  if (!templateExtension)
    templateExtension = tkind_TStandard();
  if (hasInstanceContext()) {
    if (!_tableForWaitingDeclarations.hasVisited(function)
         && function != _parents.getSFunctionDecl())
      unvisitedDecls().push_back(function);
    else {
      clang::Decl::Kind kindDecl = function->getDeclContext()->getDeclKind();
      if (kindDecl >= clang::Decl::firstRecord
          && kindDecl <= clang::Decl::lastRecord)
        _tableForWaitingDeclarations.ensureGeneration(
          static_cast<const clang::RecordDecl*>(function->getDeclContext()),
          unvisitedDecls());
    };
  }
  else if (shouldDelay && !*shouldDelay)
    *shouldDelay = !_tableForWaitingDeclarations.hasVisited(function)
         && function != _parents.getSFunctionDecl();

  qualified_name name = _clangUtils->makeQualifiedName(*function);
  if (strlen(name->decl_name) == 0) {
    free(const_cast<char*>(name->decl_name));
    name->decl_name = strdup("constructor-special");
  };
  if (isImplicitThisBare) {
    _rttiTable.addBareToQualification(name);
    // if (shouldDelay && !*shouldDelay)
    //   *shouldDelay = true;
  };
  clang::CXXConstructExpr::const_arg_iterator argEnd = constructor->arg_end();
  list /* expression */ arguments = NULL;
  ForwardReferenceList forwardArguments(arguments);
  clang::SourceLocation sloc = constructor->getExprLoc();
  location loc = makeLocation(constructor->getSourceRange());
  const char* temp = NULL;
  expression tmpvar;
  qual_type typ;
  if (hasImplicitThisStar) {
    expression lval = guard.releaseExpr ();
    expression address = expression_cons(loc,exp_node_Address(lval));
    tmpvar = address;
  }
  else {
    temp = mk_tmp_name();
    tmpvar = expression_cons(loc, exp_node_Address(
        expression_cons(copy_loc(loc), exp_node_Variable(
          variable_Local(qualified_name_cons(NULL,temp))))));
    typ = makeDefaultType(sloc, constructor->getType());
  };
  forwardArguments.insertContainer(tmpvar);
  for (clang::CXXConstructExpr::const_arg_iterator
      argIter = constructor->arg_begin(); argIter != argEnd; ++argIter) {
    exp_node argument = makeExpression(*argIter, shouldDelay,receiver);
    expression eargument = expression_cons(makeLocation(
          (*argIter)->getSourceRange()), argument);
    forwardArguments.insertContainer(eargument);
  };
  signature sig = _clangUtils->makeSignature(*constructor->getConstructor());
  exp_node call_node =
    exp_node_Static_call(
      name, sig, funkind_FKConstructor(true),
      arguments, templateExtension, false);
  expression call = expression_cons(copy_loc(loc),call_node);
  exp_node res = temp ? exp_node_Temporary(strdup(temp), typ,
      init_expr_Single_init(call), false) : call_node;
  return res;
}

exp_node FramacVisitor::makeDeleteExpression(
    const clang::CXXDeleteExpr* deleteExpr,
    bool* shouldDelay, /* statement */ list* receiver) {
  location loc = makeLocation(deleteExpr->getSourceRange());
  expression thisArgument =
    makeLocExpression(deleteExpr->getArgument(), shouldDelay, receiver);
  const clang::CXXRecordDecl* recordDecl =
    deleteExpr->getDestroyedType()->getAsCXXRecordDecl();
  /* statement */ list statements = NULL;

  if (deleteExpr->getOperatorDelete()
      && !deleteExpr->getOperatorDelete()->isImplicit()) {
    /* overloaded delete */
    const clang::FunctionDecl* function = deleteExpr->getOperatorDelete();
    if (hasInstanceContext()) {
      if (!_tableForWaitingDeclarations.hasVisited(function)
            && function != _parents.getSFunctionDecl())
        unvisitedDecls().push_back(function);
      else {
        clang::Decl::Kind kindDecl = function->getDeclContext()->getDeclKind();
        if (kindDecl >= clang::Decl::firstRecord
            && kindDecl <= clang::Decl::lastRecord)
          _tableForWaitingDeclarations.ensureGeneration(
            static_cast<const clang::RecordDecl*>(function->getDeclContext()),
            unvisitedDecls());
      };
    }
    else if (shouldDelay && !*shouldDelay)
      *shouldDelay = !_tableForWaitingDeclarations.hasVisited(function)
            && function != _parents.getSFunctionDecl();
    qualified_name name = _clangUtils->makeQualifiedName(
        *deleteExpr->getOperatorDelete());
    list /* expression */ arguments = cons_container(thisArgument, NULL);
    signature sig =
      _clangUtils->makeSignature(*deleteExpr->getOperatorDelete());
    // Call of overloaded delete
    statements =
      cons_container(
        statement_Expression(
          copy_loc(loc),
          expression_cons(
            copy_loc(loc),
            exp_node_Static_call(
              name,
              sig,
              funkind_FKFunction(),
              arguments,
              tkind_TStandard(),
              false))),
        statements);
  }
  else if (!deleteExpr->isArrayForm()) { // ::delete
    // Free
    statements =
      cons_container(
        statement_Expression(
          copy_loc(loc),
          expression_cons(
            copy_loc(loc),
            exp_node_Free(
              thisArgument))),
        statements);
  }
  else { // ::delete[]
    // Free for array
    statements =
      cons_container(
        statement_Expression(
          copy_loc(loc),
          expression_cons(
            copy_loc(loc),
            exp_node_FreeArray(
              thisArgument))),
        statements);
  }

  if(recordDecl) {
    clang::CXXDestructorDecl* destructor = recordDecl->getDestructor();
    if(destructor) {
      if (hasInstanceContext()) {
        if (!_tableForWaitingDeclarations.hasVisited(destructor)
               && destructor != _parents.getSFunctionDecl())
          unvisitedDecls().push_back(destructor);
        else {
          clang::Decl::Kind kindDecl = destructor->getDeclContext()
              ->getDeclKind();
          if (kindDecl >= clang::Decl::firstRecord
              && kindDecl <= clang::Decl::lastRecord) {
             _tableForWaitingDeclarations.ensureGeneration(
              static_cast<const clang::RecordDecl*>(
                destructor->getDeclContext()),
              unvisitedDecls());
            }
        };
      }
      else if (shouldDelay && !*shouldDelay) {
        *shouldDelay = !_tableForWaitingDeclarations.hasVisited(destructor)
            && destructor != _parents.getSFunctionDecl();
      }
      qualified_name name = _clangUtils->makeQualifiedName(*destructor);

      if (deleteExpr->isArrayForm()) {
        // "i"
        const char* loopVariableName = mk_tmp_name();
        // i
        expression loopVariableAsExpr =
          expression_cons(
            copy_loc(loc),
            exp_node_Variable(
              variable_Local(
                qualified_name_cons(
                  NULL,
                  loopVariableName))));
        expression zero = makeIntLiteral(loc,IULONGLONG,0);
        expression one = makeIntLiteral(loc,IULONGLONG,1);
        // length. As said above, should be dependent on the argument of free[]
        expression size = makeIntLiteral(loc,IULONGLONG,1);
        // n-1-i
        expression index =
          expression_cons(
            copy_loc(loc),
            exp_node_Binary_operator(
              BOMINUS,
              AKRVALUE,
              expression_cons(
                copy_loc(loc),
                exp_node_Binary_operator(
                  BOMINUS,
                  AKRVALUE,
                  size,
                  one)),
            loopVariableAsExpr));
        // p[n-1-i]
        expression nthElt =
          expression_cons(
            copy_loc(loc),
            exp_node_ArrayAccess(thisArgument, index));
        // TODO: verify if the following instruction is still needed
        // expression thisCopyArgument =
        //   makeLocExpression(deleteExpr->getArgument(),shouldDelay, receiver);
        // TODO : create a temp expression to avoid side effects
        list /* expression */ arguments =
          cons_container(
            expression_cons(
              copy_loc(loc),
              exp_node_Address(
                nthElt)),
            NULL);
        signature sig = _clangUtils->makeSignature(*destructor);
        // A::Dtor(&p[n-1-i])
        exp_node call_node =
          exp_node_Static_call(
            name,
            sig,
            funkind_FKDestructor(true),
            arguments,
            tkind_TStandard(),
            false);
        expression call = expression_cons(copy_loc(loc),call_node);
        // unsigned long long
        qual_type loopVariableType =
          qual_type_cons(
            NULL,
            typ_Int(
              IULONGLONG));
        // (unsigned long long)0;
        init_expr loopVariableInit =
          init_expr_Single_init(
            zero);
        // unsigned long long i = 0;
        list init =
          cons_container(
            init_declarator_cons(
              loopVariableName,
              loopVariableType,
              opt_some_container(
                loopVariableInit)),
            NULL);
        // ++i
        incr_statement incr =
          incr_statement_CExpression(
            expression_cons(
              copy_loc(loc),
              exp_node_Unary_operator(
                uokind_UOPreInc(),
                loopVariableAsExpr)));
        // i < length
        expression cond =
          expression_cons(
            copy_loc(loc),
            exp_node_Binary_operator(
              BOLESS,
              AKRVALUE,
              loopVariableAsExpr,
              size));
        // for(unsigned long long i = 0; i < length; ++i)
        //   A::Dtor(&p[n-1-i]);
        statement forStatement =
          statement_For(
            copy_loc(loc),
            init_statement_IVarDecl(
              init),
            opt_some_container(
              cond),
            incr,
            statement_Expression(
              copy_loc(loc),
              call),
            NULL);
        statements = cons_container(forStatement, statements);
      }
      else { //non array
        expression thisCopyArgument =
          makeLocExpression(deleteExpr->getArgument(), shouldDelay, receiver);
        // TODO : create a temp expression to avoid side effects
        list /* expression */ arguments =
          cons_container(thisCopyArgument, NULL);
        signature sig = _clangUtils->makeSignature(*destructor);
        exp_node call_node =
          exp_node_Static_call(
            name,
            sig,
            funkind_FKDestructor(true),
            arguments,
            tkind_TStandard(),
            false);
        statements =
          cons_container(
            statement_Expression(
              copy_loc(loc),
              expression_cons(
                copy_loc(loc),
                call_node)),
            statements);
      }
    }
  };
  return exp_node_GnuBody(statements);
}

exp_node FramacVisitor::makeNewExpression(
  const clang::CXXNewExpr* newExpr,
  bool* shouldDelay, /* statement */ list* receiver) {
  exp_node result = NULL;
  qual_type type =
    makeDefaultType(newExpr->getExprLoc(), newExpr->getAllocatedType());

  // First, we compute the address of the memory block where the object will
  // be stored. Various cases are possible, depending on the nature of
  // operator new used.

  // TODO: find a way to distinguish default placement new from custom one
  if (newExpr->getOperatorNew() && 
      !newExpr->getOperatorNew()->isReplaceableGlobalAllocationFunction() &&
      !newExpr->getOperatorNew()->isReservedGlobalPlacementOperator()) {
    // custom placement new. Just make a call to the corresponding function.
    qualified_name name
        = _clangUtils->makeQualifiedName(*newExpr->getOperatorNew());
    signature sig = _clangUtils->makeSignature(*newExpr->getOperatorNew());
    /* expression */ list arguments = NULL;
    ForwardReferenceList argumentsList(arguments);
    location loc = makeLocation(newExpr->getSourceRange());
    exp_node size_to_alloc =
      exp_node_Constant(
        compilation_constant_TypeCst(TCCSIZEOF,type->plain_type));
    if (newExpr->isArray()) {
      expression exp_size_elt = expression_cons(copy_loc(loc), size_to_alloc);
      // length
      expression exp_length;
#if CLANG_VERSION_MAJOR >= 9
      if (!newExpr->getArraySize().hasValue())
        exp_length = makeIntLiteral(copy_loc(loc), IINT, 0);
      else
        exp_length =
          makeLocExpression(*newExpr->getArraySize(), shouldDelay, receiver);
#else
      exp_length =
        makeLocExpression(newExpr->getArraySize(), shouldDelay, receiver);
#endif

      // size = length * sizeof(A)
      size_to_alloc =
        exp_node_Binary_operator(BOTIMES, AKRVALUE, exp_length, exp_size_elt);
    };
    argumentsList.insertContainer(expression_cons(copy_loc(loc),size_to_alloc));
    for (unsigned i = 0; i < newExpr->getNumPlacementArgs(); i++) {
      expression arg =
        makeLocExpression(newExpr->getPlacementArg(i), shouldDelay, receiver);
      argumentsList.insertContainer(arg);
    }
    // Call the explicit new operator
    // new(sizeof(A))
    result = exp_node_Static_call(
        name, sig, funkind_FKFunction(), arguments, tkind_TStandard(), false);
  } else if (newExpr->getNumPlacementArgs()) {
      // implicit placement new: just reuse the provided memory block
      // implicit placement new has exactly one argument, the address
      // of the memory block where the object should be put
      assert(newExpr->getNumPlacementArgs() == 1);
      result =
        makeExpression(newExpr->getPlacementArg(0), shouldDelay, receiver);
  } else if (!newExpr->isArray()) { // no placement, no array
      // malloc(sizeof(A))
      result = exp_node_Malloc(type->plain_type);
  } else {
#if CLANG_VERSION_MAJOR >= 9
      expression size;
      if (!newExpr->getArraySize().hasValue())
        size = makeIntLiteral(makeLocation(newExpr->getSourceRange()), IINT, 0);
      else
        size =
          makeLocExpression(*newExpr->getArraySize(), shouldDelay, receiver);
#else
      expression size =
        makeLocExpression(newExpr->getArraySize(), shouldDelay, receiver);
#endif
      // malloc(length * sizeof(A))
      result = exp_node_MallocArray(type->plain_type, size);
  }
  expression eresult =
    expression_cons(makeLocation(newExpr->getSourceRange()), result);
  type->plain_type = NULL;
  free_type(type);

  // Now, we have to initialize the content of the memory.

  if (newExpr->hasInitializer()) {
    const clang::CXXConstructExpr* constructor = newExpr->getConstructExpr();
    // Save the pointer returned by malloc in a fresh temporary variable
    const char* temp = mk_tmp_name();
    location loc = makeLocation(newExpr->getSourceRange());
    expression tmp_expr =
      expression_cons(
        copy_loc(loc),
        exp_node_Variable(variable_Local(qualified_name_cons(NULL, temp))));
    expression tmpvar =
      expression_cons(loc, exp_node_Assign(tmp_expr, eresult));
    if (!constructor) {
      // Initializing a scalar value, as in new int (10);
      // Translate that as a local definition + an assignment:
      // (int * tmp = malloc(sizeof(int)), *tmp = 10, tmp);
      result =
        exp_node_Temporary(
          strdup(temp),
          qual_type_cons(
            NULL,
            typ_Pointer(
              pkind_PDataPointer(
                makeDefaultType(
                  newExpr->getExprLoc(), newExpr->getAllocatedType())))),
          init_expr_Single_init(eresult), false);
      eresult = expression_cons(copy_loc(loc), result);
      expression init =
        makeLocExpression(newExpr->getInitializer(), shouldDelay, receiver);
      expression assign =
        expression_cons(
          copy_loc(loc),
          exp_node_Assign(
            expression_cons(
              copy_loc(loc),
              exp_node_Dereference(tmp_expr)),init));
      result = exp_node_Binary_operator(BOCOMMA, AKRVALUE, eresult, assign);
      eresult = expression_cons(copy_loc(loc), result);
      result =
        exp_node_Binary_operator(
          BOCOMMA, AKRVALUE, eresult, expression_dup(tmp_expr));
    }
    else {
      if(!newExpr->isArray()) {
          // *(tmp = (A*)malloc()) = initializer
        eresult =
          expression_cons(
            loc,
            exp_node_Dereference(
              expression_cons(
                copy_loc(loc),
                exp_node_PointerCast(
                  qual_type_cons(
                    NULL,
                    typ_LVReference(
                      pkind_PDataPointer(
                        makeDefaultType(
                          newExpr->getExprLoc(),
                          newExpr->getAllocatedType())))),
              reference_or_pointer_kind_RPKPointer(),
              tmpvar))));
        FramaCIRGenAction::ExpressionGuard guard(*this, eresult);
        // A::Ctor(...)
        exp_node call_node = makeConstructExpression(constructor, shouldDelay,
          receiver, true, false, guard);
        result =
          exp_node_Temporary(
            strdup(temp),
            qual_type_cons(
              NULL,
              typ_Pointer(
                pkind_PDataPointer(
                  makeDefaultType(
                    newExpr->getExprLoc(), newExpr->getAllocatedType())))),
            init_expr_Single_init(
              expression_cons(
                copy_loc(loc),
                call_node)),
            false);
      }
      else {
        // tmp = malloc()
        statement allocation = statement_Expression(copy_loc(loc), tmpvar);
        // "i"
        const char* loopVariableName = mk_tmp_name();
        // i
        expression loopVariableAsExpr =
          expression_cons(
            copy_loc(loc),
            exp_node_Variable(
              variable_Local(qualified_name_cons(NULL, loopVariableName))));
        // tmp[i]
        expression nthElt =
          expression_cons(
            copy_loc(loc),
            exp_node_ArrayAccess(expression_dup(tmp_expr), loopVariableAsExpr));
        FramaCIRGenAction::ExpressionGuard guard(*this, nthElt);
        // A::Ctor(&tmp[i])
        exp_node call_node = makeConstructExpression(constructor, shouldDelay,
          receiver, true, false, guard);
        expression call = expression_cons(copy_loc(loc),call_node);
        // unsigned long long
        qual_type loopVariableType =
          qual_type_cons(
            NULL,
            typ_Int(
              IULONGLONG));
        // (unsigned long long)0;
        init_expr loopVariableInit =
          init_expr_Single_init(makeIntLiteral(loc,IULONGLONG,0));
        // unsigned long long i = 0;
        list init =
          cons_container(
            init_declarator_cons(
              loopVariableName,
              loopVariableType,
              opt_some_container(
                loopVariableInit)),
            NULL);
        // ++i
        incr_statement incr =
          incr_statement_CExpression(
            expression_cons(
              copy_loc(loc),
              exp_node_Unary_operator(
                uokind_UOPreInc(),
                loopVariableAsExpr)));
        // length
        expression size =
#if CLANG_VERSION_MAJOR >= 9
          (!newExpr->getArraySize().hasValue())
            ? makeIntLiteral(copy_loc(loc), IINT, 0)
            : makeLocExpression(
                *newExpr->getArraySize(),
                shouldDelay,
                receiver);
#else
          expression_cons(
            copy_loc(loc),
            makeExpression(
              newExpr->getArraySize(),
              shouldDelay,
              receiver));
#endif
        // i < length
        expression cond =
          expression_cons(
            copy_loc(loc),
            exp_node_Binary_operator(
              BOLESS,
              AKRVALUE,
              loopVariableAsExpr,
              size));
        // for(unsigned long long i = 0; i < length; ++i)
        //   A::Ctor(&tmp[i]);
        statement forStatement =
          statement_For(
            copy_loc(loc),
            init_statement_IVarDecl(
              init),
            opt_some_container(
              cond),
            incr,
            statement_Expression(
              copy_loc(loc),
              call),
            NULL);
        list statements = NULL;
        statements =
          cons_container(
            statement_Expression(
              copy_loc(loc),
              expression_cons(
                copy_loc(loc),
                exp_node_Variable(
                  variable_Local(
                    qualified_name_cons(
                      NULL,
                      temp))))),
            statements);
        statements = cons_container(forStatement, statements);
        statements = cons_container(allocation, statements);
        statements =
          cons_container(
            statement_VarDecl(
              copy_loc(loc),
              strdup(temp),
              qual_type_cons(
                NULL,
                typ_Pointer(
                  pkind_PDataPointer(
                    makeDefaultType(
                      newExpr->getExprLoc(),
                      newExpr->getAllocatedType())))),
              opt_none()),
            statements);
        /*
         * statements:
         * A* tmp = malloc(length * sizeof(A));
         * for(unsigned long long i = 0; i < length; ++i)
         *   A::Ctor(&tmp[i]);
         * tmp;
         */
        // ({statements})
        result = exp_node_GnuBody(statements);
      }
    };
  };
  return result;
}

void FramacVisitor::ensureBuiltinDeclaration(
  unsigned builtinID, const clang::FunctionDecl* fd, bool doesForceVariadic)
{ if (!isGeneratedBuiltin(builtinID)) {
    const char* name = copy_string(fd->getNameAsString ());
    clang::SourceLocation sloc = fd->getLocation();
    location loc = makeLocation(fd->getSourceRange());
    qual_type return_type =
      makeDefaultExternalNameType(sloc, fd->getReturnType());
    list /*arg_decl*/ prms = NULL;
    ForwardReferenceList params(prms);
    if (builtinID >= clang::Builtin::BI__atomic_load
        && builtinID <= clang::Builtin::BI__atomic_nand_fetch
        && return_type->plain_type->tag_typ == VOID) {
      free_typ(return_type->plain_type);
      return_type->plain_type = typ_Int(IINT);
      arg_decl cdecl = (arg_decl)malloc(sizeof(*cdecl));
      cdecl->arg_name = strdup("__frama_c_arg_0");
      cdecl->arg_type = qual_type_cons(NULL, typ_Pointer(
        pkind_PDataPointer(qual_type_cons(NULL, typ_Void()))));
      cdecl->arg_loc = copy_loc(loc);
      params.insertContainer(cdecl);
    }
    else if (builtinID == clang::Builtin::BI__builtin_va_end
          || builtinID == clang::Builtin::BI__builtin_va_start) {
      arg_decl cdecl = (arg_decl)malloc(sizeof(*cdecl));
      const clang::ParmVarDecl *prm = fd->getParamDecl(0);
      if (prm->getNameAsString().size() > 0)
        cdecl->arg_name = copy_string(prm->getNameAsString());
      else
        cdecl->arg_name = strdup("__frama_c_arg_0");
      cdecl->arg_type = qual_type_cons(NULL, typ_Named(
        qualified_name_cons(NULL, strdup("__builtin_va_list")), true));
      cdecl->arg_loc = makeLocation(prm->getSourceRange());
      params.insertContainer(cdecl);
    } else {
      int i = 0;
      clang::FunctionDecl::param_const_iterator stop = fd->param_end();
      for (clang::FunctionDecl::param_const_iterator it = fd->param_begin(); 
           it!=stop;it++) {
        if (it!=fd->param_begin() || !doesForceVariadic
            || !(*it)->getOriginalType()->isVoidType()) {
        std::string name = (*it)->getNameAsString();
        if (name.size() == 0) {
          std::ostringstream out;
          out << "__frama_c_arg_" << i++;
          name = out.str();
        };
        clang::SourceLocation sloc = (*it)->getLocation();
        qual_type prm_type =
          makeDefaultExternalNameType(sloc, (*it)->getOriginalType());
        location loc = makeLocation((*it)->getSourceRange());
        params.insertContainer(arg_decl_cons(prm_type,copy_string(name),loc));
        }
      }
    }
    decl_or_impl_name decl_name = decl_or_impl_name_Declaration(name);
    translation_unit_decl func =
      translation_unit_decl_Function(
        decl_name, funkind_FKFunction(), loc, return_type, prms,
        opt_none() /* body */, true /* fd->isExternC() */, false,
        doesForceVariadic || fd->isVariadic(), tkind_TStandard(),
        false /* has_further_definition */,
        opt_none() /* throws */,
        opt_none() /* contract */);
    if (_clangUtils->isExternCContext(_lexicalContextForPostVisit)
         && _clangUtils->isExternCContext(_semanticContextForPostVisit))
      _globals.insertContainer(func);
    else
      _globals.insertBeforeContainer(func);
    if (builtinID < clang::Builtin::FirstTSBuiltin)
      setGeneratedBuiltin(builtinID);
  };
}

bool FramacVisitor::is_lambda_call(const clang::CallExpr* call) {
  if (call->getStmtClass() == clang::Stmt::CXXOperatorCallExprClass) {
    const clang::CXXOperatorCallExpr* op =
      llvm::dyn_cast<clang::CXXOperatorCallExpr>(call);
    if (op->getOperator() == clang::OO_Call) {
      if (call->getNumArgs() > 0) {
        clang::QualType typ = call->getArg(0)->getType();
        const clang::CXXRecordDecl* rec = typ->getAsCXXRecordDecl();
        return (rec && rec->isLambda());
      }
    }
  }
  return false;
}

exp_node FramacVisitor::makeLambdaCallExpression(
  const clang::CallExpr* call, bool* shouldDelay, list* receiver,
  FramaCIRGenAction::ExpressionGuard& guard) {
  list arguments = NULL;
  clang::CallExpr::const_arg_iterator beg = call->arg_begin();
  clang::CallExpr::const_arg_iterator it = call->arg_end();
  expression lambda_obj = makeLocExpression(*beg, shouldDelay, receiver);
  beg++;
  while (beg < it) {
    it -= 1;
    expression arg = makeLocExpression(*it, shouldDelay, receiver);
    arguments = cons_container(arg, arguments);
  }
  exp_node result = exp_node_Lambda_call(lambda_obj, arguments);
  return
    convert_result(guard, call->getCallReturnType(*_context), result, call);
}

exp_node FramacVisitor::makeCallExpression(
  const clang::CallExpr* callExpr, bool* shouldDelay,
  /* statement */ list* receiver, FramaCIRGenAction::ExpressionGuard& guard) {
  funkind fkind;
  if (is_lambda_call(callExpr))
    return makeLambdaCallExpression(callExpr,shouldDelay,receiver,guard);
  const clang::FunctionDecl* fd = callExpr->getDirectCallee();
  if (fd) {
    clang::Decl::Kind kind = fd->getDeclKind();
    if (kind == clang::Decl::CXXConstructor)
      fkind = funkind_FKConstructor(true);
    else if (kind == clang::Decl::CXXDestructor)
      fkind = funkind_FKDestructor(true);
    else if ((kind >= clang::Decl::firstCXXMethod)
        && (kind <= clang::Decl::lastCXXMethod)) {
      if (fd->getCanonicalDecl()->getStorageClass() != clang::SC_Static)
        fkind = _clangUtils->cv_meth(
          static_cast<const clang::CXXMethodDecl*>(fd));
      else
        fkind = funkind_FKFunction();
    }
    else
      fkind = funkind_FKFunction();
    unsigned builtinID = fd->getBuiltinID();
    if (builtinID > 0) {
      ensureBuiltinDeclaration(builtinID, fd);
      _tableForWaitingDeclarations.addDeclaration(fd,_globals);
      _instanceContexts.removeUnvisited(fd);
    }
  }
  else if (clang::CXXOperatorCallExpr::classof(callExpr))
    /* TODO: check whether an operator can have cv qualification */
    fkind = funkind_FKMethod(NULL);
  else fkind = funkind_FKFunction ();
  clang::CallExpr::const_arg_iterator argIterEnd = callExpr->arg_end();
  list /* expression */ arguments = NULL;
  ForwardReferenceList forwardArguments(arguments);
  bool isFirstObject = (fkind->tag_funkind != FKFUNCTION);
  for (clang::CallExpr::const_arg_iterator argIter=callExpr->arg_begin();
      argIter != argIterEnd; ++argIter) {
    expression arg = makeLocExpression(*argIter, shouldDelay,receiver);
    if (isFirstObject) {
      arg =
        expression_cons(
          makeLocation((*argIter)->getSourceRange()),
          exp_node_Address(arg));
    };
    forwardArguments.insertContainer(arg);
    isFirstObject = false;
  };
  const clang::FunctionDecl* directCall = callExpr->getDirectCallee();
  if (directCall) {
    tkind templateExtension = NULL;
    if (directCall->getTemplateSpecializationKind()
        >= clang::TSK_ImplicitInstantiation) {
      clang::FunctionTemplateSpecializationInfo* info
          = directCall->getTemplateSpecializationInfo();
      if (info)
        templateExtension =
          tkind_TTemplateInstance(_clangUtils->getTemplateExtension(info));
    };
    if (!templateExtension)
      templateExtension = tkind_TStandard();
    qualified_name name = _clangUtils->makeQualifiedName(*directCall);
    if (fkind->tag_funkind == FKCONSTRUCTOR && strlen(name->decl_name) == 0) {
      free(const_cast<char*>(name->decl_name));
      name->decl_name = strdup("constructor-special");
    };
    if (hasInstanceContext()) {
      if (!_tableForWaitingDeclarations.hasVisited(directCall)
            && directCall != _parents.getSFunctionDecl())
        unvisitedDecls().push_back(directCall);
      else {
        clang::Decl::Kind kindDecl = directCall->getDeclContext()->getDeclKind();
        if (kindDecl >= clang::Decl::firstRecord
            && kindDecl <= clang::Decl::lastRecord)
          _tableForWaitingDeclarations.ensureGeneration(
            static_cast<const clang::RecordDecl*>(directCall->getDeclContext()),
            unvisitedDecls());
      };
    }
    else if (shouldDelay && !*shouldDelay)
      *shouldDelay = !_tableForWaitingDeclarations.hasVisited(directCall)
            && directCall != _parents.getSFunctionDecl();

    signature sig = _clangUtils->makeSignature(*directCall);
    exp_node result =
      exp_node_Static_call(
        name, sig, fkind, arguments,
        templateExtension, directCall->isInExternCContext());
    return
      convert_result(
        guard,callExpr->getCallReturnType(*_context),result,callExpr);
  };
  if (callExpr->getCallee()->getStmtClass()
      == clang::Stmt::CXXPseudoDestructorExprClass)
    return exp_node_Constant(compilation_constant_IntCst(IINT,
            ICSTATICCONST, 0));
  expression call =
    makeLocExpression(callExpr->getCallee(), shouldDelay,receiver);
  return
    convert_result(
      guard,
      callExpr->getCallReturnType(*_context),
      exp_node_Dynamic_call(fkind, call, arguments),
      callExpr);
}

exp_node FramacVisitor::makeMemberCallExpression(
  const clang::CXXMemberCallExpr* callExpr, bool* shouldDelay,
  /* statement */ list* receiver, FramaCIRGenAction::ExpressionGuard& guard)
{ 
  /*
    There are 4 kinds of member calls:
    - direct call to a non-static, non-virtual function (just need to add the
      this argument at the beginning of the list)
    - direct call to a virtual function (this argument + retrieve entry in
      virtual methode table)
    - call via a pointer-to-member to non-virtual function
    - call via a pointer-to-member to virtual function (currently unsupported)
   */
  clang::CXXMemberCallExpr::const_arg_iterator argIterEnd = callExpr->arg_end();
  const clang::Expr* thisArgument = callExpr->getImplicitObjectArgument();
  list /* expression */ arguments = NULL;
  ForwardReferenceList forwardArguments(arguments);
  const clang::Expr* callee = callExpr->getCallee()->IgnoreParens();
  // directCall will be NULL for pointer-to-member calls
  const clang::CXXMethodDecl* directCall = callExpr->getMethodDecl();
  // NB: as said above, pointer-to-member are assumed to be non-virtual.
  bool isVirtualCall = directCall ? directCall->isVirtual() : false;
  // even if the function is virtual, if we have qualified lookup, we'll end
  // up calling a specific version, without VT lookup.
  if (isVirtualCall) {
    assert(llvm::dyn_cast<const clang::MemberExpr>(callee));
    isVirtualCall =
      !static_cast<const clang::MemberExpr*>(callee)->hasQualifier();
  }
  // first, translate the receiver argument (i.e. this)
  expression argument = makeLocExpression(thisArgument, shouldDelay);
  // clang doc says that callee is a member expr
  // in fact, it contains the information whether we
  // have x.f(),  x->f() x.*f() or x->*f()
  clang::Stmt::StmtClass kind = callee->getStmtClass();
  assert (kind == clang::Stmt::BinaryOperatorClass
          || kind == clang::Stmt::MemberExprClass);
    // pointer to member call
  if (kind == clang::Stmt::BinaryOperatorClass) {
    assert(llvm::dyn_cast<const clang::BinaryOperator>(callee));
    const clang::BinaryOperator* binop =
      static_cast<const clang::BinaryOperator*>(callee);
    switch(binop->getOpcode())
      {
        case clang::BO_PtrMemD:
          argument =
            expression_cons(makeLocation(callee->getSourceRange()),
                            exp_node_Address(argument));
        case clang::BO_PtrMemI:
          break;
        default:
          std::cerr << "Unexpected opcode in method call: ";
          callee->dump();
          std::cerr << std::endl;
          exit(2);
      }
  } else {
    // normal call (either static or virtual)
    assert(llvm::dyn_cast<const clang::MemberExpr>(callee));
    const clang::MemberExpr* callee_member
      = static_cast<const clang::MemberExpr*>(callee);
    if(!callee_member->isArrow()) {
      argument =
        expression_cons(
          makeLocation(callee->getSourceRange()),
          exp_node_Address(argument));
    }
  }
  // for virtual calls, the receiver is still treated separately
  if (!isVirtualCall) forwardArguments.insertContainer(argument);

  // Now translate all the arguments
  for (clang::CXXMemberCallExpr::const_arg_iterator
      argIter = callExpr->arg_begin(); argIter != argIterEnd; ++argIter) {
    expression argument = makeLocExpression(*argIter, shouldDelay);
    forwardArguments.insertContainer(argument);
  };

  // Now, find which function to call
  // First, check whether we are in a template instantiation
  tkind templateExtension = NULL;
  if (directCall && directCall->getTemplateSpecializationKind()
      >= clang::TSK_ImplicitInstantiation) {
    clang::FunctionTemplateSpecializationInfo* info
      = directCall->getTemplateSpecializationInfo();
    if (info)
      templateExtension =
        tkind_TTemplateInstance(_clangUtils->getTemplateExtension(info));
  };
  if (!templateExtension) templateExtension = tkind_TStandard();
  if (!directCall) {
    // pointer to member call: we have a binary operator, and the
    // function pointer is the rhs part
    assert(llvm::dyn_cast<const clang::BinaryOperator>(callee) && _context);
    const clang::BinaryOperator* binop =
      static_cast<const clang::BinaryOperator*>(callee);
    expression call = makeLocExpression(binop->getRHS());
    return
      convert_result(
        guard,
        callExpr->getCallReturnType(*_context),
        exp_node_Dynamic_call(funkind_FKMethod(NULL), call, arguments),
        callExpr);

  }
  // direct call

  // Update tableForwaitingdeclarations as needed to provide functions
  // definitions in a suitable order.
  if (hasInstanceContext()) {
    if (!_tableForWaitingDeclarations.hasVisited(directCall)
        && directCall != _parents.getSFunctionDecl())
      unvisitedDecls().push_back(directCall);
    else {
      clang::Decl::Kind kindDecl =
        directCall->getDeclContext()->getDeclKind();
      if (kindDecl >= clang::Decl::firstRecord
          && kindDecl <= clang::Decl::lastRecord)
        _tableForWaitingDeclarations.ensureGeneration(
          static_cast<const clang::RecordDecl*>(
            directCall->getDeclContext()),
          unvisitedDecls());
    };
  }
  else if (shouldDelay && !*shouldDelay)
    *shouldDelay = !_tableForWaitingDeclarations.hasVisited(directCall)
      && directCall != _parents.getSFunctionDecl();
  
  qualified_name name = _clangUtils->makeQualifiedName(*directCall);
  signature sig = _clangUtils->makeSignature(*directCall);
  clang::QualType const& ret = callExpr->getCallReturnType(*_context);
  if (!isVirtualCall) {
    // static call: we just have a normal function call
    return convert_result(
      guard,ret,
      exp_node_Static_call(
        name, sig,
        _clangUtils->cv_meth(static_cast<const clang::CXXMethodDecl*>(
            directCall)), arguments, templateExtension, false),
      callExpr);
  };

  // virtual call: this is in fact an indirect call.
  // Retrieve appropriate pointer from VMT
  assert(templateExtension->tag_tkind == TSTANDARD);
  free(templateExtension);
  templateExtension = NULL;
  exp_node result =
    exp_node_Virtual_call(
      name, sig, _clangUtils->cv_meth(static_cast<const clang::CXXMethodDecl*>(
        directCall)), argument, arguments, 0, NULL, NULL);
  const_cast<RTTITable&>(_rttiTable).retrieveMethodIndex(*_clangUtils,
      callExpr->getMethodDecl()->getParent(), callExpr->getMethodDecl(),
      &result->cons_exp_node.Virtual_call.method_index,
      &result->cons_exp_node.Virtual_call.shift_object,
      &result->cons_exp_node.Virtual_call.shift_pvmt);
  return convert_result(guard,ret,result, callExpr);
}

exp_node
FramacVisitor::makeBaseToDerivedPointerCastExpression(
    const clang::CXXRecordDecl* base, qual_type baseType,
    const clang::CXXRecordDecl* derived, qual_type derivedType,
    expression expr) {
  assert(base && derived);
  RTTITable::InheritancePath inheritancePath;
  RTTITable::VirtualInheritancePath virtualInheritancePath(NULL, 0);
  _rttiTable.retrieveInheritancePathBetween(derived, base,
      inheritancePath, virtualInheritancePath, *_clangUtils);
  assert(!virtualInheritancePath.first);
  int sizeInheritancePath = (int) inheritancePath.size()-1;
  assert(sizeInheritancePath >= 0);
  exp_node nodeResult = exp_node_ShiftPointerCast(
      derivedType, baseType, reference_or_pointer_kind_RPKPointer(), expr);
  while (--sizeInheritancePath >= 0) {
    const clang::CXXRecordDecl
      *localDerived = inheritancePath[sizeInheritancePath].first;
    tkind derived_kind = _clangUtils->makeTemplateKind(localDerived);
    qual_type localDerivedType =
      qual_type_cons(
        NULL,
        typ_Pointer(
          pkind_PDataPointer(
            qual_type_cons(
              NULL,
              typ_Struct(
                _clangUtils->makeQualifiedName(*localDerived),derived_kind)))));
    exp_node tmpResult = exp_node_ShiftPointerCast(
      localDerivedType, qual_type_dup(localDerivedType),
      reference_or_pointer_kind_RPKPointer(),
      expression_cons(copy_loc(expr->eloc), nodeResult));
    qual_type tmp=nodeResult->cons_exp_node.ShiftPointerCast.cast_type;
    nodeResult->cons_exp_node.ShiftPointerCast.cast_type
      = tmpResult->cons_exp_node.ShiftPointerCast.cast_type;
    tmpResult->cons_exp_node.ShiftPointerCast.cast_type = tmp;
    nodeResult = tmpResult;
  };
  return nodeResult;
}

exp_node FramacVisitor::makeBaseToDerivedReferenceCastExpression(
    const clang::CXXRecordDecl* base, qual_type baseType,
    const clang::CXXRecordDecl* derived, qual_type derivedType,
    expression expr) {
  assert(base && derived);
  RTTITable::InheritancePath inheritancePath;
  RTTITable::VirtualInheritancePath virtualInheritancePath(NULL, 0);
  _rttiTable.retrieveInheritancePathBetween(derived, base,
      inheritancePath, virtualInheritancePath, *_clangUtils);
  assert(!virtualInheritancePath.first);
  int sizeInheritancePath = (int) inheritancePath.size()-1;
  assert(sizeInheritancePath >= 0);
  exp_node nodeResult = exp_node_ShiftPointerCast(
      qual_type_cons(NULL, typ_LVReference(pkind_PDataPointer(derivedType))),
      baseType, reference_or_pointer_kind_RPKReference(), expr);
  while (--sizeInheritancePath >= 0) {
    const clang::CXXRecordDecl
      *localDerived = inheritancePath[sizeInheritancePath].first;
    tkind derived_kind = _clangUtils->makeTemplateKind(localDerived);
    qual_type localDerivedType =
      qual_type_cons(
        NULL,
        typ_LVReference(
          pkind_PDataPointer(
            qual_type_cons(
              NULL,
              typ_Struct(
                _clangUtils->makeQualifiedName(*localDerived),derived_kind)))));
    exp_node tmpResult = exp_node_ShiftPointerCast(
      localDerivedType,
      qual_type_dup(localDerivedType->plain_type->cons_typ.LVReference
          .kind->cons_pkind.PDataPointer.subtype),
      reference_or_pointer_kind_RPKReference(),
      expression_cons(copy_loc(expr->eloc), nodeResult));
    qual_type tmp=nodeResult->cons_exp_node.ShiftPointerCast.cast_type;
    nodeResult->cons_exp_node.ShiftPointerCast.cast_type
      = tmpResult->cons_exp_node.ShiftPointerCast.cast_type;
    tmpResult->cons_exp_node.ShiftPointerCast.cast_type = tmp;
    nodeResult = tmpResult;
  };
  return nodeResult;
}

exp_node FramacVisitor::makeDerivedToBaseCastExpression(
  ptr_or_ref kind,
  const clang::CXXRecordDecl* derived, qual_type baseType,
  const clang::CXXRecordDecl* base, expression expr, bool* shouldDelay)
{ assert(base && derived);
  if (hasInstanceContext()) {
    _tableForWaitingDeclarations.ensureGeneration(derived, unvisitedDecls());
    _tableForWaitingDeclarations.ensureGeneration(base, unvisitedDecls());
  }
  else if (shouldDelay && !*shouldDelay) {
    *shouldDelay = !_tableForWaitingDeclarations.hasVisited(derived)
        || !_tableForWaitingDeclarations.hasVisited(base);
  };
  RTTITable::InheritancePath inheritancePath;
  RTTITable::VirtualInheritancePath virtualInheritancePath(NULL, 0);
  _rttiTable.retrieveInheritancePathBetween(
    derived, base, inheritancePath, virtualInheritancePath, *_clangUtils);

  exp_node nodeResult = NULL;
  int sizeInheritancePath = (int) inheritancePath.size()-1;
  // if we don't have a virtual base, the non-virtual inheritance path
  // cannot be empty
  assert(virtualInheritancePath.first || sizeInheritancePath >= 0);
  // if the base class is part of a virtual base of derived (either
  // directly a virtual base, or a class the virtual base inherits from),
  // we first perform an offset computation, potentially followed by
  // a sequence of non-virtual casts
  if (virtualInheritancePath.first) {
    // const clang::ClassTemplateSpecializationDecl* TSD = NULL;
    tkind tk = _clangUtils->makeTemplateKind(derived);
    auto pk_derived =
      pkind_PDataPointer(
        qual_type_cons(
          NULL, typ_Struct(_clangUtils->makeQualifiedName(*derived),tk)));
    auto t_derived =
      kind == PTR ? typ_Pointer(pk_derived) : typ_LVReference(pk_derived);
    qual_type derivedType = qual_type_cons(NULL, t_derived);
    const clang::CXXRecordDecl* derivedClass = virtualInheritancePath.first;
    qual_type localDerivedType = baseType;
    if (sizeInheritancePath >= 0) {
      localDerivedType = qual_type_dup(derivedType);
    };
    auto rpk =
      kind == PTR ?
      reference_or_pointer_kind_RPKVirtualBasePointer(
        virtualInheritancePath.second, derivedType, false) :
      reference_or_pointer_kind_RPKVirtualBaseReference(
        virtualInheritancePath.second, derivedType);
    nodeResult = exp_node_PointerCast(localDerivedType, rpk, expr);
    if (virtualInheritancePath.second < 0) {
      auto id = nodeResult->cons_exp_node.PointerCast.ref_pointer;
      auto idx =
        kind == PTR ?
        &id->cons_reference_or_pointer_kind.RPKVirtualBasePointer.base_index:
        &id->cons_reference_or_pointer_kind.RPKVirtualBaseReference.base_index;
      const_cast<RTTITable&>(_rttiTable).retrieveBaseIndex(
        *_clangUtils,
        derived, const_cast<clang::CXXRecordDecl*>(derivedClass), idx);
    }
  };
  // now compute the non-virtual part of the pointer cast.
  if (sizeInheritancePath >= 0) {
    auto exp = nodeResult?expression_cons(copy_loc(expr->eloc),nodeResult):expr;
    auto rpk =
      kind == PTR ?
      reference_or_pointer_kind_RPKStaticBasePointer ():
      reference_or_pointer_kind_RPKStaticBaseReference ();
    nodeResult = exp_node_PointerCast(baseType, rpk, exp);
  }
  for (int index = 0; index < sizeInheritancePath; ++index) {
    const clang::CXXRecordDecl
      *localBase = inheritancePath[index].first;
    auto tk = _clangUtils->makeTemplateKind(localBase);
    auto pk_data =
      pkind_PDataPointer(
        qual_type_cons(
          NULL,typ_Struct(_clangUtils->makeQualifiedName(*localBase), tk)));
    auto typ =
      kind == PTR ? typ_Pointer(pk_data) : typ_LVReference(pk_data);
    qual_type localBaseType = qual_type_cons(NULL,typ);
    auto rpk =
      kind == PTR ?
      reference_or_pointer_kind_RPKStaticBasePointer() :
      reference_or_pointer_kind_RPKStaticBaseReference();
    exp_node tmpResult =
      exp_node_PointerCast(
        localBaseType, rpk, nodeResult->cons_exp_node.PointerCast.sub);
    nodeResult->cons_exp_node.PointerCast.sub =
        expression_cons(copy_loc(expr->eloc), tmpResult);
  };
  return nodeResult;
}

exp_node FramacVisitor::makeCastExpression(
  const clang::CastExpr* castExpr,
  bool* shouldDelay, /* statement */ list* receiver,
  FramaCIRGenAction::ExpressionGuard& guard) {
  expression subExpr =
    makeLocExpression(castExpr->getSubExpr(), shouldDelay, receiver);
  qual_type resultType =
    makeDefaultType(castExpr->getExprLoc(), castExpr->getType());
  switch (castExpr->getCastKind()) {
    case clang::CK_BitCast:
      return guard.setAssignResult(exp_node_Unary_operator(
           uokind_UOCastC(resultType),subExpr), castExpr);
    case clang::CK_LValueBitCast:
      return guard.setAssignResult(exp_node_Dereference(
        expression_cons(copy_loc(subExpr->eloc), exp_node_Unary_operator(
          uokind_UOCastC(qual_type_cons(NULL, typ_Pointer(pkind_PDataPointer(
            resultType)))), expression_cons(copy_loc(subExpr->eloc),
              exp_node_Address(subExpr))))), castExpr);
    case clang::CK_ToUnion:
    case clang::CK_VectorSplat:
    case clang::CK_CPointerToObjCPointerCast:
    case clang::CK_BlockPointerToObjCPointerCast:
    case clang::CK_AnyPointerToBlockPointerCast:
    case clang::CK_ObjCObjectLValueCast:
    case clang::CK_ARCProduceObject:
    case clang::CK_ARCConsumeObject:
    case clang::CK_ARCReclaimReturnedObject:
    case clang::CK_ARCExtendBlockObject:
    case clang::CK_AtomicToNonAtomic:
    case clang::CK_NonAtomicToAtomic:
    case clang::CK_CopyAndAutoreleaseBlockObject:
    case clang::CK_BuiltinFnToFnPtr:
      std::cerr << "Unsupported cast:";
1910
1911
1912
#if CLANG_VERSION_MAJOR >= 11
      castExpr->dump(llvm::errs(), *_context);
#else
1913
      castExpr->dump(llvm::errs(), _context->getSourceManager());
1914
#endif
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
      std::cerr << "\nAborting\n";
      exit(2);
    case clang::CK_FloatingRealToComplex:
    case clang::CK_FloatingComplexToReal:
    case clang::CK_FloatingComplexToBoolean:
    case clang::CK_FloatingComplexCast:
    case clang::CK_FloatingComplexToIntegralComplex:
    case clang::CK_IntegralRealToComplex:
    case clang::CK_IntegralComplexToReal:
    case clang::CK_IntegralComplexToBoolean:
    case clang::CK_IntegralComplexCast:
    case clang::CK_IntegralComplexToFloatingComplex:
      std::cerr << "Unsupported context cast:";
1928
1929
1930
#if CLANG_VERSION_MAJOR >= 11
      castExpr->dump(llvm::errs(), *_context);
#else
1931
      castExpr->dump(llvm::errs(), _context->getSourceManager());
1932
#endif
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
      std::cerr << "\nAborting\n";
      exit(2);
    case clang::CK_ToVoid:
      return
        guard.setAssignResult(
          exp_node_Unary_operator(uokind_UOCastToVoid(), subExpr), castExpr);
    case clang::CK_LValueToRValue:
      // does not exactly denote a cast from "reference to T" to "T":
      // we need to use another indicator to introduce the appropriate
      // transformation, see ClangUtils::lvalHasRefType for more information
    case clang::CK_NoOp:
      return
        guard.setAssignResult(
          exp_node_Unary_operator(uokind_UOCastNoEffect(resultType), subExpr),
          castExpr);
    case clang::CK_BaseToDerived:
      { qual_type baseType =
          makeDefaultType(
            castExpr->getSubExpr()->getExprLoc(),
            castExpr->getSubExpr()->getType());
        if (castExpr->getType()->isPointerType())
          /* isArrayType(), isFunctionType(), isPointerType(),
             isReferenceType(), isRecordType(), isUnionType(),
             isEnumeralType(), isMemberPointerType() */
          return guard.setAssignResult(
            makeBaseToDerivedPointerCastExpression(
              castExpr->getSubExpr()->getType()->getPointeeCXXRecordDecl(),
              baseType, castExpr->getType()->getPointeeCXXRecordDecl(),
              resultType, subExpr), castExpr);
        return guard.setAssignResult(
          makeBaseToDerivedReferenceCastExpression(
            castExpr->getSubExpr()->getType()->getAsCXXRecordDecl(), baseType,
            castExpr->getType()->getAsCXXRecordDecl(), resultType, subExpr),
          castExpr);
      }
    case clang::CK_UncheckedDerivedToBase:
    case clang::CK_DerivedToBase:
      if (castExpr->getType()->isPointerType())
        /* isArrayType(), isFunctionType(), isPointerType(),
           isReferenceType(), isRecordType(), isUnionType(),
           isEnumeralType(), isMemberPointerType() */
          return guard.setAssignResult(
            makeDerivedToBaseCastExpression(
              PTR,
              castExpr->getSubExpr()->getType()->getPointeeCXXRecordDecl(),
              resultType, castExpr->getType()->getPointeeCXXRecordDecl(),
              subExpr, shouldDelay),
            castExpr);
        return guard.setAssignResult(
          makeDerivedToBaseCastExpression(
            REF,
            castExpr->getSubExpr()->getType()->getAsCXXRecordDecl(),
            qual_type_cons(NULL, typ_LVReference(pkind_PDataPointer(resultType))),
            castExpr->getType()->getAsCXXRecordDecl(), subExpr,
            shouldDelay),
          castExpr);
    case clang::CK_ArrayToPointerDecay:
    case clang::CK_FunctionToPointerDecay:
    case clang::CK_NullToMemberPointer:
    case clang::CK_NullToPointer:
      if (castExpr->getType()->isReferenceType())
        /* isArrayType(), isFunctionType(), isPointerType(),
           isReferenceType(), isRecordType(), isUnionType(),
           isEnumeralType(), isMemberPointerType() */
        return guard.setAssignResult(exp_node_PointerCast(resultType,
              reference_or_pointer_kind_RPKReference(), subExpr), castExpr);
      return guard.setAssignResult(exp_node_PointerCast(resultType,
            reference_or_pointer_kind_RPKPointer(), subExpr), castExpr);
    case clang::CK_IntegralToPointer:
    case clang::CK_ReinterpretMemberPointer:
      return guard.setAssignResult(exp_node_PointerCast(resultType,
            reference_or_pointer_kind_RPKPointer(), subExpr), castExpr);
    case clang::CK_MemberPointerToBoolean:
    case clang::CK_PointerToBoolean:
    case clang::CK_IntegralToBoolean:
    case clang::CK_FloatingToBoolean:
      return guard.setAssignResult(exp_node_Unary_operator(
          uokind_UOCastInteger(resultType, IBOOL)/*, AKRVALUE*/, subExpr),
        castExpr);
    case clang::CK_PointerToIntegral:
    case clang::CK_IntegralCast:
    case clang::CK_IntegralToFloating:
    case clang::CK_FloatingToIntegral:
    case clang::CK_FloatingCast:
      if (resultType->plain_type->tag_typ==ENUM)
        return guard.setAssignResult(exp_node_Unary_operator(
          uokind_UOCastEnum(resultType, resultType->plain_type
            ->cons_typ.Enum.kind), /*AKRVALUE,*/ subExpr), castExpr);
      if (resultType->plain_type->tag_typ==INT)
        return guard.setAssignResult(exp_node_Unary_operator(
          uokind_UOCastInteger(resultType, resultType->plain_type
            ->cons_typ.Int.kind), /* AKRVALUE,*/ subExpr), castExpr);
      if (resultType->plain_type->tag_typ==FLOAT)
        return guard.setAssignResult(exp_node_Unary_operator(
          uokind_UOCastFloat(resultType, resultType->plain_type
            ->cons_typ.Float.kind), /* AKRVALUE,*/ subExpr), castExpr);
      return guard.setAssignResult(exp_node_Unary_operator(
          uokind_UOCastC(resultType),subExpr), castExpr);
    case clang::CK_UserDefinedConversion: /* should be translated */
    case clang::CK_ConstructorConversion: {
      exp_node content = subExpr->econtent;
      free_qual_type(resultType);
      free_location(subExpr->eloc);
      free(subExpr);
      return guard.setAssignResult(content, castExpr);
    }
    case clang::CK_Dynamic:
      return
        guard.setAssignResult(
          makeDynamicCastExpressionAux(
            _clangUtils->getBeginLoc(*castExpr), castExpr->getType(),
            castExpr->getSubExpr()->getType(), subExpr),
          castExpr);
    default:
      { std::cerr << "Unsupported context cast:";
2048
2049
2050
#if CLANG_VERSION_MAJOR >= 11
        castExpr->dump(llvm::errs(), *_context);
#else
2051
        castExpr->dump(llvm::errs(), _context->getSourceManager());
2052
#endif
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
        std::cerr << "\nAborting\n";
        exit(2);
      };
  };
}

exp_node FramacVisitor::makeDynamicCastExpressionAux(
  const clang::SourceLocation loc,
  const clang::QualType result_type,
  const clang::QualType orig_type,
  expression subExpr)
{
  bool isReferenceType = result_type->isReferenceType();
  auto resultType = makeDefaultType(loc, result_type);
  init_expr init_arg =
    init_expr_Single_init(
      !isReferenceType ?
      subExpr:
      expression_cons(copy_loc(subExpr->eloc), exp_node_Address(subExpr)));
  const char* temp = mk_tmp_name();
  expression arg =
    expression_cons(
      copy_loc(subExpr->eloc),
      exp_node_Temporary(
        temp,
        qual_type_cons(
          NULL,
          typ_Pointer(
            pkind_PDataPointer(
              makeDefaultType(loc, orig_type->getPointeeType())))),
        init_arg, true));
  auto c_orig_type = makeDefaultType(loc,orig_type);
  auto orig_var =
    expression_cons(
      copy_loc(subExpr->eloc),
      exp_node_Variable(
        variable_Local(qualified_name_cons(NULL,strdup(temp)))));
  // auto orig_exp =
  //   isReferenceType?
  //   expression_cons(copy_loc(subExpr->eloc), exp_node_Dereference(orig_var)):
  //   orig_var;
  auto pvmt =
    _rttiTable.getPvmt(
      *_clangUtils,orig_type->getPointeeCXXRecordDecl(), orig_var);
  auto casted_exp =
    isReferenceType?
    expression_cons(copy_loc(subExpr->eloc), exp_node_Dereference(arg)) : arg;
  auto rpk_res =
    (isReferenceType?
     reference_or_pointer_kind_RPKDynamicReference:
     reference_or_pointer_kind_RPKDynamicPointer)
    (c_orig_type, pvmt);
  return exp_node_PointerCast(resultType, rpk_res, casted_exp);
}

exp_node FramacVisitor::makeDynamicCastExpression(
    const clang::CXXDynamicCastExpr* castExpr, bool* shouldDelay,
    /* statement */ list* receiver, FramaCIRGenAction::ExpressionGuard& guard) {
  // expression subExpr =
  //   makeLocExpression(castExpr->getSubExpr(), shouldDelay, receiver);
  // qual_type resultType =
  //   makeDefaultType(castExpr->getExprLoc(), castExpr->getType());

  const clang::CXXRecordDecl* base = castExpr->getSubExpr()->getType()
      .getTypePtr()->getPointeeCXXRecordDecl();
  const clang::CXXRecordDecl* derived = castExpr->getType().getTypePtr()
      ->getPointeeCXXRecordDecl();
  if (!base)
    base = castExpr->getSubExpr()->getType().getTypePtr()
        ->getCanonicalTypeInternal().getTypePtr()->getAsCXXRecordDecl();
  if (!derived)
    derived = castExpr->getType().getTypePtr()
        ->getCanonicalTypeInternal().getTypePtr()->getAsCXXRecordDecl();
  if (base && derived) {
    if (hasInstanceContext()) {
      _tableForWaitingDeclarations.ensureGeneration(derived, unvisitedDecls());
      _tableForWaitingDeclarations.ensureGeneration(base, unvisitedDecls());
    }
    else if (shouldDelay && !*shouldDelay) {
      *shouldDelay = !_tableForWaitingDeclarations.hasVisited(derived)
          || !_tableForWaitingDeclarations.hasVisited(base);
    };
  };
  return
    guard.setAssignResult(
      makeDynamicCastExpressionAux(
        _clangUtils->getBeginLoc(*castExpr), castExpr->getType(),
        castExpr->getSubExpr()->getType(),
        makeLocExpression(castExpr->getSubExpr())),
      castExpr);
}

exp_node FramacVisitor::makeCompoundLiteralExpression(
    const clang::CompoundLiteralExpr* compoundExpr,
    bool* shouldDelay, /* statement */ list* receiver,
    bool hasImplicitThisStar, FramaCIRGenAction::ExpressionGuard& guard) {
  clang::QualType ctype = compoundExpr->getType();
  qual_type typ =
    makeDefaultType(compoundExpr->getExprLoc(), ctype);
  expression address = NULL;
  if (hasImplicitThisStar) {
    expression lval = guard.releaseExpr ();
    location loc = makeLocation(compoundExpr->getSourceRange());
    lval = getNodeReference(lval, compoundExpr->getType());
    address = expression_cons(loc,exp_node_Address(lval));
  };
  init_expr init =
    makeInitExpr(ctype, compoundExpr->getInitializer(), shouldDelay);
  const char* temp = mk_tmp_name();
  exp_node res = exp_node_Temporary(temp, typ, init, false);
  if (address) {
    location loc = makeLocation(compoundExpr->getSourceRange());
    res = exp_node_Assign(address, expression_cons(loc,res));
  };
  return res;
}

exp_node FramacVisitor::makeDeclRefExpression(
    const clang::DeclRefExpr* variableExpr, bool* shouldDelay,
    /* statement */ list* receiver, FramaCIRGenAction::ExpressionGuard& guard) {
  variable result = NULL;
  clang::Decl::Kind kind = variableExpr->getDecl()->getKind();
  if (kind == clang::Decl::Field) {
    std::cerr << "Unsupported field access:";
2177
2178
2179
#if CLANG_VERSION_MAJOR >= 11
    variableExpr->dump(llvm::errs(), *_context);
#else
2180
    variableExpr->dump(llvm::errs(), _context->getSourceManager());
2181
#endif
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
    std::cerr << "\nAborting\n";
    exit(2);
  }
  else if (kind >= clang::Decl::firstFunction
      && kind <= clang::Decl::lastFunction) {
    assert(llvm::dyn_cast<clang::FunctionDecl>(variableExpr->getDecl()));
    const clang::FunctionDecl* function
      = static_cast<const clang::FunctionDecl*>(variableExpr->getDecl());
    if (hasInstanceContext()) {
      if (!_tableForWaitingDeclarations.hasVisited(function)
            && function != _parents.getSFunctionDecl())
        unvisitedDecls().push_back(function);
      else {
        clang::Decl::Kind kindDecl = function->getDeclContext()->getDeclKind();
        if (kindDecl >= clang::Decl::firstRecord
            && kindDecl <= clang::Decl::lastRecord)
          _tableForWaitingDeclarations.ensureGeneration(
            static_cast<const clang::RecordDecl*>(function->getDeclContext()),
            unvisitedDecls());
      };
    }
    else if (shouldDelay && !*shouldDelay)
      *shouldDelay = !_tableForWaitingDeclarations.hasVisited(function)
            && function != _parents.getSFunctionDecl();
    tkind templateExtension = NULL;
    if (function->getTemplateSpecializationKind()
        >= clang::TSK_ImplicitInstantiation) {
      clang::FunctionTemplateSpecializationInfo* info
        = function->getTemplateSpecializationInfo();
      if (info)
        templateExtension =
          tkind_TTemplateInstance(_clangUtils->getTemplateExtension(info));
    };
    if (!templateExtension)
      templateExtension = tkind_TStandard();
    funkind fkind;
    if (kind == clang::Decl::CXXConstructor)
      fkind = funkind_FKConstructor(true);
    else if (kind == clang::Decl::CXXDestructor)
      fkind = funkind_FKDestructor(true);
    else if ((kind >= clang::Decl::firstCXXMethod)
             && (kind <= clang::Decl::lastCXXMethod)) {
      if (function->getCanonicalDecl()->getStorageClass() != clang::SC_Static)
        fkind = _clangUtils->cv_meth(static_cast<const clang::CXXMethodDecl*>(
          function));
      else
        fkind = funkind_FKFunction();
    }
    else
      fkind = funkind_FKFunction();
    signature sig = _clangUtils->makeSignature(*function);
    qualified_name qual = _clangUtils->makeQualifiedName(*function);
    if (fkind->tag_funkind == FKCONSTRUCTOR && strlen(qual->decl_name) == 0) {
      free(const_cast<char*>(qual->decl_name));
      qual->decl_name = strdup("constructor-special");
    };
    result = variable_CodePointer(qual, sig, fkind, 
      function->isInExternCContext(), templateExtension);
  }
  else if (kind == clang::Decl::Var) {
    assert(llvm::dyn_cast<clang::VarDecl>(variableExpr->getDecl()));
    const clang::VarDecl* var
        = static_cast<const clang::VarDecl*>(variableExpr->getDecl());
    if (var->hasLocalStorage())
      result = variable_Local(_clangUtils->makeQualifiedName(*var));
    else { // var->hasGlobalStorage()
      result = variable_Global(_clangUtils->makeQualifiedName(*var));
      if (shouldDelay && !*shouldDelay) {
        *shouldDelay = !_tableForWaitingDeclarations.hasVisited(var);
      };
    }
  }
  else if (kind == clang::Decl::ImplicitParam)
    result = variable_FunctionParameter(strdup(variableExpr
        ->getDecl()->getName().str().c_str()));
  else if (kind == clang::Decl::ParmVar)
    result = variable_FunctionParameter(strdup(variableExpr
        ->getDecl()->getName().str().c_str()));
  else if (kind == clang::Decl::EnumConstant) {
    assert(llvm::dyn_cast<clang::EnumConstantDecl>(variableExpr->getDecl()));
    const clang::EnumConstantDecl* enumDecl
      = static_cast<const clang::EnumConstantDecl*>(variableExpr->getDecl());
    const clang::QualType t = enumDecl->getType();
    assert (llvm::dyn_cast<clang::EnumType const>(t));
    const clang::EnumType* enumType =
      static_cast<const clang::EnumType*>(t.getTypePtr());
2268
    const clang::EnumDecl* declEnum = enumType->getDecl();
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
    if (hasInstanceContext()) {
      if (!_tableForWaitingDeclarations.hasVisited(declEnum))
        unvisitedDecls().push_back(declEnum);
      else {
        clang::Decl::Kind kindDecl = declEnum->getDeclContext()->getDeclKind();
        if (kindDecl >= clang::Decl::firstRecord
            && kindDecl <= clang::Decl::lastRecord)
          _tableForWaitingDeclarations.ensureGeneration(
            static_cast<const clang::RecordDecl*>(declEnum->getDeclContext()),
            unvisitedDecls());
      };
    }
    else if (shouldDelay && !*shouldDelay)
      *shouldDelay = !_tableForWaitingDeclarations.hasVisited(
          enumType->getDecl());
    return
      guard.setAssignResult(
        exp_node_Constant(
          compilation_constant_EnumCst(
            _clangUtils->makeQualifiedName(*variableExpr->getDecl()),
2289
2290
2291
            ekind_cons(
              _clangUtils->makeQualifiedName(*declEnum),
              Clang_utils::isExternCContext(enumType->getDecl())),
2292
2293
2294
2295
2296
            (int64_t)enumDecl->getInitVal().getLimitedValue(UINT64_MAX))),
        variableExpr);
  }
  else if (kind == clang::Decl::IndirectField) {
    std::cerr << "Unsupported indirect field:";
2297
2298
2299
#if CLANG_VERSION_MAJOR >= 11
    variableExpr->dump(llvm::errs(), *_context);
#else
2300
    variableExpr->dump(llvm::errs(), _context->getSourceManager());
2301
#endif
2302
2303
2304
2305
2306
    std::cerr << "\nAborting\n";
    exit(2);
  }
  else {
    std::cerr << "Unsupported reference expression:";
2307
2308
2309
#if CLANG_VERSION_MAJOR >= 11
    variableExpr->dump(llvm::errs(), *_context);
#else
2310
    variableExpr->dump(llvm::errs(), _context->getSourceManager());
2311
#endif
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
    std::cerr << "\nAborting\n";
    exit(2);
  };
  exp_node eres = exp_node_Variable(result);
  if (_clangUtils->lvalHasRefType(variableExpr)) {
    location loc = makeLocation(variableExpr->getSourceRange());
    expression exp_res = expression_cons(loc,eres);
    eres = exp_node_Unary_operator(uokind_UOCastDeref(),exp_res);
  }
  return guard.setAssignResult(eres, variableExpr);
}

exp_node FramacVisitor::makeMaterializeTemporaryExpression(
    const clang::MaterializeTemporaryExpr* tmpExpr, bool* shouldDelay,
    /* statement */ list* receiver, FramaCIRGenAction::ExpressionGuard& guard) {
  expression oldThisStar = _implicitThisStar;
  location loc = makeLocation(tmpExpr->getSourceRange());
  const char* tmp = mk_materialized_tmp_name();
  qualified_name qtmp = qualified_name_cons(NULL,tmp);
  expression etmp =
    expression_cons(loc, exp_node_Variable(variable_Local(qtmp)));
  _implicitThisStar = etmp;
2334
2335
2336
2337
2338
2339
2340
  const clang::Expr* e =
#if CLANG_VERSION_MAJOR >= 10
    tmpExpr->getSubExpr();
#else
    tmpExpr->GetTemporaryExpr();
#endif
  init_expr temp = makeInitExpr(tmpExpr->getType(), e, shouldDelay);
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
  qual_type temp_type =
    makeDefaultType(tmpExpr->getExprLoc(), tmpExpr->getType());
  _implicitThisStar = oldThisStar;
  return guard.setAssignResult(exp_node_Temporary(tmp,temp_type,temp,false),
                               tmpExpr);
}

exp_node
FramacVisitor::makeBindTemporaryExpression(
    const clang::CXXBindTemporaryExpr* tmp, bool* shouldDelay,
    /* statement */ list* receiver, bool hasImplicitThisStar,
    FramaCIRGenAction::ExpressionGuard& guard) {
  expression oldThisStar = _implicitThisStar;
  location loc = makeLocation(tmp->getSourceRange());
  // location locCopy = copy_loc(loc);
  const char* tmp_name = NULL;
  expression etmp = NULL;
  if (hasImplicitThisStar) {
    etmp = guard.releaseExpr();
  } else {
    tmp_name = mk_tmp_name();
    qualified_name qtmp = qualified_name_cons(NULL,tmp_name);
    etmp =
      expression_cons(
        loc, exp_node_Variable(variable_Local(qtmp)));
  }
  _implicitThisStar = etmp;
  // expression addr = expression_cons(locCopy,
  //     exp_node_Address(expression_dup(etmp)));
  init_expr temp = makeInitExpr(tmp->getType(),tmp->getSubExpr(), shouldDelay);
  qual_type temp_type = makeDefaultType(tmp->getExprLoc(), tmp->getType());
  _implicitThisStar = oldThisStar;
  if (tmp_name)
    return guard.setAssignResult(
        exp_node_Temporary(tmp_name,temp_type,temp, false),tmp);
  else if (temp->tag_init_expr == SINGLE_INIT)
    return
      guard.setAssignResult(
        temp->cons_init_expr.Single_init.definition->econtent,tmp);
  else {
    tmp_name = mk_tmp_name();
    return guard.setAssignResult(
        exp_node_Temporary(tmp_name,temp_type,temp,false),tmp);
  }
}

exp_node FramacVisitor::makeUnaryOperator(
    const clang::UnaryOperator* unaryExpr, bool* shouldDelay,
    /* statement */ list* receiver, FramaCIRGenAction::ExpressionGuard& guard) {
  uokind unaryKind = NULL;
  // assign_kind assignment = AKRVALUE;
  switch (unaryExpr->getOpcode()) {
    case clang::UO_PostInc:
      unaryKind = uokind_UOPostInc(); /* assignment = AKASSIGN; */
      break;
    case clang::UO_PostDec:
      unaryKind = uokind_UOPostDec(); /* assignment = AKASSIGN; */
      break;
    case clang::UO_PreInc:
      unaryKind = uokind_UOPreInc(); /* assignment = AKASSIGN; */
      break;
    case clang::UO_PreDec:
      unaryKind = uokind_UOPreDec(); /* assignment = AKASSIGN; */
      break;
    case clang::UO_AddrOf:
      { expression esubexpr = 
          makeLocExpression(unaryExpr->getSubExpr(),shouldDelay,receiver);
        return guard.setAssignResult(exp_node_Address(esubexpr), unaryExpr);
      };
    case clang::UO_Deref:
      { exp_node subexpr = makeExpression(unaryExpr->getSubExpr(),
                                          shouldDelay,receiver);
        expression esubexpr = expression_cons(makeLocation(
              unaryExpr->getSubExpr()->getSourceRange()), subexpr);
        return guard.setAssignResult( exp_node_Dereference(esubexpr),unaryExpr);
      };
    case clang::UO_Plus:
      return guard.setAssignResult(makeExpression(unaryExpr->getSubExpr(),
          shouldDelay,receiver), unaryExpr);
    case clang::UO_Minus:
      unaryKind = uokind_UOOpposite(); /* assignment = AKRVALUE; */
      break;
    case clang::UO_Not:
      unaryKind = uokind_UOBitNegate(); /* assignment = AKRVALUE; */
      break;
    case clang::UO_LNot:
      unaryKind = uokind_UOLogicalNegate(); /* assignment = AKRVALUE; */
      break;
    case clang::UO_Extension:
      return guard.setAssignResult(makeExpression(unaryExpr->getSubExpr(),
        shouldDelay, receiver), unaryExpr);
    default:
      std::cerr << "Unsupported unary expressions:";
2434
2435
2436
#if CLANG_VERSION_MAJOR >= 11
      unaryExpr->dump(llvm::errs(), *_context);
#else
2437
      unaryExpr->dump(llvm::errs(), _context->getSourceManager