Exemple #1
0
void CFG::buildFullCFG()
{
    // Before building a new CFG, make sure to clear all nodes built before.
    all_nodes_.clear();
    clearNodesAndEdges();

    std::set<VirtualCFG::CFGNode> explored;

    graph_ = new SgIncidenceDirectedGraph;

    if (SgProject* project = isSgProject(start_))
    {
        Rose_STL_Container<SgNode*> functions = NodeQuery::querySubTree(project, V_SgFunctionDefinition);
        for (Rose_STL_Container<SgNode*>::const_iterator i = functions.begin(); i != functions.end(); ++i)
        {
            SgFunctionDefinition* proc = isSgFunctionDefinition(*i);
            if (proc)
            {
                buildCFG<VirtualCFG::CFGNode, VirtualCFG::CFGEdge>
                    (proc->cfgForBeginning(), all_nodes_, explored);
            }
        }
    }
    else
        buildCFG<VirtualCFG::CFGNode, VirtualCFG::CFGEdge>
            (start_->cfgForBeginning(), all_nodes_, explored);
}
// normalize all loops within candidate function definitions
void normalizeLoops (std::vector<SgFunctionDefinition* > candidateFuncDefs)
{
  for (std::vector<SgFunctionDefinition* >::iterator iter = candidateFuncDefs.begin(); iter != candidateFuncDefs.end(); iter++)
  {
    SgFunctionDefinition* funcDef = *iter; 
    ROSE_ASSERT (funcDef);
    // This has to happen before analyses are called.
    // For each loop 
    VariantVector vv (V_SgForStatement); 
    Rose_STL_Container<SgNode*> loops = NodeQuery::querySubTree(funcDef, vv); 

    if (enable_debug)
      cout<<"Normalize loops queried from memory pool ...."<<endl;

    // normalize C99 style for (int i= x, ...) to C89 style: int i;  (i=x, ...)
    // Liao, 10/22/2009. Thank Jeff Keasler for spotting this bug
    for (Rose_STL_Container<SgNode*>::iterator iter = loops.begin();
        iter!= loops.end(); iter++ )
    {
      SgForStatement* cur_loop = isSgForStatement(*iter);
      ROSE_ASSERT(cur_loop);

      if (enable_debug)
        cout<<"\t loop at:"<< cur_loop->get_file_info()->get_line() <<endl;
      // skip for (;;) , SgForStatement::get_test_expr() has a buggy assertion.
      SgStatement* test_stmt = cur_loop->get_test();
      if (test_stmt!=NULL && 
          isSgNullStatement(test_stmt))
      {
        if (enable_debug)
          cout<<"\t skipped due to empty loop header like for (;;)"<<endl;
        continue;
      }

      // skip system header
      if (insideSystemHeader (cur_loop) )
      {
        if (enable_debug)
          cout<<"\t skipped since the loop is inside a system header "<<endl;
        continue; 
      }
#if 0 // we now always normalize loops, then later undo some normalization 6/22/2016
      // SageInterface::normalizeForLoopInitDeclaration(cur_loop);
      if (keep_c99_loop_init) 
      {
        // 2/29/2016, disable for loop init declaration normalization
        // This is not used . No longer used.
        normalizeForLoopTest(cur_loop);
        normalizeForLoopIncrement(cur_loop);
        ensureBasicBlockAsBodyOfFor(cur_loop);
        constantFolding(cur_loop->get_test());
        constantFolding(cur_loop->get_increment());
      }
      else
#endif
        SageInterface::forLoopNormalization(cur_loop);
    } // end for all loops
  } // end for all function defs 
  
}
Exemple #3
0
int main(int argc, char *argv[]) 
{
  // Build the AST used by ROSE
  SgProject* sageProject = frontend(argc,argv);

  // Process all function definition bodies for static control flow graph generation
  Rose_STL_Container<SgNode*> functions = NodeQuery::querySubTree(sageProject, V_SgFunctionDefinition);
  for (Rose_STL_Container<SgNode*>::const_iterator i = functions.begin(); i != functions.end(); ++i) 
  {
    SgFunctionDefinition* proc = isSgFunctionDefinition(*i);
    ROSE_ASSERT (proc != NULL); 
    string fileName= StringUtility::stripPathFromFileName(proc->get_file_info()->get_filenameString());
    string dotFileName1=fileName+"."+ proc->get_declaration()->get_name() +".debug.dot";
    string dotFileName2=fileName+"."+ proc->get_declaration()->get_name() +".interesting.dot";

    StaticCFG::CFG cfg(proc);

    // Dump out the full CFG, including bookkeeping nodes
    cfg.buildFullCFG();
    cfg.cfgToDot(proc, dotFileName1);

    // Dump out only those nodes which are "interesting" for analyses
    cfg.buildFilteredCFG();
    cfg.cfgToDot(proc, dotFileName2);
  }

  return 0;
}
Exemple #4
0
void
CompassAnalyses::SizeOfPointer::Traversal::
visit(SgNode* node)
   { 
     int starCount;
     SgSizeOfOp *szOf = isSgSizeOfOp(node);
     if(!szOf) return;
     Rose_STL_Container<SgNode*> pointers = NodeQuery::querySubTree(node,V_SgPointerType);
     Rose_STL_Container<SgNode*> deRefs = NodeQuery::querySubTree(node,V_SgPointerDerefExp);
     Rose_STL_Container<SgNode*> varRefs = NodeQuery::querySubTree(node,V_SgVarRefExp);
     for (Rose_STL_Container<SgNode *>::iterator i = varRefs.begin(); i != varRefs.end(); i++)
       {
         SgVarRefExp *vRef = isSgVarRefExp((*i));
         if (!vRef) return;
         SgType *t = vRef->get_type();
         std::string typeName = t->unparseToString();
         //std::cout << countStars(typeName) <<   std::endl;
         starCount = countStars(typeName);
         if (!starCount or
             (starCount == pointers.size() and 
              deRefs.size() == (starCount - 1)))
           {
             //std::cout << "IT'S OK!" << std::endl;
             return;
           }
         
         
       }
     output->addOutput(new CheckerOutput(node));
} //End of the visit function.
Exemple #5
0
void CFG::buildFilteredCFG()
{
    all_nodes_.clear();
    clearNodesAndEdges();

    std::set<VirtualCFG::InterestingNode> explored;
    std::map<VirtualCFG::InterestingNode, SgGraphNode*> all_nodes;

    graph_ = new SgIncidenceDirectedGraph;

    if (SgProject* project = isSgProject(start_))
    {
        Rose_STL_Container<SgNode*> functions = NodeQuery::querySubTree(project, V_SgFunctionDefinition);
        for (Rose_STL_Container<SgNode*>::const_iterator i = functions.begin(); i != functions.end(); ++i)
        {
            SgFunctionDefinition* proc = isSgFunctionDefinition(*i);
            if (proc)
            {
                buildCFG<VirtualCFG::InterestingNode, VirtualCFG::InterestingEdge>
                    (VirtualCFG::makeInterestingCfg(proc), all_nodes, explored);
            }
        }
    }
    else
        buildCFG<VirtualCFG::InterestingNode, VirtualCFG::InterestingEdge>
            (VirtualCFG::makeInterestingCfg(start_), all_nodes, explored);

    typedef std::pair<VirtualCFG::InterestingNode, SgGraphNode*> pair_t;
    foreach (const pair_t& p, all_nodes)
        all_nodes_[VirtualCFG::CFGNode(p.first.getNode(), 0)] = p.second;
}
int
main ( int argc, char* argv[] )
   {
     ROSE_INITIALIZE;

     if (SgProject::get_verbose() > 0)
          printf ("In preprocessor.C: main() \n");

     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT (project != NULL);

     Rose_STL_Container<SgNode*> nodeList;
     nodeList = NodeQuery::querySubTree (project,V_SgForStatement);
     printf ("\nnodeList.size() = %zu \n",nodeList.size());

     Rose_STL_Container<SgNode*>::iterator i = nodeList.begin();
     while (i != nodeList.end())
        {
          Sg_File_Info & fileInfo = *((*i)->get_file_info());
          printf ("Query node = %p = %s in %s \n ----- at line %d on column %d \n",
              *i,(*i)->sage_class_name(),fileInfo.get_filename(),
               fileInfo.get_line(), fileInfo.get_col());
          i++;
        }

     if (project->get_verbose() > 0)
          printf ("Calling the backend() \n");

     return 0;
   }
