void CompassAnalyses::FunctionDocumentation::Traversal:: visit(SgNode* sgNode) { // Implement your traversal here. if (isSgFunctionDeclaration(sgNode)) { SgFunctionDeclaration* funcDecl = isSgFunctionDeclaration(sgNode); if (funcDecl->get_file_info()->isCompilerGenerated() || funcDecl->get_definingDeclaration() != sgNode ) return; if (!( isDocumented( funcDecl) || isDocumented(isSgFunctionDeclaration(funcDecl->get_firstNondefiningDeclaration())) ) ) { std::string funcName = funcDecl->get_qualified_name(); output->addOutput(new CheckerOutput(funcDecl, funcName)); } } } //End of the visit function.
void FunctionTypeAccu::visit(SgNode *node) { if (isSgFunctionDeclaration(node)) { SgFunctionDeclaration *func = isSgFunctionDeclaration(node); funcs_.push_back(func); } return; }
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); }
SgFunctionDeclaration *CudaOutliner::createFuncSkeleton (const string& name, SgType* ret_type, SgFunctionParameterList* params, SgScopeStatement* scope) { ROSE_ASSERT(scope != NULL); ROSE_ASSERT(isSgGlobal(scope)!=NULL); SgFunctionDeclaration* func; SgProcedureHeaderStatement* fortranRoutine; if (SageInterface::is_Fortran_language()) { fortranRoutine = SageBuilder::buildProcedureHeaderStatement(name.c_str(),ret_type, params, SgProcedureHeaderStatement::e_subroutine_subprogram_kind,scope); func = isSgFunctionDeclaration(fortranRoutine); } else { func = SageBuilder::buildDefiningFunctionDeclaration(name,ret_type,params,scope); } ROSE_ASSERT (func != NULL); SgFunctionSymbol* func_symbol = scope->lookup_function_symbol(func->get_name()); ROSE_ASSERT(func_symbol != NULL); if (0)//Outliner::enable_debug) { printf("Found function symbol in %p for function:%s\n",scope,func->get_name().getString().c_str()); } return func; }
SgFunctionDeclaration *RoseToLLVM::findEnclosingFunction(SgNode *node) { return (node == NULL || isSgProject(node) ? (SgFunctionDeclaration *) NULL : isSgFunctionDeclaration(node) ? (SgFunctionDeclaration *) node : findEnclosingFunction(node -> get_parent())); }
void SgFunctionDeclaration::fixupCopy_symbols(SgNode* copy, SgCopyHelp & help) const { #if DEBUG_FIXUP_COPY printf ("\nIn SgFunctionDeclaration::fixupCopy_symbols(): for function = %s = %p = %s copy = %p \n",this->get_name().str(),this,this->class_name().c_str(),copy); #endif SgFunctionDeclaration* functionDeclaration_copy = isSgFunctionDeclaration(copy); ROSE_ASSERT(functionDeclaration_copy != NULL); // Call the base class fixupCopy member function SgDeclarationStatement::fixupCopy_symbols(copy,help); // Setup the scopes of the SgInitializedName objects in the paraleter list ROSE_ASSERT(get_parameterList() != NULL); get_parameterList()->fixupCopy_symbols(functionDeclaration_copy->get_parameterList(),help); // Setup the details in the SgFunctionDefinition (this may have to rebuild the sysmbol table) // printf ("In SgFunctionDeclaration::fixupCopy_symbols(): this->get_definition() = %p \n",this->get_definition()); if (this->get_definition() != NULL) { // DQ (3/15/2014): The defining declaration should not be marked (isForward() == true). if (isForward() == true) { printf ("Error: The defining declaration should not be marked (isForward() == true) \n"); printf ("SgFunctionDeclaration::fixupCopy_symbols(): (isForward() == true): functionDeclaration_copy = %p = %s \n",functionDeclaration_copy,functionDeclaration_copy->class_name().c_str()); printf (" --- functionDeclaration_copy->get_firstNondefiningDeclaration() = %p \n",functionDeclaration_copy->get_firstNondefiningDeclaration()); printf (" --- functionDeclaration_copy->get_definingDeclaration() = %p \n",functionDeclaration_copy->get_definingDeclaration()); functionDeclaration_copy->get_file_info()->display("SgFunctionDeclaration::fixupCopy_scopes(): (isForward() == true): debug"); // Reset this! // functionDeclaration_copy->unsetForward(); } ROSE_ASSERT(isForward() == false); // DQ (2/26/2009): Handle special cases where the copyHelp function is non-trivial. // Is every version of copyHelp object going to be a problem? // For the outlining, our copyHelp object does not copy defining function declarations // and substitutes a non-defining declarations, so if the copy has been built this way // then skip trying to reset the SgFunctionDefinition. // printf ("In SgFunctionDeclaration::fixupCopy_symbols(): functionDeclaration_copy->get_definition() = %p \n",functionDeclaration_copy->get_definition()); // this->get_definition()->fixupCopy_symbols(functionDeclaration_copy->get_definition(),help); if (functionDeclaration_copy->get_definition() != NULL) { this->get_definition()->fixupCopy_symbols(functionDeclaration_copy->get_definition(),help); } // If this is a declaration with a definition then it is a defining declaration // functionDeclaration_copy->set_definingDeclaration(functionDeclaration_copy); } // printf ("\nLeaving SgFunctionDeclaration::fixupCopy_symbols(): for function = %s = %p = %s copy = %p \n",this->get_name().str(),this,this->class_name().c_str(),copy); }
virtual void visit (SgNode* astNode) { SgFunctionDeclaration *fdecl = isSgFunctionDeclaration(astNode); if (fdecl) { fdeclList.push_back(fdecl); } SgFunctionDefinition *fdef = isSgFunctionDefinition(astNode); if (fdef) { fdefList.push_back(fdef); } }
void ASLAnalysis::visit(SgNode* node){ // concrete classes of AST nodes switch(node->variantT()){ // naming scheme for variants: V_<classname> case V_SgFunctionDeclaration:{ SgFunctionDeclaration* fdecl=isSgFunctionDeclaration(node); if(SgFunctionDefinition* fdef=fdecl->get_definition()) { std::string functionName=fdecl->get_name().getString(); Sg_File_Info* ptrFileInfo=node->get_file_info(); std::string aslPrefix=""; if(ptrFileInfo){ aslPrefix=ptrFileInfo->get_filenameString()+"/"; } enterFunction(aslPrefix+functionName); // set function name and reset enumeration counter } } break; // function calls through function pointers case V_SgPointerDerefExp:{ if(isSgFunctionCallExp(node->get_parent()) && !(isSgFunctionCallExp(node->get_parent())->get_function() != node)){ #ifdef DEBUG std::cout<<"Function Pointer at call-site"<<std::endl; #endif storeLocalSite(node); callSiteCounter++; functionPointerCallCounter++; } } break; case V_SgFunctionCallExp:{ SgFunctionCallExp* fcall=isSgFunctionCallExp(node); if(SgFunctionRefExp* func=isSgFunctionRefExp(fcall->get_function())) { // SgFunctionSymbol* functionSymbol=func->get_symbol(); // std::string functionName=functionSymbol->get_name().getString(); callSiteCounter++; } } break; } }
foreach(SgDirectedGraphEdge *edge, edges) { SgGraphNode *toNode = edge->get_to(); SgFunctionDeclaration *toDecl = isSgFunctionDeclaration(toNode->get_SgNode()); ROSE_ASSERT(toDecl != NULL); if(toDecl->get_specialFunctionModifier().isConstructor() || toDecl->get_specialFunctionModifier().isDestructor()) continue; if(find(functions.begin(), functions.end(), toDecl) == functions.end()) { graph->removeDirectedEdge(edge); std::cout << "Edge removed from " << defDecl->get_qualified_name().getString() << " to " << toDecl->get_qualified_name().getString()<< std::endl; } }
void SimpleInstrumentation::visit ( SgNode* astNode ) { // Demonstrate and test append mechanism for statements // printf ("In assemblyFunction(): astNode->sage_class_name() = %s \n",astNode->sage_class_name()); if (isSgFunctionDeclaration(astNode) != NULL) { // printf ("Found a function declaration \n"); SgFunctionDeclaration* functionDeclarationStatement = isSgFunctionDeclaration(astNode); SgName sageName = functionDeclarationStatement->get_name(); string functionNameString = sageName.str(); // Make sure this is the "main" function before we insert new code if (functionNameString == "main") { string globalDeclarations = "int k;"; string functionSource = ""; string localDeclarations = "\ void myTimerFunctionStart(void) \n\ { \n\ int xyzVariable; \n\ } \n\n\
void visitorTraversal::visit(SgNode* n) { if (isSgFunctionDeclaration(n) != NULL) { printf ("Found a function declaration ... \n"); // Build the nested traversal object nestedVisitorTraversal exampleTraversal; // Call the traversal starting at the project node of the AST (traverse in postorder just to be different) // Note that we call the traverse function instead of traverseInputFiles, because we are not starting at // the AST root. exampleTraversal.traverse(n,postorder); } }
ValueP ExternalCallingStackFrame::evalFunctionRefExp(SgFunctionSymbol *sym) { SgFunctionDeclaration *decl = sym->get_declaration(); SgFunctionDeclaration *defDecl = isSgFunctionDeclaration(decl->get_definingDeclaration()); if (defDecl == NULL) { return externEvalFunctionRefExp(sym); } SgFunctionDefinition *def = defDecl->get_definition(); if (def == NULL) { return externEvalFunctionRefExp(sym); } return StackFrame::evalFunctionRefExp(sym); }
int main(int argc, char * argv[]) { SgProject* project = frontend(argc,argv); std::ofstream report_file; report_file.open(((*project)[0]->getFileName() + ".report").c_str()); if (report_file.is_open()) { PolyhedralModelisation poly_model; poly_model.traverse(project); std::set<PolyhedralElement *> collection; poly_model.collectPolyhedralElement(collection, true, false, true, true, false); // default arguments... std::set<PolyhedralElement *>::iterator it; for (it = collection.begin(); it != collection.end(); it++) { const PolyhedralControl * control = dynamic_cast<const PolyhedralControl *>(*it); if (control == NULL) continue; SgFunctionDefinition * func_def = isSgFunctionDefinition(control->associated_node); if (func_def == NULL) continue; SgFunctionDeclaration * func_decl = isSgFunctionDeclaration(func_def->get_declaration()); if (func_decl == NULL) continue; if (!func_decl->get_functionModifier().isCudaKernel()) continue; Sg_File_Info * fi = func_def->get_startOfConstruct(); report_file << "Found: " << func_decl->get_name() << " at " << fi->get_filenameString() << ":" << fi->get_line() << std::endl; report_file << "\tStructure:" << std::endl; (*it)->print(report_file, "\t\t"); report_file << std::endl; report_file << "\tAccesses:" << std::endl; std::set<Access *> accesses; (*it)->collectAccess(accesses); std::set<Access *>::iterator it_access; for (it_access = accesses.begin(); it_access != accesses.end(); it_access++) { (*it_access)->print(report_file, "\t\t"); } report_file << std::endl; report_file << std::endl; } } else std::cerr << "Cannot open " << (*project)[0]->getFileName() << ".report to save the analysis report..." << std::endl; return 0; }
bool isVirtual(SgFunctionDeclaration *functionDeclaration) { if ( functionDeclaration == NULL ) return false; if ( functionDeclaration->get_functionModifier().isVirtual() ) return true; SgDeclarationStatement *firstNondefiningDeclaration = functionDeclaration->get_firstNondefiningDeclaration(); if ( firstNondefiningDeclaration == NULL ) return false; SgFunctionDeclaration *firstNondefiningFuncDeclaration = isSgFunctionDeclaration(firstNondefiningDeclaration); ROSE_ASSERT(firstNondefiningFuncDeclaration != NULL); return firstNondefiningFuncDeclaration->get_functionModifier().isVirtual(); }
void CompassAnalyses::FunctionDefinitionPrototype::Traversal:: visit(SgNode* node) { SgDeclarationStatement *sgdecl = isSgDeclarationStatement(node); if( sgdecl != NULL ) { SgFunctionDeclaration *fd = isSgFunctionDeclaration(node); if( fd != NULL ) { if( sgdecl->get_firstNondefiningDeclaration() == NULL ) { output->addOutput( new CompassAnalyses::FunctionDefinitionPrototype::CheckerOutput( node, fd->get_name().getString().c_str() ) ); } } //if( fd != NULL ) } } //End of the visit function.
virtual void visit(SgNode * n) { switch (n->variantT()) { case V_SgFunctionDeclaration: { SgFunctionDeclaration * func_decl = isSgFunctionDeclaration(n); ROSE_ASSERT(func_decl != NULL); std::string func_name = func_decl->get_name().getString(); // std::cout << "Found SgFunctionDeclaration: " << func_name << std::endl; if (func_name == "caller") p_caller = func_decl; if (func_name == "kernel") p_kernel = func_decl; break; } case V_SgForStatement: { SgForStatement * for_stmt = isSgForStatement(n); ROSE_ASSERT(for_stmt != NULL); // std::cout << "Found SgForStatement." << std::endl; p_for_stmts.push_back(for_stmt); break; } case V_SgFunctionCallExp: { SgFunctionCallExp * func_call = isSgFunctionCallExp(n); ROSE_ASSERT(func_call != NULL); SgFunctionRefExp * func_ref = isSgFunctionRefExp(func_call->get_function()); ROSE_ASSERT(func_ref != NULL); // std::cout << "Found SgFunctionCallExp: " << func_ref->getAssociatedFunctionDeclaration ()->get_name().getString() << std::endl; if (func_ref->getAssociatedFunctionDeclaration()->get_name().getString() == "kernel") p_kernel_call_site = func_call; break; } case V_SgSourceFile: // fix the file suffix, Liao 12/29/2010 { SgSourceFile * sfile = isSgSourceFile (n); ROSE_ASSERT (sfile != NULL); sfile->set_Cuda_only(true); } default:{} } }
void FortranAnalysis::visit(SgFunctionDefinition * func_def) { SgFunctionDeclaration * func_decl = isSgFunctionDeclaration(func_def->get_declaration()); if (func_decl == NULL) return; SgInitializedNamePtrList func_args = func_decl->get_parameterList()->get_args(); SgInitializedNamePtrList::iterator arg = func_args.begin(); // for (it_args = func_args.begin(); it_args != func_args.end(); it_args++) { while (arg != func_args.end()) { SgInitializedName * func_arg = isSgInitializedName(*arg++); SgSymbol * sym = func_def->lookup_symbol(func_arg->get_name()); SgType * type = sym->get_type(); if (sym == NULL) { printf("FortranAnalysis::visit: no symbol for name %s\n", func_arg->get_name().getString().c_str()); } else if (isSgArrayType(type) != NULL) { printf("WARNING: arg %s must be a scalar\n", func_arg->get_name().str()); sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_ARRAY_TYPE_ARG")); } else if (isSgNamedType(type)) { sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_NAMED_TYPE_ARG")); } else { sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_ARG")); } if (sym != NULL && isElementalArrayType(func_arg)) { sym->setAttribute("elemental_attr", new AstTextAttribute("ELEMENTAL_ARRAY")); sym->setAttribute("index_attr", new AstTextAttribute("idx")); } if (sym != NULL && hasArrayDescriptor(func_arg)) { sym->setAttribute("descriptor_attr", new AstTextAttribute("desc_"+func_arg->get_name())); sym->setAttribute("index_attr", new AstTextAttribute("idx_"+func_arg->get_name())); } } }
void VirtualFunctionAnalysis::pruneCallGraph(CallGraphBuilder& builder) { SgIncidenceDirectedGraph *graph = builder.getGraph(); ROSE_ASSERT(graph != NULL); boost::unordered_map<SgFunctionDeclaration*, SgGraphNode*>node_mapping = builder.getGraphNodesMapping(); typedef boost::unordered_map<SgFunctionDeclaration *, SgGraphNode *> map; foreach (map::value_type it, node_mapping) { SgFunctionDeclaration *defDecl = ( it.first->get_definition() != NULL ? it.first : isSgFunctionDeclaration(it.first->get_definingDeclaration()) ); if(defDecl == NULL) continue; Rose_STL_Container<SgNode*> functionCallExpList = NodeQuery::querySubTree(defDecl, V_SgFunctionCallExp); std::vector<SgFunctionDeclaration *> functions; foreach(SgNode* functionCallExp, functionCallExpList) { functions.insert(functions.end(), resolver.at(isSgExpression(functionCallExp)).begin(), resolver.at(isSgExpression(functionCallExp)).end()); }
int main ( int argc, char * argv[] ) { int a; if (argc <= 1) { PrintUsage(argv[0]); return -1; } DEBUG_ICFG = 1; DEBUG_STMT = 0; SgProject sageProject ( argc,argv); SageInterface::changeAllBodiesToBlocks(&sageProject); CmdOptions::GetInstance()->SetOptions(argc, argv); // TestPtrAnal op; // ptr_Anal_ICFG_Creator op; int filenum = sageProject.numberOfFiles(); for (int i = 0; i < filenum; ++i) { SgFile &sageFile = sageProject.get_file(i); SgGlobal *root = sageFile.get_root(); AstInterfaceImpl scope(root); AstInterface fa(&scope); SgDeclarationStatementPtrList& declList = root->get_declarations (); for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) { SgFunctionDeclaration *func = isSgFunctionDeclaration(*p); if (func == 0) continue; SgFunctionDefinition *defn = func->get_definition(); if (defn == 0) continue; op(fa, defn); } } op.draw("out.jpg"); return 0; }
int main ( int argc, char * argv[] ) { if (argc <= 1) { PrintUsage(argv[0]); return -1; } SgProject sageProject ( argc,argv); SageInterface::changeAllLoopBodiesToBlocks(&sageProject); CmdOptions::GetInstance()->SetOptions(argc, argv); TestPtrAnal op; int filenum = sageProject.numberOfFiles(); for (int i = 0; i < filenum; ++i) { SgSourceFile* sageFile = isSgSourceFile(sageProject.get_fileList()[i]); ROSE_ASSERT(sageFile != NULL); SgGlobal *root = sageFile->get_globalScope(); AstInterfaceImpl scope(root); AstInterface fa(&scope); SgDeclarationStatementPtrList& declList = root->get_declarations (); for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) { SgFunctionDeclaration *func = isSgFunctionDeclaration(*p); if (func == 0) continue; SgFunctionDefinition *defn = func->get_definition(); if (defn == 0) continue; op(fa, defn); } } return 0; }
void Visitor::visit(SgNode* n) { SgFunctionDefinition* functionDefinition = isSgFunctionDefinition(n); if (functionDefinition != NULL) { SgTreeCopy tc; #if 1 std::string functionDefinitionString = functionDefinition->unparseToString(); printf ("(before copy) functionDefinitionString = %s \n",functionDefinitionString.c_str()); #endif #if 1 SgFunctionDefinition* copy = isSgFunctionDefinition(n->copy(tc)); ROSE_ASSERT (copy != NULL); #if 1 functionDefinitionString = functionDefinition->unparseToString(); printf ("(after copy) functionDefinitionString = %s \n",functionDefinitionString.c_str()); #endif SgFunctionDeclaration* parentScope = isSgFunctionDeclaration(functionDefinition->get_parent()); ROSE_ASSERT (parentScope); copy->set_parent(parentScope); #endif } }
bool ClangToSageTranslator::VisitFunctionDecl(clang::FunctionDecl * function_decl, SgNode ** node) { #if DEBUG_VISIT_DECL std::cerr << "ClangToSageTranslator::VisitFunctionDecl" << std::endl; #endif bool res = true; // FIXME: There is something weird here when try to Traverse a function reference in a recursive function (when first Traverse is not complete) // It seems that it tries to instantiate the decl inside the function... // It may be faster to recode from scratch... // If I am not wrong this have been fixed.... SgName name(function_decl->getNameAsString()); SgType * ret_type = buildTypeFromQualifiedType(function_decl->getResultType()); SgFunctionParameterList * param_list = SageBuilder::buildFunctionParameterList_nfi(); applySourceRange(param_list, function_decl->getSourceRange()); // FIXME find the good SourceRange (should be stored by Clang...) for (unsigned i = 0; i < function_decl->getNumParams(); i++) { SgNode * tmp_init_name = Traverse(function_decl->getParamDecl(i)); SgInitializedName * init_name = isSgInitializedName(tmp_init_name); if (tmp_init_name != NULL && init_name == NULL) { std::cerr << "Runtime error: tmp_init_name != NULL && init_name == NULL" << std::endl; res = false; continue; } param_list->append_arg(init_name); } if (function_decl->isVariadic()) { SgName empty = ""; SgType * ellipses_type = SgTypeEllipse::createType(); param_list->append_arg(SageBuilder::buildInitializedName_nfi(empty, ellipses_type, NULL)); } SgFunctionDeclaration * sg_function_decl; if (function_decl->isThisDeclarationADefinition()) { sg_function_decl = SageBuilder::buildDefiningFunctionDeclaration(name, ret_type, param_list, NULL); sg_function_decl->set_definingDeclaration(sg_function_decl); if (function_decl->isVariadic()) { sg_function_decl->hasEllipses(); } if (!function_decl->hasBody()) { std::cerr << "Defining function declaration without body..." << std::endl; res = false; } /* if (sg_function_decl->get_definition() != NULL) SageInterface::deleteAST(sg_function_decl->get_definition()); SgFunctionDefinition * function_definition = new SgFunctionDefinition(sg_function_decl, NULL); SgInitializedNamePtrList & init_names = param_list->get_args(); SgInitializedNamePtrList::iterator it; for (it = init_names.begin(); it != init_names.end(); it++) { (*it)->set_scope(function_definition); SgSymbolTable * st = function_definition->get_symbol_table(); ROSE_ASSERT(st != NULL); SgVariableSymbol * tmp_sym = new SgVariableSymbol(*it); st->insert((*it)->get_name(), tmp_sym); } */ SgFunctionDefinition * function_definition = sg_function_decl->get_definition(); if (sg_function_decl->get_definition()->get_body() != NULL) SageInterface::deleteAST(sg_function_decl->get_definition()->get_body()); SageBuilder::pushScopeStack(function_definition); SgNode * tmp_body = Traverse(function_decl->getBody()); SgBasicBlock * body = isSgBasicBlock(tmp_body); SageBuilder::popScopeStack(); if (tmp_body != NULL && body == NULL) { std::cerr << "Runtime error: tmp_body != NULL && body == NULL" << std::endl; res = false; } else { function_definition->set_body(body); body->set_parent(function_definition); applySourceRange(function_definition, function_decl->getSourceRange()); } sg_function_decl->set_definition(function_definition); function_definition->set_parent(sg_function_decl); SgFunctionDeclaration * first_decl; if (function_decl->getFirstDeclaration() == function_decl) { SgFunctionParameterList * param_list_ = SageBuilder::buildFunctionParameterList_nfi(); setCompilerGeneratedFileInfo(param_list_); SgInitializedNamePtrList & init_names = param_list->get_args(); SgInitializedNamePtrList::iterator it; for (it = init_names.begin(); it != init_names.end(); it++) { SgInitializedName * init_param = new SgInitializedName(**it); setCompilerGeneratedFileInfo(init_param); param_list_->append_arg(init_param); } first_decl = SageBuilder::buildNondefiningFunctionDeclaration(name, ret_type, param_list_, NULL); setCompilerGeneratedFileInfo(first_decl); first_decl->set_parent(SageBuilder::topScopeStack()); first_decl->set_firstNondefiningDeclaration(first_decl); if (function_decl->isVariadic()) first_decl->hasEllipses(); } else { SgSymbol * tmp_symbol = GetSymbolFromSymbolTable(function_decl->getFirstDeclaration()); SgFunctionSymbol * symbol = isSgFunctionSymbol(tmp_symbol); if (tmp_symbol != NULL && symbol == NULL) { std::cerr << "Runtime error: tmp_symbol != NULL && symbol == NULL" << std::endl; res = false; } if (symbol != NULL) first_decl = isSgFunctionDeclaration(symbol->get_declaration()); } sg_function_decl->set_firstNondefiningDeclaration(first_decl); first_decl->set_definingDeclaration(sg_function_decl); } else { sg_function_decl = SageBuilder::buildNondefiningFunctionDeclaration(name, ret_type, param_list, NULL); if (function_decl->isVariadic()) sg_function_decl->hasEllipses(); SgInitializedNamePtrList & init_names = param_list->get_args(); SgInitializedNamePtrList::iterator it; for (it = init_names.begin(); it != init_names.end(); it++) { (*it)->set_scope(SageBuilder::topScopeStack()); } if (function_decl->getFirstDeclaration() != function_decl) { SgSymbol * tmp_symbol = GetSymbolFromSymbolTable(function_decl->getFirstDeclaration()); SgFunctionSymbol * symbol = isSgFunctionSymbol(tmp_symbol); if (tmp_symbol != NULL && symbol == NULL) { std::cerr << "Runtime error: tmp_symbol != NULL && symbol == NULL" << std::endl; res = false; } SgFunctionDeclaration * first_decl = NULL; if (symbol != NULL) { first_decl = isSgFunctionDeclaration(symbol->get_declaration()); } else { // FIXME Is it correct? SgNode * tmp_first_decl = Traverse(function_decl->getFirstDeclaration()); first_decl = isSgFunctionDeclaration(tmp_first_decl); ROSE_ASSERT(first_decl != NULL); // ROSE_ASSERT(!"We should have see the first declaration already"); } if (first_decl != NULL) { if (first_decl->get_firstNondefiningDeclaration() != NULL) sg_function_decl->set_firstNondefiningDeclaration(first_decl->get_firstNondefiningDeclaration()); else { ROSE_ASSERT(first_decl->get_firstNondefiningDeclaration() != NULL); } } else { ROSE_ASSERT(!"First declaration not found!"); } } else { sg_function_decl->set_firstNondefiningDeclaration(sg_function_decl); } } ROSE_ASSERT(sg_function_decl->get_firstNondefiningDeclaration() != NULL); /* // TODO Fix problem with function symbols... SgSymbol * symbol = GetSymbolFromSymbolTable(function_decl); if (symbol == NULL) { SgFunctionSymbol * func_sym = new SgFunctionSymbol(isSgFunctionDeclaration(sg_function_decl->get_firstNondefiningDeclaration())); SageBuilder::topScopeStack()->insert_symbol(name, func_sym); } */ // ROSE_ASSERT(GetSymbolFromSymbolTable(function_decl) != NULL); *node = sg_function_decl; return VisitDeclaratorDecl(function_decl, node) && res; }
int main(int argc, char * argv[]) { // Build the AST used by ROSE project = frontend(argc,argv); /*convertToOMPNormalForm(project, project); // Run internal consistancy tests on AST AstTests::runAllTests(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* func = isSgFunctionDefinition(*i); ROSE_ASSERT(func); printf("func = %s\n", func->unparseToString().c_str()); // output the CFG to a file ofstream fileCFG; fileCFG.open((func->get_declaration()->get_name().getString()+"_cfg.dot").c_str()); cout << " writing to file "<<(func->get_declaration()->get_name().getString()+"_cfg.dot")<<"\n"; cfgToDot(fileCFG, func->get_declaration()->get_name(), func->cfgForBeginning()); fileCFG.close(); } backend(project);*/ //generatePDF ( *project ); // find a declaration for foo() Rose_STL_Container<SgNode*> funcDecls = NodeQuery::querySubTree(project, V_SgFunctionDeclaration); for(Rose_STL_Container<SgNode*>::iterator it = funcDecls.begin(); it!=funcDecls.end(); it++) { SgFunctionDeclaration* decl = isSgFunctionDeclaration(*it); ROSE_ASSERT(decl); if(decl->get_name().getString() == "foo") { fooDecl = decl; break; } } if(!fooDecl) { printf("ERROR: could not find declaration of function foo()!\n"); numFails++; } testParsing(); convertToOMPNormalForm(project, project); testOMPForSensitiveInsertion(); AstTests::runAllTests(project); insertTopBottomOmpDirectives(project, ompUtils::omp_critical, true, &fooCallStmtCreate); insertTopBottomOmpDirectives(project, ompUtils::omp_single, false, &fooCallStmtCreate); // Run internal consistancy tests on AST // // Generate the CFGs of all the functions to ensure that all CFG data is good 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* func = isSgFunctionDefinition(*i); ROSE_ASSERT(func); printf("func = %s\n", func->unparseToString().c_str()); // output the CFG to a file ofstream fileCFG; fileCFG.open((func->get_declaration()->get_name().getString()+"_cfg.dot").c_str()); cout << " writing to file "<<(func->get_declaration()->get_name().getString()+"_cfg.dot")<<"\n"; cfgToDot(fileCFG, func->get_declaration()->get_name(), func->cfgForBeginning()); fileCFG.close(); } backend(project); system("diff rose_test_example.c test_example.valid_rose_output.c > selfTest.out"); struct stat file; stat("selfTest.out",&file); if(file.st_size!=0) { printf("Error: found differences between rose_test_example.c and the canonical test_example.valid_rose_output.c! Details in selfTest.out.\n"); numFails++; } if(numFails==0) cout << "PASSED\n"; else cout << "FAILED!\n"; }
int main(int argc, char** argv) { //Parse command-line options 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 //Insert MM-wrapper header file string mmHeader = po.getMMWrapperHeaderLocation(); insertHeader(mmHeader, PreprocessingInfo::after, false, getGlobalScope(findMain(project))); //Initialize set of system headers & compiler generated vars RegisterPointers::initialize(); //Add calls to registers sizes of static variables RegisterVars rv(project, mmHeader); rv.registerStaticVars(); //Used to accumulate all global variables set<SgInitializedName*> globalVars; //Add wrapper calls to each function/sub-function so that all pointers are registered Rose_STL_Container<SgNode*> pragmas = querySubTree(project, V_SgPragmaDeclaration); Rose_STL_Container<SgNode*>::const_iterator pragmaIt; Rose_STL_Container<SgNode*> funcCalls = querySubTree(project, V_SgFunctionCallExp); SgPragmaDeclaration* pragma; SgStatement* stmt; SgFunctionDeclaration* funcDecl; for(pragmaIt = pragmas.begin(); pragmaIt != pragmas.end(); pragmaIt++) { pragma = isSgPragmaDeclaration(*pragmaIt); ROSE_ASSERT(pragma); PragmaParser pp(pragma); if(pp.isPopcornPragma() && pp.getPragmaType() == PARTITIONED) { //Get function declaration stmt = getNextStatement(pragma); while(!isSgFunctionDeclaration(stmt)) stmt = getNextStatement(stmt); funcDecl = isSgFunctionDeclaration(stmt); ROSE_ASSERT(funcDecl); Pragmas pragmas(funcDecl); //Save global variables saveGlobalVariables(pragmas.getGlobalInputs(), globalVars, pragmas.getFunction()->get_scope()); saveGlobalVariables(pragmas.getGlobalOutputs(), globalVars, pragmas.getFunction()->get_scope()); //Update call sites //TODO I don't think we need this anymore, since all sizes are //handled through the mm_wrapper interface //FunctionCallUpdater fcu(funcDecl, funcCalls); //fcu.updateDeclaration(); //fcu.updateSites(); } } //Register/unregister global variables RegisterVars::registerGlobalVars(globalVars); //Add call to initialize wrapper SgFunctionDeclaration* main = findMain(project); ROSE_ASSERT(main); FunctionCallUpdater::insertInitWrapperCall(main); return backend(project); }
InheritedAttribute visitorTraversal::evaluateInheritedAttribute(SgNode* n, InheritedAttribute inheritedAttribute) { Sg_File_Info* s = n->get_startOfConstruct(); Sg_File_Info* e = n->get_endOfConstruct(); Sg_File_Info* f = n->get_file_info(); for(int x=0; x < inheritedAttribute.depth; ++x) { printf(" "); } if(s != NULL && e != NULL && !isSgLabelStatement(n)) { printf ("%s (%d, %d, %d)->(%d, %d): %s",n->sage_class_name(),s->get_file_id()+1,s->get_raw_line(),s->get_raw_col(),e->get_raw_line(),e->get_raw_col(), verbose ? n->unparseToString().c_str() : "" ); if(isSgAsmDwarfConstruct(n)) { printf(" [DWARF construct name: %s]", isSgAsmDwarfConstruct(n)->get_name().c_str()); } SgExprStatement * exprStmt = isSgExprStatement(n); if(exprStmt != NULL) { printf(" [expr type: %s]", exprStmt->get_expression()->sage_class_name()); SgFunctionCallExp * fcall = isSgFunctionCallExp(exprStmt->get_expression()); if(fcall != NULL) { SgExpression * funcExpr = fcall->get_function(); if(funcExpr != NULL) { printf(" [function expr: %s]", funcExpr->class_name().c_str()); } SgFunctionDeclaration * fdecl = fcall->getAssociatedFunctionDeclaration(); if(fdecl != NULL) { printf(" [called function: %s]", fdecl->get_name().str()); } } } if(isSgFunctionDeclaration(n)) { printf(" [declares function: %s]", isSgFunctionDeclaration(n)->get_name().str()); } SgStatement * sgStmt = isSgStatement(n); if(sgStmt != NULL) { printf(" [scope: %s, %p]", sgStmt->get_scope()->sage_class_name(), sgStmt->get_scope()); } //SgLabelStatement * lblStmt = isSgLabelStatement(n); //if(lblStmt != NULL) { // SgStatement * lblStmt2 = lblStmt->get_statement(); //} } else if (f != NULL) { SgInitializedName * iname = isSgInitializedName(n); if(iname != NULL) { SgType* inameType = iname->get_type(); printf("%s (%d, %d, %d): %s [type: %s", n->sage_class_name(),f->get_file_id()+1,f->get_raw_line(),f->get_raw_col(),n->unparseToString().c_str(),inameType->class_name().c_str()); SgDeclarationStatement * ds = isSgDeclarationStatement(iname->get_parent()); if(ds != NULL) { if(ds->get_declarationModifier().get_storageModifier().isStatic()) { printf(" static"); } } SgArrayType * art = isSgArrayType(iname->get_type()); if(art != NULL) { printf(" %d", art->get_rank()); } printf("]"); if(isSgAsmDwarfConstruct(n)) { printf(" [DWARF construct name: %s]", isSgAsmDwarfConstruct(n)->get_name().c_str()); } } else { printf("%s (%d, %d, %d): %s", n->sage_class_name(),f->get_file_id()+1,f->get_raw_line(),f->get_raw_col(), verbose ? n->unparseToString().c_str() : ""); } } else { printf("%s : %s", n->sage_class_name(), verbose ? n->unparseToString().c_str() : ""); if(isSgAsmDwarfConstruct(n)) { printf(" [DWARF construct name: %s]", isSgAsmDwarfConstruct(n)->get_name().c_str()); } } printf(" succ# %lu", n->get_numberOfTraversalSuccessors()); printf("\n"); return InheritedAttribute(inheritedAttribute.depth+1); }
void InsertFortranContainsStatement::visit ( SgNode* node ) { // DQ (10/3/2008): This bug in OFP is now fixed so no fixup is required. printf ("Error: fixup of contains statement no longer required. \n"); ROSE_ASSERT(false); // DQ (11/24/2007): Output the current IR node for debugging the traversal of the Fortran AST. ROSE_ASSERT(node != NULL); #if 0 Sg_File_Info* fileInfo = node->get_file_info(); printf ("node = %s fileInfo = %p \n",node->class_name().c_str(),fileInfo); if (fileInfo != NULL) { bool isCompilerGenerated = fileInfo->isCompilerGenerated(); std::string filename = fileInfo->get_filenameString(); int line_number = fileInfo->get_line(); int column_number = fileInfo->get_line(); printf ("--- isCompilerGenerated = %s position = %d:%d filename = %s \n",isCompilerGenerated ? "true" : "false",line_number,column_number,filename.c_str()); } #endif SgFunctionDefinition* functionDefinition = isSgFunctionDefinition(node); // This is for handling where CONTAINS is required in a function if (functionDefinition != NULL) { SgBasicBlock* block = functionDefinition->get_body(); SgStatementPtrList & statementList = block->get_statements(); SgStatementPtrList::iterator i = statementList.begin(); bool firstFunctionDeclaration = false; bool functionDeclarationSeen = false; while (i != statementList.end() && firstFunctionDeclaration == false) { SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(*i); // DQ (1/20/2008): Note that entry statements should not cause introduction of a contains statement! if (isSgEntryStatement(functionDeclaration) != NULL) functionDeclaration = NULL; if (functionDeclaration != NULL) { firstFunctionDeclaration = functionDeclarationSeen == false; functionDeclarationSeen = true; if (firstFunctionDeclaration == true) { // Insert a CONTAINS statement. // printf ("Building a contains statement (in function) \n"); SgContainsStatement* containsStatement = new SgContainsStatement(); SageInterface::setSourcePosition(containsStatement); containsStatement->set_definingDeclaration(containsStatement); block->get_statements().insert(i,containsStatement); containsStatement->set_parent(block); ROSE_ASSERT(containsStatement->get_parent() != NULL); } } i++; } } #if 0 // OFP now has better support for the CONTAINS statement so this code is not longer required. // The use of CONTAINS in modules appears to be handled by OFP, so no fixup is required. SgClassDefinition* classDefinition = isSgClassDefinition(node); // This is for handling where CONTAINS is required in a module if (classDefinition != NULL) { SgDeclarationStatementPtrList & statementList = classDefinition->get_members(); SgDeclarationStatementPtrList::iterator i = statementList.begin(); bool firstFunctionDeclaration = false; bool functionDeclarationSeen = false; while (i != statementList.end() && firstFunctionDeclaration == false) { printf ("InsertFortranContainsStatement: *i in statementList in module = %p = %s \n",*i,(*i)->class_name().c_str()); SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(*i); if (functionDeclaration != NULL) { firstFunctionDeclaration = functionDeclarationSeen == false; functionDeclarationSeen = true; if (firstFunctionDeclaration == true) { // Insert a CONTAINS statement. // printf ("Building a contains statement (in module) \n"); SgContainsStatement* containsStatement = new SgContainsStatement(); SageInterface::setSourcePosition(containsStatement); containsStatement->set_definingDeclaration(containsStatement); // This insert function does not set the parent (unlike for SgBasicBlock) classDefinition->get_members().insert(i,containsStatement); containsStatement->set_parent(classDefinition); ROSE_ASSERT(containsStatement->get_parent() != NULL); } } i++; } } #endif }
void POETAstInterface::unparse(POETCode_ext* n, std::ostream& out, int align) { static SgUnparse_Info info; static Unparser* roseUnparser = 0; static POETCode* linebreak=ASTFactory::inst()->new_string("\n"); static POETCode* comma=ASTFactory::inst()->new_string(","); static bool template_only=false; static POETCode* left_over = 0; SgNode * input = (SgNode*)n->get_content(); POETCode* res = POETAstInterface::find_Ast2POET(input); if (res == n) { if (template_only && input->variantT() == V_SgFunctionDeclaration) { left_over = LIST(n,left_over); } else { std::string res = input->unparseToCompleteString(); out << res; } } else { if (roseUnparser == 0) { /* QY/2013: copied from the global unparseFile to use a different ostream and delegate*/ bool UseAutoKeyword = false; bool generateLineDirectives = true; bool useOverloadedOperators = false; bool num = false; bool _this = true; bool caststring = false; bool _debug = false; bool _class = false; bool _forced_transformation_format = false; bool _unparse_includes = false; Unparser_Opt roseOptions( UseAutoKeyword, generateLineDirectives, useOverloadedOperators, num, _this, caststring, _debug, _class, _forced_transformation_format, _unparse_includes ); roseUnparser = new Unparser(&out, "", roseOptions); } switch (input->variantT()) { case V_SgSourceFile: { SgSourceFile* f = isSgSourceFile(input); info.set_current_scope(f->get_globalScope()); template_only = true; code_gen(out, n->get_children(), 0, 0, align); template_only = false; if (left_over != 0) { code_gen(out, left_over, 0, 0, align); left_over = 0; } break; } case V_SgFunctionDeclaration: if (template_only) { left_over = LIST(n, left_over); break; } case V_SgTemplateInstantiationFunctionDecl: { SgFunctionDeclaration* d = isSgFunctionDeclaration(input); roseUnparser->u_exprStmt->unparseAttachedPreprocessingInfo(d,info,PreprocessingInfo::before); POETCode_ext_delegate repl(n, out); roseUnparser->repl = &repl; roseUnparser->u_exprStmt->unparseFuncDeclStmt(d, info); break; } case V_SgFunctionDefinition: { SgStatement* d = isSgStatement(input); POETCode_ext_delegate repl(n, out); roseUnparser->repl = &repl; roseUnparser->u_exprStmt->unparseStatement(d, info); assert(n->get_children() != n); out << "{"; code_gen(out, linebreak, 0, 0, align + 2); code_gen(out, n->get_children(), 0, linebreak, align+2); code_gen(out, linebreak, 0, 0, align); out << "}"; break; } case V_SgPragmaDeclaration: { out << "#pragma "; POETTuple* c = dynamic_cast<POETTuple*>(n->get_children()); assert(c != 0); code_gen(out, c->get_entry(0)); roseUnparser->cur << " "; roseUnparser->cur.insert_newline(1,align); code_gen(out, c->get_entry(1), 0, 0, align); break; } case V_SgForStatement: { out << "for (" ; POETTuple* c = dynamic_cast<POETTuple*>(n->get_children()); assert(c != 0); code_gen(out, c->get_entry(0)); code_gen(out, c->get_entry(1)); out << ";"; code_gen(out, c->get_entry(2)); out << ")"; break; } case V_SgExprStatement: code_gen(out, n->get_children(), 0, 0, align); out << ";"; break; case V_SgTemplateInstantiationMemberFunctionDecl: break; default: std::cerr << "Unsupported unparsing for : " << input->class_name() << input->unparseToString() << "\n"; //assert(0); } } }
// void RemoveConstantFoldedValue::visit ( SgNode* node ) RemoveConstantFoldedValueSynthesizedAttribute RemoveConstantFoldedValue::evaluateSynthesizedAttribute ( SgNode* node, SubTreeSynthesizedAttributes synthesizedAttributeList ) { ROSE_ASSERT(node != NULL); // DQ (3/11/2006): Set NULL pointers where we would like to have none. #if 0 #if 0 // Avoid excessive output. if (isSgFunctionDeclaration(node) == NULL && isSgInitializedName(node) == NULL && isSgFunctionParameterList(node) == NULL) printf ("In RemoveConstantFoldedValue::evaluateSynthesizedAttribute(): node = %p = %s synthesizedAttributeList.size() = %" PRIuPTR " \n",node,node->class_name().c_str(),synthesizedAttributeList.size()); #else printf ("In RemoveConstantFoldedValue::evaluateSynthesizedAttribute(): node = %p = %s synthesizedAttributeList.size() = %" PRIuPTR " \n",node,node->class_name().c_str(),synthesizedAttributeList.size()); #endif #endif // Here we reset the pointer to the constant folded value to be the pointer to the original expression tree. SubTreeSynthesizedAttributes::iterator i = synthesizedAttributeList.begin(); while (i != synthesizedAttributeList.end()) { #if 0 // Avoid excessive output. if (isSgFunctionDeclaration(i->node) == NULL && isSgInitializedName(i->node) == NULL && isSgFunctionParameterList(i->node) == NULL && i->node != NULL) printf ("synthesizedAttribute = %p = %s \n",i->node,(i->node != NULL) ? i->node->class_name().c_str() : "NULL"); #endif // DQ (10/8/2011): Refectored this code so that we could better support chains of original expression trees (see test2011_146.C). handleTheSynthesizedAttribute(node,*i); i++; } // Here we force the nested traversal of the originalExpressionTree, since it is not traversed as part of the AST. // Note that these are not always leaf nodes that we want to interogate (see test2011_140.C). // DQ (9/24/2011): I think this is the wrong place to process this case (see test2011_140.C). // DQ (9/24/2011): We have fixed the AST traversal to no longer traverse originalExpressionTree subtree's (since // it make analysis using the traversal redundant with the constant folded values). // If the current node is an expression and a leaf node of the AST, then check if it has an originalExpressionTree, // since we no longer traverse the originalExpressionTree as part of the definition of the AST. // SgExpression* leafExpression = (synthesizedAttributeList.empty() == true) ? isSgExpression(node) : NULL; SgExpression* expression = isSgExpression(node); if (expression != NULL) { #if 0 printf ("In RemoveConstantFoldedValue::evaluateSynthesizedAttribute(): Found an expression \n"); #endif SgExpression* originalExpressionTree = expression->get_originalExpressionTree(); if (originalExpressionTree != NULL) { #if 0 printf ("Found an expression with a valid originalExpressionTree\n"); #endif // Make sure that the traversal will see the nested subtrees of any originalExpressionTree (since they may have constant folded subexpresions). RemoveConstantFoldedValue nestedOriginalExpressionTreeTraversal; RemoveConstantFoldedValueSynthesizedAttribute nestedSynthesizedAttribute = nestedOriginalExpressionTreeTraversal.traverse(originalExpressionTree); #if 0 // DQ (10/8/2011): We should not handl this here, I think. handleTheSynthesizedAttribute(node,nestedSynthesizedAttribute); #endif #if 0 printf ("DONE: Found an expression with a valid originalExpressionTree nestedSynthesizedAttribute \n"); #endif } } return RemoveConstantFoldedValueSynthesizedAttribute(node); }
SgFunctionDeclaration * CudaOutliner::generateFunction ( SgBasicBlock* s, const string& func_name_str, ASTtools::VarSymSet_t& syms, MintHostSymToDevInitMap_t hostToDevVars, const ASTtools::VarSymSet_t& pdSyms, const ASTtools::VarSymSet_t& psyms, SgScopeStatement* scope) { //Create a function named 'func_name_str', with a parameter list from 'syms' //pdSyms specifies symbols which must use pointer dereferencing if replaced during outlining, //only used when -rose:outline:temp_variable is used //psyms are the symbols for OpenMP private variables, or dead variables (not live-in, not live-out) ROSE_ASSERT ( s && scope); ROSE_ASSERT(isSgGlobal(scope)); // step 1: perform necessary liveness and side effect analysis, if requested. // --------------------------------------------------------- std::set< SgInitializedName *> liveIns, liveOuts; // Collect read-only variables of the outlining target std::set<SgInitializedName*> readOnlyVars; if (Outliner::temp_variable||Outliner::enable_classic) { SgStatement* firstStmt = (s->get_statements())[0]; if (isSgForStatement(firstStmt)&& Outliner::enable_liveness) { LivenessAnalysis * liv = SageInterface::call_liveness_analysis (SageInterface::getProject()); SageInterface::getLiveVariables(liv, isSgForStatement(firstStmt), liveIns, liveOuts); } SageInterface::collectReadOnlyVariables(s,readOnlyVars); if (0)//Outliner::enable_debug) { cout<<" INFO:Mint: CudaOutliner::generateFunction()---Found "<<readOnlyVars.size()<<" read only variables..:"; for (std::set<SgInitializedName*>::const_iterator iter = readOnlyVars.begin(); iter!=readOnlyVars.end(); iter++) cout<<" "<<(*iter)->get_name().getString()<<" "; cout<<endl; cout<<"CudaOutliner::generateFunction() -----Found "<<liveOuts.size()<<" live out variables..:"; for (std::set<SgInitializedName*>::const_iterator iter = liveOuts.begin(); iter!=liveOuts.end(); iter++) cout<<" "<<(*iter)->get_name().getString()<<" "; cout<<endl; } } //step 2. Create function skeleton, 'func'. // ----------------------------------------- SgName func_name (func_name_str); SgFunctionParameterList *parameterList = buildFunctionParameterList(); SgType* func_Type = SgTypeVoid::createType (); SgFunctionDeclaration* func = createFuncSkeleton (func_name, func_Type ,parameterList, scope); //adds __global__ keyword func->get_functionModifier().setCudaKernel(); ROSE_ASSERT (func); // Liao, 4/15/2009 , enforce C-bindings for C++ outlined code // enable C code to call this outlined function // Only apply to C++ , pure C has trouble in recognizing extern "C" // Another way is to attach the function with preprocessing info: // #if __cplusplus // extern "C" // #endif // We don't choose it since the language linkage information is not explicit in AST if ( SageInterface::is_Cxx_language() || is_mixed_C_and_Cxx_language() \ || is_mixed_Fortran_and_Cxx_language() || is_mixed_Fortran_and_C_and_Cxx_language() ) { // Make function 'extern "C"' func->get_declarationModifier().get_storageModifier().setExtern(); func->set_linkage ("C"); } //step 3. Create the function body // ----------------------------------------- // Generate the function body by deep-copying 's'. SgBasicBlock* func_body = func->get_definition()->get_body(); ROSE_ASSERT (func_body != NULL); // This does a copy of the statements in "s" to the function body of the outlined function. ROSE_ASSERT(func_body->get_statements().empty() == true); // This calls AST copy on each statement in the SgBasicBlock, but not on the block, so the // symbol table is setup by AST copy mechanism and it is setup properly SageInterface::moveStatementsBetweenBlocks (s, func_body); if (Outliner::useNewFile) ASTtools::setSourcePositionAtRootAndAllChildrenAsTransformation(func_body); //step 4: variable handling, including: // ----------------------------------------- // create parameters of the outlined functions // add statements to unwrap the parameters if wrapping is requested // add repacking statements if necessary // replace variables to access to parameters, directly or indirectly // do not wrap parameters Outliner::enable_classic = true; functionParameterHandling(syms, hostToDevVars, pdSyms, psyms, readOnlyVars, liveOuts, func); ROSE_ASSERT (func != NULL); // Retest this... // Copied the similar fix from the rose outliner // Liao 2/6/2013. It is essential to rebuild function type after the parameter list is finalized. // The original function type was build using empty parameter list. SgType* stale_func_type = func->get_type(); func->set_type(buildFunctionType(func->get_type()->get_return_type(), buildFunctionParameterTypeList(func->get_parameterList()))); SgFunctionDeclaration* non_def_func = isSgFunctionDeclaration(func->get_firstNondefiningDeclaration ()) ; ROSE_ASSERT (non_def_func != NULL); ROSE_ASSERT (stale_func_type == non_def_func->get_type()); non_def_func->set_type(func->get_type()); ROSE_ASSERT(func->get_definition()->get_body()->get_parent() == func->get_definition()); ROSE_ASSERT(scope->lookup_function_symbol(func->get_name())); return func; }
//! init virtual fucntion inheritance void Classhierarchy::inheritVirtualFunctions() { // prepare LUT for multiple declarations //map<SgNode *, set<SgNode *> > multDec; property_map< dbgType, boost::vertex_classhierarchy_t>::type chMap = boost::get( boost::vertex_classhierarchy, *this ); graph_traits< dbgType >::vertex_iterator vi,vend; tie(vi,vend) = vertices( *this ); //graph_traits< dbgType >::vertex_descriptor par=*vi, succ=*vi; // output info for(; vi!=vend; vi++) { //cerr << " BCH v i"<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; for( set<SgNode*>::iterator chd= chMap[*vi].defined.begin(); chd!= chMap[*vi].defined.end(); chd++) { SgFunctionDeclaration *funcDec = isSgFunctionDeclaration( *chd ); //cerr << " BCH chd " << funcDec->get_mangled_name().str()<< endl; // debug //cerr << " BCH chd " << funcDec->get_mangled_name().str()<< " "<< (int)funcDec->get_type() << endl; // debug } } // search for multiple declarations tie(vi,vend) = vertices( *this ); for(; vi!=vend; vi++) { for(set<SgNode*>::iterator chd= chMap[*vi].defined.begin(); chd!= chMap[*vi].defined.end(); chd++) { SgFunctionDeclaration *funcDec = isSgFunctionDeclaration( *chd ); bool found = true; while(found) { found = false; for(set<SgNode*>::iterator chdComp = chMap[*vi].defined.begin(); (chdComp!= chMap[*vi].defined.end())&&(!found); ) { SgFunctionDeclaration *compDec = isSgFunctionDeclaration( *chdComp ); if(chdComp != chd) { //if( compDec->get_type() == funcDec->get_type() ) { // ??? TODO fix type comparison? if(compareFunctionDeclarations(compDec, funcDec)) { //cerr << " BCH REM " << funcDec->get_mangled_name().str()<< " " << compDec->get_mangled_name().str() << endl; // debug chMap[*vi].multDeclarations[ funcDec ].insert( compDec ); found = true; chMap[*vi].defined.erase( chdComp ); // should return new iterator in newer STL standard?? //chVertexData::iterator chdComp2 = (chMap[*vi]).erase( chdComp ); //chdComp = chdComp2; //cerr << " BCH removing i"<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; } } if(!found) chdComp++; } } // found } //if( get( vertex_dbg_data, *this , *vi).get_id() == edges[i].get_sourceId() ) { //par = *vi; //parFound = true; //} } //typedef std::deque< boostVert > container; //cerr << " TOPO START " << endl; std::deque< dbgVertex > torder; try { boost::topological_sort(*this, std::back_inserter(torder)); } catch(boost::not_a_dag) { cerr << "CH - BOOST ERROR: NOT A DAG!!!!!??? " << endl; assert( false ); return; } //cerr << " TOPO END " << endl; //cerr << " -- " << endl; // debug for( std::deque< dbgVertex >::iterator vi=torder.begin(); vi!=torder.end(); vi++) { dbgVertex srcVert = *vi; // current vertex in the topo order //cerr << "XTOPO v i"<< get(vertex_index,*this,*vi)<< " i1" << get(vertex_index1, *this, *vi)<<","<< get(vertex_name, *this, *vi) << endl; for(set<SgNode*>::iterator chd= chMap[srcVert].defined.begin(); chd!= chMap[srcVert].defined.end(); chd++) { SgFunctionDeclaration *defMF = isSgFunctionDeclaration( *chd ); bool erased = true; while(erased) { erased = false; for(set<SgNode*>::iterator inhd= chMap[srcVert].inherited.begin(); inhd!= chMap[srcVert].inherited.end() && (!erased); ) { SgFunctionDeclaration *inhMF = isSgFunctionDeclaration( *inhd ); if(compareFunctionDeclarations(defMF, inhMF)) { // own function overrides, so delete old one chMap[srcVert].inherited.erase( *inhd ); erased = true; //cerr << " TOPO MF:"<< defMF->get_mangled_name().str()<< " overrides MF:"<< inhMF->get_mangled_name().str() << endl; // debug } if(!erased) inhd++; } } } // add to inherited functions for(set<SgNode*>::iterator chd= chMap[srcVert].defined.begin(); chd!= chMap[srcVert].defined.end(); chd++) { chMap[srcVert].inherited.insert( *chd ); } // inherit own methods to child classes graph_traits<dbgType>::in_edge_iterator ii,iend; tie(ii,iend) = in_edges(*vi, *this); for(; ii!=iend; ii++) { //dbgVertex srcVert = source(*ii,*this); // methods inherited from this class to the other one dbgVertex child = source(*ii, *this); //cerr << " T inherits to "<< get(vertex_index,*this,child)<< " i1" << get(vertex_index1, *this, child)<<","<< get(vertex_name, *this, child) << endl; //for(set<SgNode*>::iterator chd= chMap[srcVert].defined.begin(); chd!= chMap[srcVert].defined.end(); chd++) { for(set<SgNode*>::iterator chd= chMap[srcVert].inherited.begin(); chd!= chMap[srcVert].inherited.end(); chd++) { SgFunctionDeclaration *inhFunc = isSgFunctionDeclaration( *chd ); bool virt = false; //cerr << " TOPO v srch1" << endl; if(inhFunc->isVirtual()) virt = true; // also check multiple declarations //cerr << " TOPO v srch2" << endl; if(!virt) { for(set<SgNode *>::iterator si=chMap[srcVert].multDeclarations[inhFunc].begin(); si != chMap[srcVert].multDeclarations[inhFunc].end(); si++) { SgFunctionDeclaration *inhDup = isSgFunctionDeclaration( *si ); if(inhDup->isVirtual()) virt = true; //cerr << " TOPO v srch "<< inhDup->get_mangled_name().str() << endl; // debug } } // TODO check virtual inheritance? other declarations? if(virt) { //cerr << " VIRT " << inhFunc->get_mangled_name().str() << endl; // debug // and now... ?? } chMap[child].inherited.insert( inhFunc ); } //cerr << " BOOST v <<< " << get(vertex_index1, *this, boost::target(*ii,*this) )<<","<< get(vertex_name, *this, boost::target(*ii,*this) ) << endl; // debug } } // add own methods to all inherited ones for( std::deque< dbgVertex >::iterator vi=torder.begin(); vi!=torder.end(); vi++) { } }