Пример #1
0
bool  ClangToSageTranslator::VisitEnumConstantDecl(clang::EnumConstantDecl * enum_constant_decl, SgNode ** node) {
#if DEBUG_VISIT_DECL
    std::cerr << "ClangToSageTranslator::VisitEnumConstantDecl" << std::endl;
#endif
    bool res = true;

    SgName name(enum_constant_decl->getNameAsString());

    SgType * type = buildTypeFromQualifiedType(enum_constant_decl->getType());

    SgInitializer * init = NULL;

    if (enum_constant_decl->getInitExpr() != NULL) {
        SgNode * tmp_expr = Traverse(enum_constant_decl->getInitExpr());
        SgExpression * expr = isSgExpression(tmp_expr);
        if (tmp_expr != NULL && expr == NULL) {
            std::cerr << "Runtime error: tmp_expr != NULL && expr == NULL" << std::endl;
            res = false;
        }
        else {
            init = SageBuilder::buildAssignInitializer_nfi(expr, expr->get_type());
        }
    }

    SgInitializedName * init_name = SageBuilder::buildInitializedName(name, type, init);

    SgEnumFieldSymbol * symbol = new SgEnumFieldSymbol(init_name);

    SageBuilder::topScopeStack()->insert_symbol(name, symbol);

    *node = init_name;

    return VisitValueDecl(enum_constant_decl, node) && res;
}
Пример #2
0
    bool findCallsWithFuncArgs2(SgNode *node, string &str) {		
	SgExprStatement *statement;
	if (statement = isSgExprStatement(node)) {
	    SgFunctionCallExp *call_exp;	
            if (call_exp = isSgFunctionCallExp(statement->get_the_expr())) {
                m_nodes.clear(); m_nodes.insert(call_exp);
                m_domain.expand(&m_nodes, QRQueryDomain::all_children);
                m_domain.getNodes()->erase(call_exp);
                NodeQuery::VariantVector vector (V_SgFunctionCallExp);
                QRQueryOpVariant op(vector);
                op.performQuery(&m_domain, &m_range);
                unsigned hits = m_range.countRange();
                if (hits) {
                    set<SgNode *> *rnodes = m_range.getNodes();
                    for (set<SgNode *>::iterator iter = rnodes->begin();
                         iter != rnodes->end(); )
                    {
                        SgFunctionCallExp *exp = (SgFunctionCallExp *) *iter; iter++;
                        SgExpression *funcexpr = exp->get_function();
                        str += funcexpr->unparseToString();
                        if (iter != rnodes->end()) {
                            str += ", ";
                        } 
                    }
                    return true;
                }
            }
	}
	
	return false;
    }
Пример #3
0
void
RemoveConstantFoldedValue::handleTheSynthesizedAttribute( SgNode* node, const RemoveConstantFoldedValueSynthesizedAttribute & i )
   {
     SgExpression* value = isSgExpression(i.node);
     if (value != NULL)
        {
          SgExpression* originalExpressionTree = value->get_originalExpressionTree();
          if (originalExpressionTree != NULL)
             {
#if 0
               printf ("Found an originalExpressionTree = %p = %s \n",originalExpressionTree,originalExpressionTree->class_name().c_str());
#endif
               if (node == value->get_parent())
                  {
                 // What kind of IR node are we at presently? Replace the expression representing the SgValueExp with the Expression representing the original subtree.
#if 0
                    printf ("Current IR node with SgExpression child = %p = %s originalExpressionTree = %p = %s \n",node,node->class_name().c_str(),originalExpressionTree,originalExpressionTree->class_name().c_str());
#endif
                    bool traceReplacement = true;
                    ConstantFoldedValueReplacer r(traceReplacement, value);
                    node->processDataMemberReferenceToPointers(&r);
                  }
                 else
                  {
                    printf ("*** Strange case of child attribute not having the current node as a parent child = %p = %s originalExpressionTree = %p = %s \n",node,node->class_name().c_str(),originalExpressionTree,originalExpressionTree->class_name().c_str());
                  }
             }
        }
   }
Пример #4
0
bool ClangToSageTranslator::VisitParmVarDecl(clang::ParmVarDecl * param_var_decl, SgNode ** node) {
#if DEBUG_VISIT_DECL
    std::cerr << "ClangToSageTranslator::VisitParmVarDecl" << std::endl;
#endif
    bool res = true;

    SgName name(param_var_decl->getNameAsString());

    SgType * type = buildTypeFromQualifiedType(param_var_decl->getOriginalType());

    SgInitializer * init = NULL;

    if (param_var_decl->hasDefaultArg()) {
        SgNode * tmp_expr = Traverse(param_var_decl->getDefaultArg());
        SgExpression * expr = isSgExpression(tmp_expr);
        if (tmp_expr != NULL && expr == NULL) {
            std::cerr << "Runtime error: tmp_expr != NULL && expr == NULL" << std::endl;
            res = false;
        }
        else {
            applySourceRange(expr, param_var_decl->getDefaultArgRange());
            init = SageBuilder::buildAssignInitializer_nfi(expr, expr->get_type());
            applySourceRange(init, param_var_decl->getDefaultArgRange());
        }
    }

    *node = SageBuilder::buildInitializedName(name, type, init);

    return VisitDeclaratorDecl(param_var_decl, node) && res;
}
Пример #5
0
void
DetectOriginalExpressionTreeTraversal::visit ( SgNode* node )
   {
  // This is used to operate on the AST and on subtree that are hidden in SgArrayType and bitfile expressions.

     ROSE_ASSERT(node != NULL);

  // printf ("In DetectOriginalExpressionTreeTraversal::visit(): node = %s \n",node->class_name().c_str());

     SgExpression* exp = isSgExpression(node);
     if (exp != NULL)
        {
          SgExpression* originalExpressionTree = exp->get_originalExpressionTree();

          if (originalExpressionTree != NULL)
             {
               printf ("Error: DetectOriginalExpressionTreeTraversal::visit() -- there is a valid originalExpressionTree = %p = %s on node = %p = %s \n",originalExpressionTree,originalExpressionTree->class_name().c_str(),exp,exp->class_name().c_str());
               ROSE_ASSERT(originalExpressionTree->get_startOfConstruct() != NULL);
               originalExpressionTree->get_startOfConstruct()->display("Error: DetectOriginalExpressionTreeTraversal::visit()");
             }

       // DQ (6/12/2013): Commented out as part of EDG 4.7 testing.
#if 0
          ROSE_ASSERT(originalExpressionTree == NULL);
#endif
        }
   }