Exemple #7
0
 // obtain read or write variables processed by all nested loops, if any
 void getVariablesProcessedByInnerLoops (SgScopeStatement* current_loop_body, bool isRead, std::set<SgInitializedName*>& var_set)
 {
   // AST query to find all loops
   // add all read/write variables into the var_set
   VariantVector vv;
   vv.push_back(V_SgForStatement);  
   vv.push_back(V_SgFortranDo);  
   Rose_STL_Container<SgNode*> nodeList = NodeQuery::querySubTree(current_loop_body, vv); 
   for (Rose_STL_Container<SgNode *>::iterator i = nodeList.begin(); i != nodeList.end(); i++)
   {
     SgStatement* loop = isSgStatement(*i);
     if (debug)
       cout<< "Found nested loop at line:"<< loop->get_file_info()->get_line()<<endl;
     std::set<SgInitializedName*> src_var_set ;
     if (isRead)
       src_var_set = LoopLoadVariables[loop];
     else
       src_var_set = LoopStoreVariables[loop];
     std::set<SgInitializedName*>::iterator j; 
     if (debug)
       cout<< "\t Insert processed variable:"<<endl;
     for (j= src_var_set.begin(); j!= src_var_set.end(); j++)
     {
        var_set.insert(*j);
       if (debug)
         cout<< "\t \t "<<(*j)->get_name()<<endl;
     }
   }
 }
/******************************************
 * Traversal over all functions
 * this needs to be improved... for correctness, the traversal must 
 * be according to controlflow (otherwise global variables are incorrect)
 *****************************************/
bool  DefUseAnalysis::start_traversal_of_functions() {
  if (DEBUG_MODE) 
    cout << "START: Traversal over Functions" << endl;

  nrOfNodesVisited = 0;
  dfaFunctions.clear();

  // Traverse through each FunctionDefinition and check for DefUse
  Rose_STL_Container<SgNode*> functions = NodeQuery::querySubTree(project, V_SgFunctionDefinition); 
  DefUseAnalysisPF* defuse_perfunc = new DefUseAnalysisPF(DEBUG_MODE, this);
  bool abortme=false;
  for (Rose_STL_Container<SgNode*>::const_iterator i = functions.begin(); i != functions.end(); ++i) {
    SgFunctionDefinition* proc = isSgFunctionDefinition(*i);
    if (DEBUG_MODE) 
      cout << "\t function Def@"<< proc->get_file_info()->get_filename() <<":" << proc->get_file_info()->get_line() << endl;
    FilteredCFGNode <IsDFAFilter> rem_source = defuse_perfunc->run(proc,abortme);
    nrOfNodesVisited += defuse_perfunc->getNumberOfNodesVisited();
    //cout << nrOfNodesVisited << " ......... function " << proc->get_declaration()->get_name().str() << endl; 
    if (rem_source.getNode()!=NULL)
      dfaFunctions.push_back(rem_source);
  }
  delete defuse_perfunc;

  if (DEBUG_MODE) {
    dfaToDOT();
  }

  if (DEBUG_MODE) 
    cout << "FINISH: Traversal over Functions" << endl;
  return abortme;  
}
Exemple #9
0
void CudaOptimizer::getArrayReferenceCounts(SgBasicBlock* kernel_body, 
					    std::map<SgInitializedName*, int>& varCount_map)
{
  
  Rose_STL_Container<SgNode*> arrList = NodeQuery::querySubTree(kernel_body, V_SgPntrArrRefExp);  
  Rose_STL_Container<SgNode*>::iterator arr;
  
  for(arr = arrList.begin(); arr != arrList.end(); arr++)
    {
      SgExpression* arrayName; 
      vector<SgExpression*>  subscripts; //first index is i if E[j][i]
      
      //index list are from right to left 
      bool yes = MintArrayInterface::isArrayReference(isSgExpression(*arr), &arrayName, &subscripts);
      assert(yes);

      SgInitializedName *i_name = SageInterface::convertRefToInitializedName(isSgVarRefExp (arrayName));

      //this is the first time the var appears
      if(varCount_map.find(i_name) == varCount_map.end())
	varCount_map[i_name] = 0;
      
      varCount_map[i_name]++;

      int arrayDim = subscripts.size() ;
      
      arr = arr + arrayDim - 1;
    }
}
Exemple #10
0
string
CommandlineProcessing::generateStringFromArgList ( Rose_STL_Container<string> argList, bool skipInitialEntry, bool skipSourceFiles )
   {
     string returnString;

     for (Rose_STL_Container<string>::iterator i = argList.begin();
          i != argList.end(); ++i) {
       if (skipInitialEntry && i == argList.begin()) continue;
       if (skipSourceFiles == true) {
               string arg    = *i;
               string suffix = "";
         if (arg.length() > 2) suffix = arg.substr(arg.size() - 2);
         if (suffix == ".C" || arg.find("--edg:definition_list_file") == 0) {
                 // DQ (5/13/2004): It was not a great idea to put this filter into this function 
                 // remove it and handle the filtering of definition_list_file better ...  later!
           continue;
             }
             }
       // returnString += *i;
       returnString += *i + " ";
        }

  // printf ("In generateStringFromArgList(): returnString = %s \n",returnString.c_str());

     return returnString;
   }