void replaceExps(SgExpression* exp, SgVariableDeclaration* vardecl) {
	 if (isSgVarRefExp(exp)) {
                return;
        }
        else if (isSgUnaryOp(exp)) {
                if (isSgMinusMinusOp(exp) || isSgPlusPlusOp(exp)) {
                        SgExpression* operand = (isSgUnaryOp(exp))->get_operand();
			SgExpression* operand_cpy = SageInterface::copyExpression(operand);
			std::cout << "operand: " << operand->class_name() << std::endl;
			SageInterface::replaceExpression(exp,operand_cpy);
		}



                return;
        }
        else if (isSgBinaryOp(exp)) {
                replaceExps(isSgBinaryOp(exp)->get_lhs_operand(), vardecl);
                replaceExps(isSgBinaryOp(exp)->get_rhs_operand(), vardecl);
                return;
        }
        else {
                return;
        }
        return;
}
Пример #7
0
void
CompassAnalyses::NonAssociativeRelationalOperators::Traversal::
visit(SgNode* node)
   {
     SgBinaryOp *relOperator = isSgBinaryOp(node);

     if( relOperator != NULL && 
         isRelationalOperator(relOperator) )
     {
       SgExpression *lhs = relOperator->get_lhs_operand();
       SgExpression *rhs = relOperator->get_rhs_operand();

       if( lhs != NULL && rhs != NULL )
       {
         CompassAnalyses::NonAssociativeRelationalOperators::ExpressionTraversal expressionTraversal;

         if( expressionTraversal.run(lhs->get_parent()) > 1 ) 
         {
           output->addOutput( new CheckerOutput(relOperator) );
         } //if( expressionTraversal.run(lhs->get_parent()) > 1 ) 

       } //if( lhs != NULL && rhs != NULL )
     } //if( relOperator != NULL && isRelationalOperator(node) )

     return;
   } //End of the visit function.