int main( int argc, char * argv[] ) 
{
        // Build the AST used by ROSE
        SgProject* project = frontend(argc,argv);
        
        generatePDF ( *project );
        
        Rose_STL_Container<SgNode*> functions = NodeQuery::querySubTree(project, V_SgFunctionDefinition);
        for (Rose_STL_Container<SgNode*>::const_iterator i = functions.begin(); i != functions.end(); ++i) {
                SgFunctionDefinition* curFunc = isSgFunctionDefinition(*i);
                ROSE_ASSERT(curFunc);
                                
                SgBasicBlock *funcBody = curFunc->get_body();
                InterestingNode funcCFGStart = (InterestingNode)funcBody->cfgForBeginning();;
                        
                // output the CFG to a file
                ofstream fileCFG;
                fileCFG.open((curFunc->get_declaration()->get_name().getString()+"_cfg.dot").c_str());
                cout << "writing to file "<<(curFunc->get_declaration()->get_name().getString()+"_cfg.dot")<<"\n";
                VirtualCFG::cfgToDot(fileCFG, curFunc->get_declaration()->get_name(), funcCFGStart);
                fileCFG.close();
        }
        
        // Unparse and compile the project (so this can be used for testing)
        return backend(project);
}
int main(int argc, char *argv[]) 
{
  SgProject* sageProject = frontend(argc,argv);
  AstTests::runAllTests(sageProject);

  Rose_STL_Container <SgNode*> functions = NodeQuery::querySubTree(sageProject, V_SgFunctionDefinition);

  for (Rose_STL_Container <SgNode*>::const_iterator i = functions.begin(); i != functions.end(); ++i) 
  {
    SgFunctionDefinition* proc = isSgFunctionDefinition(*i);
    ROSE_ASSERT (proc);
    string file_name = StringUtility::stripPathFromFileName(proc->get_file_info()->get_filename());
    string file_func_name= file_name+ "_"+proc->get_mangled_name().getString();
    
    string full_output = file_func_name +"_scfg.dot";
    // Full CFG graph
    StaticCFG::CFG cfg(proc);
    cfg.buildFullCFG();
    cfg.cfgToDot(proc, full_output);


#if 0 // not ready
    string simple_output = file_func_name +"_simple_vcfg.dot";
    std::ofstream simplegraph(simple_output.c_str());
    // Simplified CFG suitable for most analyses
    // This will cause assertion failure
    //StaticCFG::cfgToDot(simplegraph, proc->get_declaration()->get_name(), StaticCFG::makeInterestingCfg(proc)); 
    // This will generate identical graph as cfgToDotForDebugging ()
    StaticCFG::cfgToDot(simplegraph, proc->get_declaration()->get_name(), proc->cfgForBeginning());
#endif    
  }
  return 0;
}
Exemple #13
0
          NameQuerySynthesizedAttributeType NameQuery::queryNodeList 
                 ( Rose_STL_Container<SgNode*> nodeList,
                   std::string targetNode,
                   NameQuery::TypeOfQueryTypeTwoParameters elementReturnType ){
                return AstQueryNamespace::queryRange(nodeList.begin(), nodeList.end(),
                             std::bind2nd(getFunction(elementReturnType), targetNode));

          };
Exemple #14
0
          NameQuerySynthesizedAttributeType NameQuery::queryNodeList 
                 ( Rose_STL_Container<SgNode*> nodeList,
                   std::string targetNode,
                   NameQuery::roseFunctionPointerTwoParameters querySolverFunction ){
                return AstQueryNamespace::queryRange(nodeList.begin(), nodeList.end(),
                             std::bind2nd(std::ptr_fun(querySolverFunction), targetNode));
//                                  std::bind2nd(getFunction(elementReturnType),traversal), defineQueryType);

          };
Exemple #15
0
static bool ContainsNonSimpleCall(SgStatement *stmt)
{
   static std::set< std::string > segDB ;
   bool containsUnknownCall = false ;

   if (segDB.empty())
   {
      char funcName[128] ;
      FILE *fp ;
      if ((fp = fopen("SegDB.txt", "r")) != NULL)
      {
         while(fgets(funcName, 128, fp))
         {
            funcName[strlen(funcName)-1] = 0 ;
            segDB.insert(funcName) ;
         }
         fclose(fp) ;
      } 
      else
      {
         printf("File SEGDB.txt is absent. Sequential segment results degraded.\n") ;
         segDB.insert("_____") ;
      }
   }
   /* check to see if this statement contains any function calls */
   Rose_STL_Container<SgNode*> calls =
       NodeQuery::querySubTree(stmt, V_SgFunctionCallExp) ;

   for (Rose_STL_Container<SgNode*>::iterator c_itr = calls.begin();
           c_itr != calls.end(); ++c_itr)
   {
      SgFunctionCallExp *stmt = isSgFunctionCallExp(*c_itr) ;
      ROSE_ASSERT(stmt);

      SgFunctionRefExp *func = isSgFunctionRefExp(stmt->get_function()) ;
      if (func != NULL)
      {
         SgFunctionSymbol *funcName = func->get_symbol() ;

         if (segDB.find(funcName->get_name().getString()) == segDB.end())
         {
            containsUnknownCall = true ;
            break ;
         }
      }
      else
      {
         /* Since I can't handle this case, assume the worst -- for now */
         containsUnknownCall = true ;
         break ;
      }
   }

   return containsUnknownCall ;
}
Exemple #16
0
bool MintArrayInterface::isStencilArray(std::vector<SgExpression*> expList) 			
{

//takes all the references of an array in a exp list 
//returns if the accesses are to the north, south, east or west
//Assumes arrays are not represented in 1-dim. (do I handle only 2D? )
//Example :expList contains  E[i][j], E[i][j+1], E[i][j-1] then return "yes" it is stencil
//        :expList contains  E[i][j], E[i][j], E[i][j] then return NO.
//we need a better way to determine if an accesses is strided access.
  
  std::vector<SgExpression*>::iterator it; 

  for(it = expList.begin(); it != expList.end(); it++)
    {
      SgExpression* exp = (*it);

      Rose_STL_Container<SgNode*> arrList = NodeQuery::querySubTree(exp, V_SgPntrArrRefExp);
  
      Rose_STL_Container<SgNode*>::iterator arr;
  
      for(arr = arrList.begin(); arr != arrList.end(); arr++)
	{
	  
	  SgExpression* arrayName; 
	  vector<SgExpression*>  subscripts; //first index is i if E[j][i]
	  
	  //index list are from right to left 
	  bool yes = MintArrayInterface::isArrayReference(isSgExpression(*arr), &arrayName, &subscripts);
	  assert(yes);
	  
	  vector<SgExpression*>::iterator indexExp;

	  for(indexExp = subscripts.begin(); indexExp != subscripts.end(); indexExp++)
	    {
	      //looking for minus, plus 1s: i-1, j+1
	      Rose_STL_Container<SgNode*> constExp = NodeQuery::querySubTree(*indexExp, V_SgIntVal);
	      
	      Rose_STL_Container<SgNode*> indexVarExp = NodeQuery::querySubTree(*indexExp, V_SgVarRefExp);

	      //should I check if it is 0 ?
	      if(constExp.size() > 0 && indexVarExp.size()> 0){
		return true;
	      }
	    }

	  int arrayDim = subscripts.size() ;
	  
	  arr = arr + arrayDim - 1;
	  
	}
    }
  return false;
}
Exemple #17
0
//! Convert a vector of string to a single string
// std::string CommandlineProcessing::generateStringFromArgList( Rose_STL_Container<std::string> & argList)
std::string CommandlineProcessing::generateStringFromArgList( const Rose_STL_Container<std::string> & argList)
{
  string result; 
  Rose_STL_Container<std::string>::const_iterator iter;
  for (iter = argList.begin(); iter != argList.end(); iter ++)
  {
    if (iter !=argList.begin())
      result += " ";
    result += *iter;
  }
  return result;  
}
Exemple #18
0
Fichier : mlm.cpp Projet : 8l/rose
void mlmTransform::insertHeaders(SgProject* project)
{
  Rose_STL_Container<SgNode*> globalList = NodeQuery::querySubTree (project,V_SgGlobal);
  for(Rose_STL_Container<SgNode*>::iterator i = globalList.begin(); i != globalList.end(); i++)
  {
    SgGlobal* global = isSgGlobal(*i);
    ROSE_ASSERT(global);

    PreprocessingInfo* headerInfo = insertHeader("mlm.h",PreprocessingInfo::after,false,global);
    headerInfo->set_file_info(global->get_file_info());
  }
  return; //assume always successful currently
}
void
mergeList ( NodeQuerySynthesizedAttributeType & nodeList, const Rose_STL_Container<SgNode*> & localList )
   {
  // Supporting function for querySolverGrammarElementFromVariantVector
     unsigned localListSize = localList.size();
     unsigned nodeListSize  = nodeList.size();
     for (Rose_STL_Container<SgNode*>::const_iterator i = localList.begin(); i != localList.end(); i++)
        {
       // printf ("Adding node to list (%s) \n",(*i)->sage_class_name());
          nodeList.push_back(*i);
        }
     ROSE_ASSERT (nodeList.size() == nodeListSize+localListSize);
   }
void
printNodeList ( const Rose_STL_Container<SgNode*> & localList )
   {
  // Supporting function for querySolverGrammarElementFromVariantVector
     int counter = 0;
     printf ("Output node list: \n");
     for (Rose_STL_Container<SgNode*>::const_iterator i = localList.begin(); i != localList.end(); i++)
        {
       // printf ("Adding node to list! \n");
          printf ("   list element #%d = %s \n",counter,(*i)->sage_class_name());
          counter++;
        }
   }