Пример #8
0
SgExpression * RoseCloog::unparse_clast_expr_term( struct clast_term * t ) const
{
	SgExpression * temp;
	if (t->var) {
		SgExpression * exp;
		
		int group = t->var->type == clast_expr_red &&
		((struct clast_reduction*) t->var)->n > 1;
		
		exp = unparse_clast_expr(t->var);
		
		if (group)
			exp->set_need_paren(true);
		
		if (cloog_int_is_one(t->val))
	    	;
		else if (cloog_int_is_neg_one(t->val))
	    	exp = buildMinusOp(exp);
        else {
			exp = buildMultiplyOp(unparse_clast_integer(t->val), exp);
		}
		return exp;
    } else {
		return unparse_clast_integer(t->val);
    }
	
	return NULL;
}
Пример #9
0
void replaceCopiesOfExpression(SgExpression* src, SgExpression* tgt, 
                               SgNode* root) {
#ifdef FD_DEBUG
  cout << "replaceCopiesOfExpression: src = " << src->unparseToString() << ", tgt = " << tgt->unparseToString() << ", root = " << root->unparseToString() << endl;
#endif
  vector<SgExpression*> copies_of_src;
#ifdef FD_DEBUG
  cout << "---" << endl;
#endif
  FdFindCopiesVisitor(src, copies_of_src).traverse(root, preorder);
#ifdef FD_DEBUG
  cout << copies_of_src.size() << " copy(ies) found." << endl;
#endif
  for (unsigned int i = 0; i < copies_of_src.size(); ++i) {
    SgTreeCopy tc;
    SgExpression* copy = isSgExpression(tgt->copy(tc));
    SgExpression* parent = isSgExpression(copies_of_src[i]->get_parent());
    assert (parent);
    parent->replace_expression(copies_of_src[i], copy);
    copy->set_parent(parent);
  }
#ifdef FD_DEBUG
  cout << "result is " << root->unparseToString() << endl;
#endif
}
Пример #10
0
SgExpression* generateAssignmentMaybe(SgExpression* lhs, SgExpression* rhs)
{
    // If lhs is NULL, return rhs without doing an assignment
    // If lhs is not NULL, assign rhs to it
    // Used as a helper in inliner

#if 0
    if (lhs)
        return new SgAssignOp(SgNULL_FILE, lhs, rhs);
    else
        return rhs;
#else
    SgExpression* returnAssignmentOperator = NULL;
    if (lhs != NULL)
    {
        returnAssignmentOperator = new SgAssignOp(SgNULL_FILE, lhs, rhs);
        returnAssignmentOperator->set_endOfConstruct(SgNULL_FILE);
        printf ("Built a SgAssignOp = %p \n",returnAssignmentOperator);
    }
    else
        returnAssignmentOperator = rhs;

    return returnAssignmentOperator;
#endif
}
Пример #11
0
Файл: f2cArray.C Проект: 8l/rose
void Fortran_to_C::linearizeArrayDeclaration(SgArrayType* originalArrayType)
{
  // Get dim_info
  SgExprListExp* dimInfo = originalArrayType->get_dim_info();
  // Get dim list
  SgExpressionPtrList dimExpressionPtrList = dimInfo->get_expressions();

  SgExpression* newDimExpr; 
  Rose_STL_Container<SgExpression*>::iterator j =  dimExpressionPtrList.begin();
  while(j != dimExpressionPtrList.end())
  {
    SgExpression* indexExpression = getFortranDimensionSize(*j);

    /*
      Total array size is equal to the multiplication of all individual dimension size.
    */
    if(j != dimExpressionPtrList.begin()){
        newDimExpr = buildMultiplyOp(newDimExpr, indexExpression);
    }
    else
    /*
      If it's first dimension, array size is just its first dimension size.
    */
    {
      newDimExpr = indexExpression;
    }
    ++j;
  }
  // calling set_index won't replace the default index expression.  I have to delete the default manually.
  removeList.push_back(originalArrayType->get_index());
  originalArrayType->set_index(newDimExpr);
  newDimExpr->set_parent(originalArrayType);
  originalArrayType->set_rank(1); 
}
Пример #12
0
SgExpression* doFdVariableUpdate(
    RewriteRule* rules,
    SgExpression* cache,
    SgExpression* old_val /* Cannot be referenced in output tree w/o copying */,
    SgExpression* new_val)
   {
#ifdef FD_DEBUG
  cout << "Trying to convert from " << old_val->unparseToString() << " to " << new_val->unparseToString() << ", using cache " << cache->unparseToString() << endl;
#endif
     SgTreeCopy tc;
     SgExpression* old_valCopy = isSgExpression(old_val->copy(tc));
     ROSE_ASSERT (old_valCopy);
     SgCommaOpExp* innerComma = new SgCommaOpExp(SgNULL_FILE, old_valCopy, new_val);
     old_valCopy->set_parent(innerComma);
     new_val->set_parent(innerComma);
     SgExpression* expr = new SgCommaOpExp(SgNULL_FILE,cache,innerComma);
     cache->set_parent(expr);
     innerComma->set_parent(expr);
     // This is done so rewrite's expression replacement code will never find a
     // NULL parent for the expression being replaced
     SgExprStatement* dummyExprStatement =
       new SgExprStatement(SgNULL_FILE, expr);
     expr->set_parent(dummyExprStatement);
     SgNode* exprCopyForRewrite = expr;
     rewrite(rules, exprCopyForRewrite); // This might modify exprCopyForRewrite
     ROSE_ASSERT (isSgExpression(exprCopyForRewrite));
     expr = isSgExpression(exprCopyForRewrite);
     expr->set_parent(NULL);
     dummyExprStatement->set_expression(NULL);
     delete dummyExprStatement;
     SgExpression* expr2 = expr;
     ROSE_ASSERT (expr2);
     if (// The rewrite rules may have changed the form of expr to something other than a comma pair
        isSgCommaOpExp(expr2) &&
        isSgCommaOpExp(isSgCommaOpExp(expr2)->get_rhs_operand()))
        {
          SgExpression* cache2 = isSgCommaOpExp(expr2)->get_lhs_operand();
          SgCommaOpExp* rhs = isSgCommaOpExp(isSgCommaOpExp(expr2)->get_rhs_operand());
       // SgExpression* old_val2 = rhs->get_lhs_operand();
          SgExpression* new_val2 = rhs->get_rhs_operand();
       // return new SgAssignOp(SgNULL_FILE, cache2, new_val2);
          cache2->set_lvalue(true);
          SgAssignOp* assignmentOperator = new SgAssignOp(SgNULL_FILE, cache2, new_val2);
          cache2->set_parent(assignmentOperator);
          new_val2->set_parent(assignmentOperator);

#ifdef FD_DEBUG
          printf ("In doFdVariableUpdate(): assignmentOperator = %p \n",assignmentOperator);
#endif

          return assignmentOperator;
        }
       else
        {
          return expr2;
        }
   }