//! Remove file names specified in filenameList from argv, except for 'exceptFilename'
void
CommandlineProcessing::removeAllFileNamesExcept ( vector<string> & argv, Rose_STL_Container<std::string> filenameList, std::string exceptFilename )
   {
#if 0
     printf ("In CommandlineProcessing::removeAllFileNamesExcept exceptFilename = %s \n",exceptFilename.c_str());
     printf ("In removeAllFileNamesExcept (at top): argv         = \n%s \n",StringUtility::listToString(argv).c_str());
     printf ("In removeAllFileNamesExcept (at top): filenameList = \n%s \n",StringUtility::listToString(filenameList).c_str());
#endif

     for (unsigned int i=0; i < argv.size(); i++)
        {
          string argString = argv[i];
#if 0
          printf ("i = %u argString = %s \n",i,argString.c_str());
#endif
          Rose_STL_Container<std::string>::iterator filenameIterator = filenameList.begin();
          while (filenameIterator != filenameList.end())
             {
#if 0
               printf ("filenameIterator = %s \n",filenameIterator->c_str());
#endif
            // DQ (1/17/2009): This is a match with filenameIterator = a.out and argString = a.out.new!
            // I think we only want to do anything about exact matches.
            // if ( argString.substr(0,filenameIterator->size()) == *filenameIterator )
               if ( argString == *filenameIterator )
                  {
#if 0
                    printf ("Found a file name (removeAllFileNamesExcept): %s \n",argString.c_str());
#endif
                    if (*filenameIterator != exceptFilename)
                       {
#if 0
                         printf ("*filenameIterator != exceptFilename so erase end of argv for i = %u \n",i);
#endif
                      // This is not an iterator invalidation error, but it is strange code!
                         argv.erase(argv.begin() + i);
                         --i; // To counteract the i++ in the loop header
#if 0
                         printf ("After erase: i = %u argv = \n%s \n",i,StringUtility::listToString(argv).c_str());
#endif
                       }
                  }

               filenameIterator++;
             }
        }

#if 0
     printf ("Leaving removeAllFileNamesExcept (at bottom): argv         = \n%s \n",StringUtility::listToString(argv).c_str());
#endif
   }
Exemple #22
0
QStringList ProjectNode::getCommandLine() const
{
    QStringList res;

    Rose_STL_Container<std::string> arglist;
    arglist = sgProject->get_originalCommandLineArgumentList();

    Rose_STL_Container<std::string>::iterator iter;
    for(iter = arglist.begin(); iter != arglist.end(); ++iter )
        res << iter->c_str();


    return res;
}
Exemple #23
0
int main(int argc, char** argv)
{
	//Parse command-line args
	ProgramOptions po(argc, argv);

	//Initialize the AST
	SgProject* project = new SgProject(argc, argv);
	ROSE_ASSERT(project);
	AstTests::runAllTests(project); //TODO switch on/off with command-line args

	//Set the folder containing the features
	string featureFolder = "";
	bool defaultFeatures = po.getFeaturesFolder(featureFolder);
	if(!defaultFeatures)
		CallScheduler::setFeaturesFolder(featureFolder);

	//Loop through all partitioned kernels and add scheduling calls
	Rose_STL_Container<SgNode*> pragmas = querySubTree(project, V_SgPragmaDeclaration);
	Rose_STL_Container<SgNode*>::const_iterator pragmaIt = pragmas.begin();
	SgPragmaDeclaration* pragma = NULL;
	SgFunctionDeclaration* funcDecl = NULL;
	SgStatement* stmt = NULL;
	for(pragmaIt = pragmas.begin(); pragmaIt != pragmas.end(); pragmaIt++)
	{
		pragma = isSgPragmaDeclaration(*pragmaIt);
		ROSE_ASSERT(pragma);

		PragmaParser pp(pragma);
		if(pp.isPopcornPragma() && pp.getPragmaType() == PARTITIONED)
		{
			stmt = getNextStatement(pragma);
			while(!isSgFunctionDeclaration(stmt))
				stmt = getNextStatement(pragma);
			funcDecl = isSgFunctionDeclaration(stmt);
			ROSE_ASSERT(funcDecl);
			Pragmas pragmas(funcDecl);

			//Add scheduling calls
			CallScheduler cs(funcDecl, pragmas);
			cs.addSchedulerCalls();

			//Insert the header
			//TODO this won't insert the header into files
			insertHeader(po.getSchedulerHeaderLocation(), PreprocessingInfo::after, false,
					getGlobalScope(funcDecl));
		}
	}

	return backend(project);
}
int main( int argc, char * argv[] )
   {
  // Build the AST used by ROSE
     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT(project != NULL);

  // Build a list of functions within the AST
     Rose_STL_Container<SgNode*> functionCallList = NodeQuery::querySubTree (project,V_SgFunctionCallExp);

     int functionCounter = 0;
     for (Rose_STL_Container<SgNode*>::iterator i = functionCallList.begin(); i != functionCallList.end(); i++)
        {
          SgExpression* functionExpression = isSgFunctionCallExp(*i)->get_function();
          ROSE_ASSERT(functionExpression != NULL);

          SgFunctionRefExp* functionRefExp = isSgFunctionRefExp(functionExpression);

          SgFunctionSymbol* functionSymbol = NULL;
          if (functionRefExp != NULL)
             {
            // Case of non-member function
               functionSymbol = functionRefExp->get_symbol();
             }
            else
             {
            // Case of member function (hidden in rhs of binary dot operator expression)
               SgDotExp* dotExp = isSgDotExp(functionExpression);
               ROSE_ASSERT(dotExp != NULL);

               functionExpression = dotExp->get_rhs_operand();
               SgMemberFunctionRefExp* memberFunctionRefExp = isSgMemberFunctionRefExp(functionExpression);
               ROSE_ASSERT(memberFunctionRefExp != NULL);

               functionSymbol = memberFunctionRefExp->get_symbol();
             }
          
          ROSE_ASSERT(functionSymbol != NULL);

          SgFunctionDeclaration* functionDeclaration = functionSymbol->get_declaration();
          ROSE_ASSERT(functionDeclaration != NULL);
          
       // Output mapping of function calls to function declarations
          printf ("Location of function call #%d at line %d resolved by overloaded function declared at line %d \n",
               functionCounter++,
               isSgFunctionCallExp(*i)->get_file_info()->get_line(),
               functionDeclaration->get_file_info()->get_line());
        }

     return 0;
   }