Пример #13
0
    virtual void visit(SgNode* n) {
        if (isSgBasicBlock(n)) {
            SgBasicBlock* bb = isSgBasicBlock(n);
            SgStatementPtrList& stmts = bb->get_statements();
            size_t initi;
            for (size_t decli = 0; decli < stmts.size(); ++decli) {
                if (isSgVariableDeclaration(stmts[decli])) {
                    SgVariableDeclaration* decl = isSgVariableDeclaration(stmts[decli]);
                    SgInitializedNamePtrList& vars = decl->get_variables();
                    for (size_t vari = 0; vari != vars.size(); ++vari) {
                        SgInitializedName* in = vars[vari];
                        if (in->get_initializer() == 0) {
                            bool used = false;
                            for (initi = decli + 1; initi < stmts.size();
                                    used |= containsVariableReference(stmts[initi], in),
                                    ++initi) {
                                SgExprStatement* initExprStmt = isSgExprStatement(stmts[initi]);
                                if (initExprStmt) {
                                    SgExpression* top = initExprStmt->get_expression();
                                    if (isSgAssignOp(top)) {
                                        SgVarRefExp* vr = isSgVarRefExp(isSgAssignOp(top)->get_lhs_operand());
                                        ROSE_ASSERT(isSgAssignOp(top) != NULL);
                                        SgExpression* newinit = isSgAssignOp(top)->get_rhs_operand();
                                        if (!used && vr && vr->get_symbol()->get_declaration() == in) {
                                            ROSE_ASSERT(newinit != NULL);
                                            // printf ("MoveDeclarationsToFirstUseVisitor::visit(): newinit = %p = %s \n",newinit,newinit->class_name().c_str());
                                            ROSE_ASSERT(newinit->get_type() != NULL);
                                            SgAssignInitializer* i = new SgAssignInitializer(SgNULL_FILE,newinit,newinit->get_type());
                                            i->set_endOfConstruct(SgNULL_FILE);
                                            // printf ("Built a SgAssignInitializer #1 \n");
                                            vars[vari]->set_initializer(i);
                                            stmts[initi] = decl;
                                            newinit->set_parent(i);

                                            // DQ (6/23/2006): Set the parent and file_info pointers
                                            // printf ("Setting parent of i = %p = %s to parent = %p = %s \n",i,i->class_name().c_str(),in,in->class_name().c_str());
                                            i->set_parent(in);
                                            ROSE_ASSERT(i->get_parent() != NULL);

                                            i->set_file_info(new Sg_File_Info(*(newinit->get_file_info())));
                                            ROSE_ASSERT(i->get_file_info() != NULL);

                                            // Assumes only one var per declaration FIXME
                                            ROSE_ASSERT (vars.size() == 1);
                                            stmts.erase(stmts.begin() + decli);
                                            --decli; // To counteract ++decli in loop header
                                            break; // To get out of initi loop
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
InheritedAttribute
BugSeeding::evaluateInheritedAttribute (
     SgNode* astNode,
     InheritedAttribute inheritedAttribute )
   {
  // Use this if we only want to seed bugs in loops
     bool isLoop = inheritedAttribute.isLoop           ||
                   (isSgForStatement(astNode) != NULL) ||
                   (isSgWhileStmt(astNode) != NULL)    ||
                   (isSgDoWhileStmt(astNode) != NULL);
  // Add Fortran support
     isLoop = isLoop || (isSgFortranDo(astNode) != NULL);

  // Mark future noes in this subtree as being part of a loop
     inheritedAttribute.isLoop = isLoop;

  // To test this on simple codes, optionally allow it to be applied everywhere
     bool applyEveryWhere = true;

     if (isLoop == true || applyEveryWhere == true)
        {
       // The inherited attribute is true iff we are inside a loop and this is a SgPntrArrRefExp.
          SgPntrArrRefExp *arrayReference = isSgPntrArrRefExp(astNode);
          if (arrayReference != NULL)
             {
            // Mark as a vulnerability
               inheritedAttribute.isVulnerability = true;

            // Now change the array index (to seed the buffer overflow bug)
               SgVarRefExp* arrayVarRef = isSgVarRefExp(arrayReference->get_lhs_operand());
               ROSE_ASSERT(arrayVarRef != NULL);
               ROSE_ASSERT(arrayVarRef->get_symbol() != NULL);
               SgInitializedName* arrayName = isSgInitializedName(arrayVarRef->get_symbol()->get_declaration());
               ROSE_ASSERT(arrayName != NULL);
               SgArrayType* arrayType = isSgArrayType(arrayName->get_type());
               ROSE_ASSERT(arrayType != NULL);
               SgExpression* arraySize = arrayType->get_index();

               SgTreeCopy copyHelp;
            // Make a copy of the expression used to hold the array size in the array declaration.
               SgExpression* arraySizeCopy = isSgExpression(arraySize->copy(copyHelp));
               ROSE_ASSERT(arraySizeCopy != NULL);

            // This is the existing index expression
               SgExpression* indexExpression = arrayReference->get_rhs_operand();
               ROSE_ASSERT(indexExpression != NULL);

            // Build a new expression: "array[n]" --> "array[n+arraySizeCopy]", where the arraySizeCopy is a size of "array"
               SgExpression* newIndexExpression = buildAddOp(indexExpression,arraySizeCopy);

            // Substitute the new expression for the old expression
               arrayReference->set_rhs_operand(newIndexExpression);
             }
        }

     return inheritedAttribute;
   }
Пример #15
0
// Propagate definitions of a variable to its uses.
// Assumptions: var is only assigned at the top level of body
//              nothing var depends on is assigned within body
// Very simple algorithm designed to only handle simplest cases
void simpleUndoFiniteDifferencingOne(SgBasicBlock* body, SgExpression* var)
   {
     SgExpression* value = 0;
     SgStatementPtrList& stmts = body->get_statements();
     vector<SgStatement*> stmts_to_remove;

     for (SgStatementPtrList::iterator i = stmts.begin(); i != stmts.end(); ++i)
        {
       // cout << "Next statement: value = " << (value ? value->unparseToString() : "(null)") << endl;
       // cout << (*i)->unparseToString() << endl;
          if (isSgExprStatement(*i) && isSgAssignOp(isSgExprStatement(*i)->get_expression()))
             {
               SgAssignOp* assignment = isSgAssignOp(isSgExprStatement(*i)->get_expression());
            // cout << "In assignment statement " << assignment->unparseToString() << endl;
               if (value)
                    replaceCopiesOfExpression(var, value, assignment->get_rhs_operand());
               if (isSgVarRefExp(assignment->get_lhs_operand()) && isSgVarRefExp(var))
                  {
                    SgVarRefExp* vr = isSgVarRefExp(assignment->get_lhs_operand());
                    if (vr->get_symbol()->get_declaration() == isSgVarRefExp(var)->get_symbol()->get_declaration())
                       {
                         value = assignment->get_rhs_operand();
                         stmts_to_remove.push_back(*i);
                       }
                  }
             }
            else
             {
               if (value)
                    replaceCopiesOfExpression(var, value, *i);
             }
        }

     for (vector<SgStatement*>::iterator i = stmts_to_remove.begin(); i != stmts_to_remove.end(); ++i) {
          stmts.erase(std::find(stmts.begin(), stmts.end(), *i));
     }

     if (value)
        {
       // DQ (12/17/2006): Separate out the construction of the SgAssignOp from the SgExprStatement to support debugging and testing.
       // stmts.push_back(new SgExprStatement(SgNULL_FILE, new SgAssignOp(SgNULL_FILE, var, value)));
          var->set_lvalue(true);
          SgAssignOp* assignmentOperator = new SgAssignOp(SgNULL_FILE, var, value);
          var->set_parent(assignmentOperator);
          value->set_parent(assignmentOperator);

          printf ("In simpleUndoFiniteDifferencingOne(): assignmentOperator = %p \n",assignmentOperator);

       // DQ: Note that the parent of the SgExprStatement will be set in AST post-processing (or it should be).
          SgExprStatement* es = new SgExprStatement(SgNULL_FILE, assignmentOperator);
          assignmentOperator->set_parent(es);
          stmts.push_back(es);
          es->set_parent(body);
        }
   }
Пример #16
0
/// \brief   replace old with repl, and delete subtree rooted in old.
/// \return  old's operand
static
SgExpression& extractOperand(SgUnaryOp& old)
{
  SgExpression* op = old.get_operand();
  SgExpression* emptydummy = SB::buildIntVal(0);

  SI::replaceExpression(op, emptydummy, keep_old_tree);

  op->set_parent(NULL);
  return *op;
}
bool isMethodCall(SgFunctionCallExp *functionCall, bool &isDotExp)
{
  ROSE_ASSERT(functionCall != NULL);

  SgExpression *expression = functionCall->get_function();
  ROSE_ASSERT(expression != NULL);

  bool isMethod = false;
  isDotExp = false;

  switch(expression->variantT()) {
  case V_SgDotExp:
    {
      isMethod = true;

      SgDotExp *dotExp = isSgDotExp(expression);
      ROSE_ASSERT(dotExp != NULL);
	  
      SgExpression *lhs = dotExp->get_lhs_operand();
      ROSE_ASSERT(lhs != NULL);
	  
      SgPointerDerefExp *pointerDerefExp =
	isSgPointerDerefExp(lhs);
	  
      if ( pointerDerefExp != NULL ) {
	;
      } else {
	isDotExp = true;
      }

      break;
    }
  case V_SgMemberFunctionRefExp:
  case V_SgArrowExp:
    {
      isMethod = true;
      break;
    }
  case V_SgFunctionRefExp:
  case V_SgPointerDerefExp:
    {
      isMethod = false;
      break;
    }
  default:
    {
      std::cerr << "Was not expecting an " << expression->sage_class_name() << std::endl;
      std::cerr << "in a function call." << std::endl;
      ROSE_ABORT();
    }
  }

  return isMethod;
}
int main(int argc, char** argv) {
	SgProject* proj = frontend(argc,argv);
	SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj);
	SgFunctionDefinition* mainDef = mainDecl->get_definition();
	std::vector<SgNode*> ifExps;
	ifExps = NodeQuery::querySubTree(mainDef, V_SgIfStmt);
	for (int i = 0; i < ifExps.size(); i++) {
		getIfConds(isSgIfStmt(ifExps[i]), isSgScopeStatement(mainDef));
	}
	
	std::vector<SgNode*> assignNodes = NodeQuery::querySubTree(mainDef, V_SgVariableDeclaration);
	std::cout << assignNodes.size() << " nodes found" << std::endl;
	std::vector<SgBinaryOp*> bin_ops;
	std::vector<SgUnaryOp*> un_ops;
	std::vector<SgNode*> other;
	std::vector<SgExpression*> results;
	for (std::vector<SgNode*>::iterator i = assignNodes.begin(); i != assignNodes.end(); i++) {
	
		SgVariableDeclaration* vdecl = isSgVariableDeclaration(*i);
		SgInitializedNamePtrList vlst = vdecl->get_variables();
		SgInitializedName* initName = isSgInitializedName((*(vlst.begin())));
		SgExpression* exp = isSgAssignInitializer(initName->get_initializer())->get_operand();
		std::cout << exp->class_name() << std::endl;
		if (!isSgFunctionCallExp(exp)) {
			getExps(exp, isSgInitializedName(*i), results, 0);
		
	
	std::cout << "prefixes" << std::endl;
	for (int j = 0; j < prefixes.size(); j++) {
	        SgExprStatement* expSt = SageBuilder::buildExprStatement_nfi(prefixes[j]);
		SageInterface::insertStatement(isSgVariableDeclaration(*i),expSt,true);
		
		std::cout << prefixes[j]->class_name() << std::endl;
	}
	std::cout << "results" << std::endl;
	for (int j = 0; j < results.size(); j++) {
		std::cout << results[j]->class_name() << std::endl;
	}
	std::cout << "postfixes" << std::endl;
	for (int j = 0; j < postfixes.size(); j++) {
		SgExprStatement* expSt = SageBuilder::buildExprStatement_nfi(postfixes[j]);
                SageInterface::insertStatement(isSgVariableDeclaration(*i),expSt,false);
		std::cout << postfixes[j]->class_name() << std::endl;
	}
	
	replaceExps(exp,vdecl);
	simplifyExps(exp);
	}
		
	}
			
	backend(proj);
	return 0;
}
 void virtual visit (SgNode* n)
 {
   SgExpression* exp = isSgExpression(n);
   if (exp != NULL)
   {
     AstAttribute* att = exp->getAttribute("UniqueNameAttribute"); 
     ROSE_ASSERT (att!= NULL);
     UniqueNameAttribute* u_att = dynamic_cast<UniqueNameAttribute* > (att);
     ROSE_ASSERT (u_att!= NULL);
     cout<<"Found expression of type "<< n->class_name()<< " : "<< u_att->get_name()<<endl;
   }
 }
Пример #20
0
 void Expr2MemLocTraversal::visit(SgPointerDerefExp* sgn)
 {
   scope regvis("Expr2MemLocTraversal::visit(SgPointerDerefExp* sgn)", scope::medium, ptaDebugLevel, 1);
   SgExpression* operand = sgn->get_operand();
   operand->accept(*this);
   boost::shared_ptr<AbstractObjectSet> new_p_aos = 
           boost::make_shared<AbstractObjectSet>(pedge, composer, analysis, AbstractObjectSet::may);
   for(AbstractObjectSet::const_iterator i=p_aos->begin(); i!=p_aos->end(); i++) {
     boost::shared_ptr<AbstractObjectSet> ao = boost::dynamic_pointer_cast<AbstractObjectSet>(aom->get(*i));
     assert(ao);
     new_p_aos->meetUpdate(ao.get());
   }
   p_aos = new_p_aos;
 }
Пример #21
0
     virtual void visit(SgNode* n)
        {
          SgReturnStmt* rs = isSgReturnStmt(n);
          if (rs)
             {
               // std::cout << "Converting return statement " << rs->unparseToString();
               // std::cout << " into possible assignment to " << where_to_write_answer->unparseToString();
               // std::cout << " and jump to " << label->get_name().getString() << std::endl;
               SgExpression* return_expr = rs->get_expression();
               SgBasicBlock* block = SageBuilder::buildBasicBlock();
            // printf ("Building IR node #1: new SgBasicBlock = %p \n",block);
               if (return_expr)
                  {
                    SgExpression* assignment = generateAssignmentMaybe(where_to_write_answer,return_expr);
                    if (where_to_write_answer)
                      where_to_write_answer->set_parent(assignment);
                    if (return_expr != assignment)
                      return_expr->set_parent(assignment);
                    SgStatement* assign_stmt = SageBuilder::buildExprStatement(assignment);
                    SageInterface::appendStatement(assign_stmt, block);
                  }

            // block->get_statements().push_back(new SgGotoStatement(SgNULL_FILE, label));
               SgGotoStatement* gotoStatement = new SgGotoStatement(SgNULL_FILE, label);
               gotoStatement->set_endOfConstruct(SgNULL_FILE);
               ROSE_ASSERT(n->get_parent() != NULL);
               SageInterface::appendStatement(gotoStatement, block);
               isSgStatement(n->get_parent())->replace_statement(rs, block);
               block->set_parent(n->get_parent());
               ROSE_ASSERT(gotoStatement->get_parent() != NULL);
             }
        }
Пример #22
0
void instrumentRead(SgVarRefExp *varRef) {
   SgExpression *parent = isSgExpression(varRef->get_parent());
   assert(parent != NULL);
   Sg_File_Info * file_info = Sg_File_Info::generateDefaultFileInfoForTransformationNode();

   SgCommaOpExp *commaOp = new SgCommaOpExp(file_info, beforeRead.getCallExp(), varRef,
                                                                           varRef->get_type());
   SgUnaryOp *uOp = isSgUnaryOp(parent);
   if (uOp != NULL) {
      uOp->set_operand(commaOp);
   }
   else {
      SgBinaryOp *bOp = isSgBinaryOp(parent);
      if (bOp != NULL) {
         if (bOp->get_lhs_operand() == varRef) {
            bOp->set_lhs_operand(commaOp);
         }
         else {
            assert(bOp->get_rhs_operand() == varRef);
            bOp->set_rhs_operand(commaOp);
         }
      }
      else {
         SgExprListExp *expList = isSgExprListExp(parent);
         if (expList != NULL) {
            SgExpressionPtrList& expressions = expList->get_expressions();
            for (SgExpressionPtrList::iterator iter = expressions.begin(); ; iter++) {
               assert (iter != expressions.end()); //element must be in the list!
               if (*iter == varRef) {
                  //insert commaOp instead of varRef
                  expressions.insert(expressions.erase(iter), commaOp);
                  break;
               }
            }
         }
         else {
            //SgClassNameRefExp
            //SgConditionalExp
            //SgDeleteExp
            //go on implementing other cases
            cerr<<"unexpected parent expression: "<<parent->class_name()<<endl;
            assert (false);
         }
      }
   }
}
Пример #23
0
void RtedTransformation::transformPtrDerefs(SharedPtrDerefContainer::value_type ptrderef)
{
    ROSE_ASSERT(ptrderef);

    SgExpression* operand = ptrderef->get_operand();
    ROSE_ASSERT ( isUpcSharedPointer(operand->get_type()) );

    SgStatement*   stmt = getSurroundingStatement(*ptrderef);
    SgExprListExp* lock_args   = SB::buildExprListExp();
    SgExprListExp* unlock_args = SB::buildExprListExp();

    SI::appendExpression(lock_args,   SI::deepCopy(operand));
    SI::appendExpression(unlock_args, SI::deepCopy(operand));

    insertCheck(ilBefore, stmt, symbols.roseUpcEnterSharedPtr, lock_args);
    insertCheck(ilAfter,  stmt, symbols.roseUpcExitSharedPtr,  unlock_args);
}
// Get the statement of an expression.  Somewhat smarter than the standard
// version of this routine, but needs to be merged.
SgStatement* getStatementOfExpression(SgNode* n)
   {
     assert(n);
  // std::cout << "Starting getStatementOfExpression on 0x" << std::hex << (int)n << ", which has type " << n->sage_class_name() << std::endl;

     SgExpression* expression = isSgExpression(n);
     ROSE_ASSERT(expression != NULL);
     SgExpression* rootExpression = getRootOfExpression(expression);
     ROSE_ASSERT(rootExpression->get_parent() != NULL);
     SgInitializedName* initializedName = isSgInitializedName(rootExpression->get_parent());

     SgNode* root = rootExpression;
     if (initializedName != NULL)
        root = initializedName;

     ROSE_ASSERT(root != NULL);
     SgStatement* statement = isSgStatement(root->get_parent());
     ROSE_ASSERT(statement != NULL);
     return statement;
   }
Пример #25
0
void
deleteOriginalExpressionTree(SgExpression* exp)
   {
  // This function deleted the existing original expression tree for an expression.

     SgExpression* originalExpressionTree = exp->get_originalExpressionTree();
     if (originalExpressionTree != NULL)
        {
#if 0
          printf ("Removing the original expression tree from keyExpression = %p = %s originalExpressionTree = %p = %s \n",
               exp,exp->class_name().c_str(),originalExpressionTree,originalExpressionTree->class_name().c_str());
#endif
       // Remove the original expression tree...
       // delete value->get_originalExpressionTree();
       // SageInterface::deleteAST(originalExpressionTree);
          SageInterface::deleteExpressionTreeWithOriginalExpressionSubtrees(originalExpressionTree);

       // Set the pointer to the original expression tree to NULL.
          exp->set_originalExpressionTree(NULL);
        }
   }
Пример #26
0
 virtual void visit(SgNode* n) {
     if (isSgVarRefExp(n)) {
         SgVarRefExp* vr = isSgVarRefExp(n);
         assert (vr->get_symbol());
         if (vr->get_symbol()->get_declaration() == initname) {
             if (inSimpleContext(vr) || !needSimpleContext) {
                 SgTreeCopy tc;
                 isSgExpression(n->get_parent())->replace_expression(
                     vr, isSgExpression(initexpr->copy(tc)));
             }
         }
     }
 }
/*
Given a node in the AST, it replaces all function calls with the corresponding expression from the fct2Var mapping.
Since we traverse in order of function evaluation, all nodes that are lower in the subtree are supposed to
have been mapped, since they have already appeared in the list. Also, we only replace the shallowest level of
function calls in the surrent subtree, since we assume that replaceFunctionCallsInExpression  has already been called
for each of the subtrees rooted at the shallowest function calls lower than the current node:

E.g.: f(g(h(i))) + 5
has the AST:
     +
    / \
  fc1  5
  / \
 f  fc2
    / \
   g  fc3 
      / \
     h   i
where fc? represents an SgFunctionCallExpression. Order of function evaluation is h(i), g(_), f(_).

Calling 'replaceFunctionCallsInExpression' on '+' will generate
                     temp_var + 5
but calling the same function on 'fc2' will generate
                     f(temp_var) + 5
*/
void
FunctionCallNormalization::replaceFunctionCallsInExpression( SgNode *root,
                                                             map<SgFunctionCallExp *, SgExpression *> fct2Var )
   {
     if ( !root )
       return;

     if ( NodeQuery::querySubTree( root, V_SgFunctionCallExp ).size() > 0 )
       {
         list<SgNode *> toVisit;
         toVisit.push_back( root );

         while ( !toVisit.empty() )
           {
             SgNode *crt = toVisit.front();

             // will visit every node above an function call exp, but not below
             // also, we will replace function call expressions found
             if ( !isSgFunctionCallExp( crt ) )
               {
                 vector<SgNode *> succ = ( crt )->get_traversalSuccessorContainer();
                 for ( vector<SgNode *>::iterator succIt = succ.begin(); succIt != succ.end(); succIt++ )
                   if ( isSgNode ( *succIt ) )
                     toVisit.push_back( *succIt );
               }
             else
               {
                 SgFunctionCallExp *call = isSgFunctionCallExp( crt );
                 ROSE_ASSERT ( call );
                 
                 map<SgFunctionCallExp *, SgExpression *>::iterator mapIter;
                 mapIter = fct2Var.find( call );
                 if ( mapIter == fct2Var.end() )
                   cout << "NOT FOUND " << call->unparseToString() << "\t" << call << "\n";

                 // a mapping for function call exps in the subtree must already exist ( postorder traversal )
                 ROSE_ASSERT ( mapIter != fct2Var.end() && mapIter->second );

                 // duplicate the variable
                 SgTreeCopy treeCopy;
                 SgExpression *scnd = mapIter->second;
                 ROSE_ASSERT ( isSgExpression( scnd ) );
                 SgExpression *newVar = isSgExpression( scnd->copy( treeCopy ) );
                 ROSE_ASSERT ( newVar );

                 SgExpression *parent = isSgExpression( call->get_parent() );
                 ROSE_ASSERT ( parent );

                 // replace the node in the AST
                 newVar->set_parent( parent );
                 int k = parent->replace_expression( call, newVar );
                 ROSE_ASSERT ( k == 1 );
                 delete call;
               }
             toVisit.pop_front();
           }
       }
   }
Пример #28
0
Файл: f2cArray.C Проект: 8l/rose
void Fortran_to_C::translateArrayDeclaration(SgArrayType* originalArrayType)
{
  // Get dim_info
  SgExprListExp* dimInfo = originalArrayType->get_dim_info();
  // Get dim list
  SgExpressionPtrList dimExpressionPtrList = dimInfo->get_expressions();
  // Get array base_type
  SgType* baseType = originalArrayType->get_base_type();

  Rose_STL_Container<SgExpression*>::iterator j =  dimExpressionPtrList.begin();
  SgExpression* indexExpression = getFortranDimensionSize(*j);
  //std::cout << "array rank:" << originalArrayType->get_rank() << std::endl;
  if(originalArrayType->get_rank() == 1)
  {
    originalArrayType->set_base_type(baseType);
    originalArrayType->set_index(indexExpression);
    indexExpression->set_parent(originalArrayType);
    constantFolding(indexExpression);
  }
  else
  {
    SgArrayType* newType = buildArrayType(baseType,indexExpression);
    baseType->set_parent(newType);
    j = j + 1;
    for(; j< (dimExpressionPtrList.end()-1); ++j)
    {
      indexExpression = getFortranDimensionSize(*j);
      baseType = newType;
      newType = buildArrayType(baseType,indexExpression);
      baseType->set_parent(newType);
    }
    j = dimExpressionPtrList.end()-1;
    indexExpression = getFortranDimensionSize(*j);
    originalArrayType->set_base_type(newType);
    originalArrayType->set_index(indexExpression);
    indexExpression->set_parent(originalArrayType);
  }
}
Пример #29
0
bool ClangToSageTranslator::VisitFieldDecl(clang::FieldDecl * field_decl, SgNode ** node) {
#if DEBUG_VISIT_DECL
    std::cerr << "ClangToSageTranslator::VisitFieldDecl" << std::endl;
#endif  
    bool res = true;
    
    SgName name(field_decl->getNameAsString());

    SgType * type = buildTypeFromQualifiedType(field_decl->getType());

    clang::Expr * init_expr = field_decl->getInClassInitializer();
    SgNode * tmp_init = Traverse(init_expr);
    SgExpression * expr = isSgExpression(tmp_init);
    // TODO expression list if aggregated initializer !
    if (tmp_init != NULL && expr == NULL) {
        std::cerr << "Runtime error: not a SgInitializer..." << std::endl;
        res = false;
    }
    SgInitializer * init = expr != NULL ? SageBuilder::buildAssignInitializer_nfi(expr, expr->get_type()) : NULL;
    if (init != NULL)
        applySourceRange(init, init_expr->getSourceRange());

  // Cannot use 'SageBuilder::buildVariableDeclaration' because of anonymous field
    // *node = SageBuilder::buildVariableDeclaration(name, type, init, SageBuilder::topScopeStack());
  // Build it by hand...
    SgVariableDeclaration * var_decl = new SgVariableDeclaration(name, type, init);

    if (isSgClassType(type)) {
        std::map<SgClassType *, bool>::iterator bool_it = p_class_type_decl_first_see_in_type.find(isSgClassType(type));
        ROSE_ASSERT(bool_it != p_class_type_decl_first_see_in_type.end());
        if (bool_it->second) {
            var_decl->set_baseTypeDefiningDeclaration(isSgNamedType(type)->get_declaration()->get_definingDeclaration());
            var_decl->set_variableDeclarationContainsBaseTypeDefiningDeclaration(true);
        }
    }
    else if (isSgEnumType(type)) {
        std::map<SgEnumType *, bool>::iterator bool_it = p_enum_type_decl_first_see_in_type.find(isSgEnumType(type));
        ROSE_ASSERT(bool_it != p_enum_type_decl_first_see_in_type.end());
        if (bool_it->second) {
            var_decl->set_baseTypeDefiningDeclaration(isSgEnumType(type)->get_declaration()->get_definingDeclaration());
            var_decl->set_variableDeclarationContainsBaseTypeDefiningDeclaration(true);
        }
    }

    var_decl->set_firstNondefiningDeclaration(var_decl);
    var_decl->set_parent(SageBuilder::topScopeStack());

    ROSE_ASSERT(var_decl->get_variables().size() == 1);

    SgInitializedName * init_name = var_decl->get_variables()[0];
    ROSE_ASSERT(init_name != NULL);
    init_name->set_scope(SageBuilder::topScopeStack());

    applySourceRange(init_name, field_decl->getSourceRange());

    SgVariableDefinition * var_def = isSgVariableDefinition(init_name->get_declptr());
    ROSE_ASSERT(var_def != NULL);
    applySourceRange(var_def, field_decl->getSourceRange());

    SgVariableSymbol * var_symbol = new SgVariableSymbol(init_name);
    SageBuilder::topScopeStack()->insert_symbol(name, var_symbol);

    *node = var_decl;

    return VisitDeclaratorDecl(field_decl, node) && res; 
}
Пример #30
0
bool ClangToSageTranslator::VisitVarDecl(clang::VarDecl * var_decl, SgNode ** node) {
#if DEBUG_VISIT_DECL
    std::cerr << "ClangToSageTranslator::VisitVarDecl" << std::endl;
#endif
    bool res = true;

  // Create the SAGE node: SgVariableDeclaration

    SgName name(var_decl->getNameAsString());

    SgType * type = buildTypeFromQualifiedType(var_decl->getType());

    clang::Expr * init_expr = var_decl->getInit();
    SgNode * tmp_init = Traverse(init_expr);
    SgExpression * expr = isSgExpression(tmp_init);
    if (tmp_init != NULL && expr == NULL) {
        std::cerr << "Runtime error: not a SgInitializer..." << std::endl; // TODO
        res = false;
    }
    SgExprListExp * expr_list_expr = isSgExprListExp(expr);

    SgInitializer * init = NULL;
    if (expr_list_expr != NULL)
        init = SageBuilder::buildAggregateInitializer(expr_list_expr, type);
    else if (expr != NULL)
        init = SageBuilder::buildAssignInitializer_nfi(expr, expr->get_type());
    if (init != NULL)
        applySourceRange(init, init_expr->getSourceRange());

    SgVariableDeclaration * sg_var_decl = new SgVariableDeclaration(name, type, init); // scope: obtain from the scope stack.

    if (isSgClassType(type)) {
        std::map<SgClassType *, bool>::iterator bool_it = p_class_type_decl_first_see_in_type.find(isSgClassType(type));
        ROSE_ASSERT(bool_it != p_class_type_decl_first_see_in_type.end());
        if (bool_it->second) {
            sg_var_decl->set_baseTypeDefiningDeclaration(isSgNamedType(type)->get_declaration()->get_definingDeclaration());
            sg_var_decl->set_variableDeclarationContainsBaseTypeDefiningDeclaration(true);
        }
    }
    else if (isSgEnumType(type)) {
        std::map<SgEnumType *, bool>::iterator bool_it = p_enum_type_decl_first_see_in_type.find(isSgEnumType(type));
        ROSE_ASSERT(bool_it != p_enum_type_decl_first_see_in_type.end());
        if (bool_it->second) {
            sg_var_decl->set_baseTypeDefiningDeclaration(isSgEnumType(type)->get_declaration()->get_definingDeclaration());
            sg_var_decl->set_variableDeclarationContainsBaseTypeDefiningDeclaration(true);
        }
    }

    sg_var_decl->set_firstNondefiningDeclaration(sg_var_decl);
    sg_var_decl->set_parent(SageBuilder::topScopeStack());

    ROSE_ASSERT(sg_var_decl->get_variables().size() == 1);

    SgInitializedName * init_name = sg_var_decl->get_variables()[0];
    ROSE_ASSERT(init_name != NULL);
    init_name->set_scope(SageBuilder::topScopeStack());

    applySourceRange(init_name, var_decl->getSourceRange());

    SgVariableDefinition * var_def = isSgVariableDefinition(init_name->get_declptr());
    ROSE_ASSERT(var_def != NULL);
    applySourceRange(var_def, var_decl->getSourceRange());

    SgVariableSymbol * var_symbol = new SgVariableSymbol(init_name);
    SageBuilder::topScopeStack()->insert_symbol(name, var_symbol);

    *node = sg_var_decl;

    return VisitDeclaratorDecl(var_decl, node) && res;
}