Exemple #25
0
 void registerAstSubtreeIds (SgNode* root)
 {
   // We only care about located nodes for now since they are visible to users in source code
   // we have to include SgProject and SgSourceFile nodes also.
   VariantVector vv;  
   vv.push_back(V_SgProject);
   vv.push_back(V_SgSourceFile);
   vv.push_back(V_SgLocatedNode);
   Rose_STL_Container <SgNode*> nodeList = NodeQuery::querySubTree (root, vv);
   for (Rose_STL_Container <SgNode*>::iterator iter = nodeList.begin(); iter != nodeList.end(); iter++)
   {
     SgNode* n = (*iter);
     setId (n);
   } 
 }
Exemple #26
0
void testOMPForSensitiveInsertion()
{
        annotateAllOmpFors(project);
        
        Rose_STL_Container<SgNode*> iteratorUses = NodeQuery::querySubTree(project, V_SgInitializedName);       
        OMPcfgRWTransaction trans;
        //VirtualCFG::cfgRWTransaction trans;
        trans.beginTransaction();
        for(Rose_STL_Container<SgNode*>::iterator it = iteratorUses.begin(); it!=iteratorUses.end(); it++)
        {
                SgInitializedName *initName = isSgInitializedName(*it); ROSE_ASSERT(initName);
                //printf("initialized Name <%s | %s>\n", initName->get_parent()->unparseToString().c_str(), initName->get_parent()->class_name().c_str());
                
                if(initName->get_name().getString() == "iterator")
                {
                        //printf("   inserting1 at spot <%s | %s>\n", initName->get_parent()->unparseToString().c_str(), initName->get_parent()->class_name().c_str());
                        trans.insertBefore(initName, fooCallCreate());
                        trans.insertAfter(initName, fooCallCreate());
                }
        }
        
        iteratorUses = NodeQuery::querySubTree(project, V_SgVarRefExp); 
        for(Rose_STL_Container<SgNode*>::iterator it = iteratorUses.begin(); it!=iteratorUses.end(); it++)
        {
                SgVarRefExp *varRef = isSgVarRefExp(*it); ROSE_ASSERT(varRef);
                
                if(varRef->get_symbol()->get_name().getString() == "iterator")
                {
                        //printf("   inserting2 at spot <%s | %s>\n", varRef->get_parent()->unparseToString().c_str(), varRef->get_parent()->class_name().c_str());
                        trans.insertBefore(varRef->get_parent(), fooCallCreate());
                        trans.insertAfter(varRef->get_parent(), fooCallCreate());
                }
        }
        
        trans.commitTransaction();
}
int main (int argc, char *argv[])
{
  SgProject *project = frontend (argc, argv);

  Rose_STL_Container<SgNode*> nodeList = NodeQuery::querySubTree(project,V_SgVarRefExp);
  for (Rose_STL_Container<SgNode *>::iterator i = nodeList.begin(); i != nodeList.end(); i++)
  {
    SgVarRefExp *vRef = isSgVarRefExp((*i));
    cout<<"Found a variable reference ! "<<endl;
  }

  ROSE_ASSERT (nodeList.size() != 0);

  return backend (project);
}
Exemple #28
0
int MintCudaMidend::insertHeaders(SgProject* project)
{

  //cout << "  INFO:Mint: Inserting runtime header cutil.h" << endl << endl ;

  Rose_STL_Container<SgNode*> globalScopeList = NodeQuery::querySubTree (project,V_SgGlobal);

  for (Rose_STL_Container<SgNode*>::iterator i = globalScopeList.begin(); i != globalScopeList.end(); i++)
    {
      SgGlobal* globalscope = isSgGlobal(*i);
      ROSE_ASSERT (globalscope != NULL);
      //SageInterface::insertHeader("cutil.h",PreprocessingInfo::after,false,globalscope);
    }
  return 0; //assume always successful currently                                                                                             
}
Exemple #29
0
void findCandidateFunctionDefinitions (SgProject* project, std::vector<SgFunctionDefinition* >& candidateFuncDefs)
{
  ROSE_ASSERT (project != NULL);
  // For each source file in the project
  SgFilePtrList & ptr_list = project->get_fileList();
  for (SgFilePtrList::iterator iter = ptr_list.begin(); iter!=ptr_list.end();
      iter++)
  {
    SgFile* sageFile = (*iter);
    SgSourceFile * sfile = isSgSourceFile(sageFile);
    ROSE_ASSERT(sfile);
//    SgGlobal *root = sfile->get_globalScope();

    if (enable_debug)
      cout<<"Processing each function within the files "<< sfile->get_file_info()->get_filename() <<endl;
    //      cout<<"\t loop at:"<< cur_loop->get_file_info()->get_line() <<endl;

    // This is wrong, many functions in question are not top level declarations!!
    //SgDeclarationStatementPtrList& declList = root->get_declarations ();
    //VariantVector vv;
    Rose_STL_Container<SgNode*> defList = NodeQuery::querySubTree(sfile, V_SgFunctionDefinition); 
//    bool hasOpenMP= false; // flag to indicate if omp.h is needed in this file

    //For each function body in the scope
    //for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) 
    for (Rose_STL_Container<SgNode*>::iterator p = defList.begin(); p != defList.end(); ++p) 
    {
      SgFunctionDefinition *defn = isSgFunctionDefinition(*p);
      ROSE_ASSERT (defn != NULL);

      SgFunctionDeclaration *func = defn->get_declaration();
      ROSE_ASSERT (func != NULL);

      if (enable_debug)
        cout<<"\t considering function "<< func->get_name() << " at "<< func->get_file_info()->get_line()<<endl;
      //ignore functions in system headers, Can keep them to test robustness
      if (defn->get_file_info()->get_filename()!=sageFile->get_file_info()->get_filename())
      {
        if (enable_debug)
          cout<<"\t Skipped since the function's associated file name does not match current file being considered. Mostly from a header. "<<endl;
        continue;
      }
      candidateFuncDefs.push_back(defn);
    } // end for def list
  } // end for file list
}
int main(int argc, char* argv[]) {
	std::vector<std::string> pragma_values;
	SgProject* proj = frontend(argc,argv);
	ROSE_ASSERT(proj != NULL);
	SgFunctionDeclaration* mainDefDecl = SageInterface::findMain(proj);
	SgFunctionDefinition* mainDef = mainDefDecl->get_definition();
	
	Rose_STL_Container<SgNode*> pragmaList = NodeQuery::querySubTree(proj,V_SgPragmaDeclaration);
	for (Rose_STL_Container<SgNode*>::iterator i = pragmaList.begin(); i != pragmaList.end(); i++) {
		SgPragmaDeclaration* prg = isSgPragmaDeclaration(*i);
		std::string prag_string = get_pragma_string(prg);
		if (isSMTGeneral(prag_string)) {
			std::string parsed = parseSMTGeneral(prag_string);
			std::cout << ";;SMTGeneral command found: " << parsed << std::endl;
			//continue;
		}
		else {
		//std::cout << "SMTGeneral command not found" << std::endl;
		std::string pos;
		pos = get_position(prag_string);
		if (pos == "define") {
			std::cout << "define:\n";
			std::vector<std::pair<std::string, std::string> > pragma_values = get_vars(prag_string);
			for (std::vector<std::pair<std::string,std::string> >::iterator j = pragma_values.begin(); j != pragma_values.end(); j++) {
				std::cout << (*j).first << " " << (*j).second << std::endl;
			}
			
		}
		else if (pos == "assume") {
			std::cout << "assume:\n";
			std::vector<std::string> assumptions = get_assumptions(prag_string);
			for (std::vector<std::string>::iterator i = assumptions.begin(); i != assumptions.end(); i++) {
				std::cout << (*i) << std::endl;
			}	
		}
		else if (pos == "begin" || pos == "end") {
			std::cout << "position: " << pos << std::endl;
		}
		else {
			ROSE_ASSERT(false);
		}
		}
	}
	return 0;
}