Exemplo n.º 1
0
void
ReportUnsharedDeclarationsTraversal::visit ( SgNode* node)
   {
     ROSE_ASSERT(node != NULL);
#if 0
     printf ("ReportUnsharedDeclarationsTraversal::visit: node = %p = %s \n",node,node->class_name().c_str());
#endif

     SgDeclarationStatement* declaration = isSgDeclarationStatement(node);
     if (declaration != NULL)
        {
          bool skipTest = isSgFunctionParameterList(declaration) || isSgNamespaceDeclarationStatement(declaration) || isSgCtorInitializerList(declaration);
          if (skipTest == false && declaration->get_startOfConstruct()->isShared() == false)
             {
               printf ("Found a declaration which is not shared declaration = %p = %s = %s \n",declaration,declaration->class_name().c_str(),SageInterface::get_name(declaration).c_str());
             }
        }

#if 0
     SgSupport* support = isSgSupport(node);
     if (support != NULL)
        {
          bool skipTest = !(isSgTemplateArgument(support));
          if (skipTest == false && support->get_file_info()->isShared() == false)
             {
               printf ("Found a support IR node which is not shared = %p = %s = %s \n",support,support->class_name().c_str(),SageInterface::get_name(support).c_str());
             }
        }
#endif

#if 0
     printf ("ReportUnsharedDeclarationsTraversal::visit(): node = %p = %s \n",node,node->class_name().c_str());
#endif
   }
int
main(int argc, char* argv[])
   {
     SgProject* project = frontend(argc, argv);

     std::vector<SgIfStmt*> ifs = SageInterface::querySubTree<SgIfStmt>(project, V_SgIfStmt);
     BOOST_FOREACH(SgIfStmt* if_stmt, ifs)
        {
          if (SgExpression *se = isSgExprStatement(if_stmt->get_conditional())->get_expression())
             {
               cout << "--->" << se->unparseToString() << "<---" << endl;

               Rose_STL_Container<SgNode*> variableList = NodeQuery::querySubTree(se, V_SgVarRefExp);
               for (Rose_STL_Container<SgNode*>::iterator i = variableList.begin(), end = variableList.end(); i != end; i++)
                  {
                    SgVarRefExp *varRef = isSgVarRefExp(*i);
                    SgVariableSymbol *currSym = varRef->get_symbol();
                    cout << "Looking at: --|" << currSym->get_name().str() << "|--" << endl;

                    SgDeclarationStatement *decl = currSym->get_declaration()->get_declaration();

                    cout << "declaration: " << decl->unparseToString() << endl;

                    SgConstVolatileModifier cvm = decl->get_declarationModifier().get_typeModifier().get_constVolatileModifier();
                    bool constness = cvm.isConst();

                    cout << "constness via isConst(): " << constness << endl;
                    cout << cvm.displayString() << endl;
                  }
             }
        }

     return 0;
   }
void
FixupStorageAccessOfForwardTemplateDeclarations::visit (SgNode* node)
   {
     ROSE_ASSERT(node != NULL);

  // These are output a static functions to avoid being defined using multiple symbols at link time.
  // This is a temporary fix until we get the better prelinker written.
     SgTemplateInstantiationFunctionDecl* functionDeclaration = isSgTemplateInstantiationFunctionDecl(node);
     if (functionDeclaration != NULL)
        {
          SgDeclarationStatement* definingDeclaration = functionDeclaration->get_definingDeclaration();
          if (definingDeclaration != NULL)
             {
               bool isStatic = definingDeclaration->get_declarationModifier().get_storageModifier().isStatic();
               if (isStatic == true)
                  {
                 // This is a static function so make sure that all declarations associated with it 
                 // (e.g. forward declarations) are marked the same.
                    bool currentDeclarationIsStatic = functionDeclaration->get_declarationModifier().get_storageModifier().isStatic();
                    if (currentDeclarationIsStatic == false)
                       {
                         if ( SgProject::get_verbose() >= AST_FIXES_VERBOSE_LEVEL )
                              printf ("AST fixup: Changing non-defining declaration (%p) to match defining declaration (static)\n",functionDeclaration);
                         functionDeclaration->get_declarationModifier().get_storageModifier().setStatic();
                       }
                  }
             }
        }
   }
Exemplo n.º 4
0
list<DoxygenComment *> *
Doxygen::getCommentList(SgDeclarationStatement *ds)
{
    SgDeclarationStatement *dxDs = Doxygen::getDoxygenAttachedDeclaration(ds);
    DoxygenCommentListAttribute *attr = dynamic_cast<DoxygenCommentListAttribute *>
                                        (dxDs->getAttribute("DoxygenCommentList"));
    ROSE_ASSERT(attr);
    return &(attr->commentList);
}
Exemplo n.º 5
0
Arquivo: RoseToTerm.C Projeto: 8l/rose
/**
 * class: SgVarRefExp
 * term: var_ref_exp_annotation(tpe,name,static,scope)
 * arg tpe: type
 * arg name: name
 * arg static: wether the declaration was static
 * arg scope: scope name (either from a namespace, a class or "null")
 */
PrologCompTerm* 
RoseToTerm::getVarRefExpSpecific(SgVarRefExp* vr) {
  SgInitializedName* n = vr->get_symbol()->get_declaration();
  /* type: in general, this can be taken "as is" from the ROSE AST. However,
   * ROSE (up to 0.9.4a-8xxx at least) gets a detail wrong: a declaration
   * like "int arr[]" as a function parameter declares a *pointer*, not an
   * array. Thus we check whether the variable might be of this sort, and if
   * yes, we must make a pointer type for it. */
  PrologTerm* typeSpecific = NULL;
  SgInitializedName* vardecl = vr->get_symbol()->get_declaration();
  SgType* t = vr->get_type()->stripType(SgType::STRIP_MODIFIER_TYPE
                                      | SgType::STRIP_REFERENCE_TYPE
                                      | SgType::STRIP_TYPEDEF_TYPE);
  if (isSgFunctionParameterList(vardecl->get_parent()) && isSgArrayType(t)) {
    SgType* baseType = isSgArrayType(t)->get_base_type();
    PrologTerm* baseTypeSpecific = getTypeSpecific(baseType);
    typeSpecific = new PrologCompTerm("pointer_type", /*1,*/ baseTypeSpecific);
  } else {
    typeSpecific = getTypeSpecific(n->get_typeptr());
  }
  /* static? (relevant for unparsing if scope is a class)*/
  PrologTerm *isStatic;
  SgDeclarationStatement* vdec = n->get_declaration();
  if (vdec != NULL) {
    isStatic = 
      getEnum(vdec->get_declarationModifier().get_storageModifier().isStatic(),
	      re.static_flags);
  } else {
    isStatic = getEnum(0, re.static_flags);
  }
  PrologTerm* scope;
  if (vdec != NULL) {
    /* named scope or irrelevant?*/
    if (SgNamespaceDefinitionStatement* scn = 
	isSgNamespaceDefinitionStatement(vdec->get_parent())) {
      scope = getNamespaceScopeName(scn);
    } else if (SgClassDefinition* scn = 
	       isSgClassDefinition(vdec->get_parent())) {
      scope = getClassScopeName(scn);
    } else {
      scope = new PrologAtom("null");
    }
  } else {
    scope = new PrologAtom("null");
  }

  return new PrologCompTerm
    ("var_ref_exp_annotation", //5,
     typeSpecific,
     /* name*/ new PrologAtom(n->get_name().getString()),
     isStatic,
     scope,
     PPI(vr));
}
Exemplo n.º 6
0
void
FixupTypesTraversal::visit ( SgNode* node)
   {
     ROSE_ASSERT(node != NULL);
  // printf ("FixupTypesTraversal::visit: node = %p = %s \n",node,node->class_name().c_str());

     SgDeclarationStatement* declaration = isSgDeclarationStatement(node);
     if (declaration != NULL)
        {
#if 0
          printf ("FixupTypesTraversal::visit: declaration = %p = %s \n",declaration,declaration->class_name().c_str());
#endif
          NormalizeTypesTraversal::DeclarationTypeMultiMapType::iterator lowerBound = declarationTypeMultiMap.lower_bound(declaration);
          NormalizeTypesTraversal::DeclarationTypeMultiMapType::iterator upperBound = declarationTypeMultiMap.upper_bound(declaration);

       // Increment the upperBound just past the end
       // if (upperBound != declarationTypeMultiMap.end())
       //      upperBound++;
       // if ( lowerBound != declarationTypeMultiMap.end() )
#if 0
          if ( upperBound != declarationTypeMultiMap.end() && (lowerBound != upperBound) )
             {
               while (lowerBound != upperBound)
                  {
                    printf ("loop: lowerBound = %p = %s \n",lowerBound->second,lowerBound->second->class_name().c_str());
                    lowerBound++;
                  }

               if (upperBound != declarationTypeMultiMap.end())
                    printf ("end: upperBound = %p = %s \n",upperBound->second,upperBound->second->class_name().c_str());
             }
#endif
       // if ( upperBound != declarationTypeMultiMap.end() && (lowerBound != upperBound) )
       // if ( upperBound != declarationTypeMultiMap.end() )
          NormalizeTypesTraversal::DeclarationTypeMultiMapType::iterator i = lowerBound;
          if ( i != declarationTypeMultiMap.end() )
             {
            // There must be at least two reference to what we want to be a shared type
            // printf ("end: upperBound = %p = %s \n",upperBound->second,upperBound->second->class_name().c_str());
            // printf ("loop: lowerBound = %p = %s \n",lowerBound->second,lowerBound->second->class_name().c_str());
               while (i != upperBound)
                  {
#if 0
                    printf ("loop: i = %p = %s \n",i->second,i->second->class_name().c_str());
#endif
                    i++;
                  }
             }
        }
   }
Exemplo n.º 7
0
        virtual void visit(SgNode *n)
        {
            SgDeclarationStatement *st = isSgDeclarationStatement(n);
            if (!st)
            {
                return;
            }
            if (!isRecognizedDeclaration(st))
            {
                return;
            }

            string proto = getProtoName(st);
            SgDeclarationStatement *dxSt = getDoxygenAttachedDeclaration(st);

            if ((*symTab)[proto].count(dxSt) == 0)
            {
                DoxygenCommentListAttribute *attr = new DoxygenCommentListAttribute();
                // King84 (2010.08.03) : This seems to be called with the same node multiple times.
                // From what I can tell, this is because a single function has been documented multiple times.
                // At the moment this function is AssemblerX86::AssemblerX86() from src/frontend/Disassemblers/AssemblerX86.h
                // For now, we will print out a warning and use the new documentation (instead of addNewAttribute we use setAttribute).
                if (dxSt->attributeExists("DoxygenCommentList"))
                {
                    std::cerr << "Warning: Multiple Doxygen comments found for function " << dxSt->get_mangled_name().getString() << " at file " << dxSt->get_file_info()->get_filenameString() << ":" << dxSt->get_file_info()->get_line() << "," << dxSt->get_file_info()->get_col() << ".  Picking the last." << std::endl;
                }
                dxSt->setAttribute("DoxygenCommentList", attr);
//                      dxSt->addNewAttribute("DoxygenCommentList", attr);
                (*symTab)[proto][dxSt] = &(attr->commentList);
            }
            list<DoxygenComment *> *commentList = (*symTab)[proto][dxSt];

            AttachedPreprocessingInfoType *info = st->getAttachedPreprocessingInfo();
            if (info)
            {
                for (AttachedPreprocessingInfoType::iterator i = info->begin(); i != info->end(); ++i)
                {
                    PreprocessingInfo *pi = *i;
                    if (pi->getRelativePosition() == PreprocessingInfo::before && DoxygenComment::isDoxygenComment(pi))
                    {
                        commentList->push_back(new DoxygenComment(st, pi));
                    }
                }
            }
        }
Exemplo n.º 8
0
int main(int argc, char* argv[]) {
	SgProject* proj = frontend(argc,argv);
	SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj);
	SgFunctionDefinition* mainDef = mainDecl->get_definition();
//	std::vector<SgNode*> dotExps = NodeQuery::querySubTree(mainDef, V_SgDotExp);
	std::vector<SgNode*> varRefs = NodeQuery::querySubTree(mainDef,V_SgVarRefExp);
	int classExps = 0;
	for (unsigned int i = 0; i < varRefs.size(); i++) {
		if (isSgClassType(isSgVarRefExp(varRefs[i])->get_type())) {
			SgClassType* ct = isSgClassType(isSgVarRefExp(varRefs[i])->get_type());
			std::cout << "name of ref: " << isSgVarRefExp(varRefs[i])->get_symbol()->get_name().getString() << std::endl;
			if (SageInterface::isStructType(ct)) {
			SgDeclarationStatement* decl = isSgType(ct)->getAssociatedDeclaration();
			SgDeclarationStatement* defining_decl = decl->get_definingDeclaration();
			if (!(defining_decl->isNameOnly())) {	
				if (isSgClassDeclaration(defining_decl)) {
				if (isSgClassDeclaration(defining_decl)->get_definition()) {
				SgDeclarationStatementPtrList member_stats = isSgClassDeclaration(defining_decl)->get_definition()->get_members();
				SgDeclarationStatementPtrList::iterator j = member_stats.begin();
				for (; j != member_stats.end(); j++) {
					SgDeclarationStatement* d = isSgDeclarationStatement(*j);
					std::cout << "decl stat name: " << d->class_name() << std::endl;
					SgInitializedNamePtrList init_lst = isSgVariableDeclaration(d)->get_variables();
					SgInitializedNamePtrList::iterator k = init_lst.begin();
					std::cout << "variables in initialized name ptr list..." << std::endl;
					for (; k != init_lst.end(); k++) {
						std::cout << isSgInitializedName(*k)->get_name().getString() << std::endl;
						std::cout << isSgInitializedName(*k)->get_type()->class_name() << std::endl;
					}
				}
					
				classExps+=1;
				}
				}
			}
			
			
			}
		}
	}	
	std::cout << "num class_exp: " << classExps << std::endl;
	return 0;
}	
Exemplo n.º 9
0
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.
Exemplo n.º 10
0
Arquivo: RoseToTerm.C Projeto: 8l/rose
PrologCompTerm* 
RoseToTerm::getVariableDeclarationSpecific(SgVariableDeclaration* d) {
  ROSE_ASSERT(d != NULL);
  /* add base type forward declaration */
  SgNode *baseTypeDecl = NULL;
  if (d->get_variableDeclarationContainsBaseTypeDefiningDeclaration()) {
    baseTypeDecl = d->get_baseTypeDefiningDeclaration();
  } else {
    /* The complication is that in the AST, the type declaration member is
     * only set if it is a type definition, not if it is a forward
     * declaration. So we need to check whether the base type (possibly
     * below layers of pointers) is a class type, and whether its first
     * declaration appears to be hidden here in the variable declaration. */
    SgClassType *ctype = isSgClassType(d->get_variables().front()
                                       ->get_type()->findBaseType());
    if (ctype) {
      /* See if the type is declared in the scope where it belongs. If no,
       * then the declaration is apparently inside this variable
       * declaration, so we add it as a subterm. */
      SgDeclarationStatement *cdecl = ctype->get_declaration();
      SgSymbol *symbol = cdecl->get_symbol_from_symbol_table();
      if (!typeWasDeclaredBefore(
           getTypeSpecific(symbol->get_type())->getRepresentation())) {
        baseTypeDecl = cdecl;
      }
    }
  }

  return new PrologCompTerm
    ("variable_declaration_specific", //3,
     getDeclarationModifierSpecific(&(d->get_declarationModifier())),
     (baseTypeDecl != NULL
      ? traverseSingleNode(baseTypeDecl)
      : new PrologAtom("null")),
     PPI(d));
}
Exemplo n.º 11
0
  //return name for various named constructs
  string roseNode::getName() const
  {
    string result;
    ROSE_ASSERT(mNode!=NULL);
    // only declarations with symbols in ROSE have user-level names
    // need to double check this
    if (isSgFile(mNode)) 
    {
      return isSgFile(mNode)->get_file_info()->get_filenameString ();
    } 
    else  if (isSgProject(mNode))
    { // No name field for rose projects
      return "";
    }
    else if (isSgFunctionDefinition(mNode))
    {
      SgFunctionDefinition* def = isSgFunctionDefinition(mNode);
      return (def->get_declaration()->search_for_symbol_from_symbol_table()->get_name()).getString();
    }  

    SgDeclarationStatement* decl = isSgDeclarationStatement(mNode); 
    if (decl)
    {
      switch (decl->variantT())
      { 
        case V_SgVariableDeclaration:
          {
            SgVariableSymbol * symbol=SageInterface::getFirstVarSym(isSgVariableDeclaration(decl));
            result = symbol->get_name();
            break;
          }
        case V_SgClassDeclaration:
        case V_SgTypedefDeclaration:
        case V_SgNamespaceDeclarationStatement:
        case V_SgFunctionDeclaration:
        case V_SgTemplateDeclaration:
        case V_SgMemberFunctionDeclaration:
          {
            result = (decl->search_for_symbol_from_symbol_table()->get_name()).getString();
            ROSE_ASSERT(result.length()!=0);
            break;
          }
         // No explicit name available
        case V_SgCtorInitializerList:
        case V_SgPragmaDeclaration:
        case V_SgFunctionParameterList:
        case V_SgUsingDirectiveStatement:
        case V_SgStmtDeclarationStatement:
          {
            break;
          }
        default:
          {
            cerr<<"error, unhandled declaration type in roseNode::getName(): "<<mNode->class_name()<<endl;
            ROSE_ASSERT(false);
            break;
          }
      }// end switch
    }
    return result ;
  }
void
FixupAstSymbolTablesToSupportAliasedSymbols::visit ( SgNode* node )
   {
  // DQ (11/24/2007): Output the current IR node for debugging the traversal of the Fortran AST.
#if ALIAS_SYMBOL_DEBUGGING
     printf ("In FixupAstSymbolTablesToSupportAliasedSymbols::visit() (preorder AST traversal) node = %p = %s \n",node,node->class_name().c_str());
#endif

#if 0
  // DQ (7/23/2011): New support for linking namespaces sharing the same name (mangled name).
  // std::map<SgName,std::vector<SgNamespaceDefinition*> > namespaceMap;
     SgNamespaceDefinitionStatement* namespaceDefinition = isSgNamespaceDefinitionStatement(node);
     if (namespaceDefinition != NULL)
        {
       // DQ (7/23/2011): Assemble namespaces with the same name into vectors defined in the map 
       // accessed using the name of the namespace as a key.

#error "DEAD CODE"

          SgName name = namespaceDefinition->get_namespaceDeclaration()->get_name();
#if ALIAS_SYMBOL_DEBUGGING
          printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: namespace definition found for name = %s #symbols = %d \n",name.str(),namespaceDefinition->get_symbol_table()->size());
#endif
       // It is important to use mangled names to define unique names when namespaces are nested.
          SgName mangledNamespaceName = namespaceDefinition->get_namespaceDeclaration()->get_mangled_name();
#if ALIAS_SYMBOL_DEBUGGING
          printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: namespace definition associated mangled name = %s \n",mangledNamespaceName.str());
#endif
       // DQ (7/23/2011): Fixup the name we use as a key in the map to relect that some namespaces don't have a name.
          if (name == "")
             {
            // Modify the mangled name to reflect the unnamed namespace...

#if ALIAS_SYMBOL_DEBUGGING
               printf ("Warning in FixupAstSymbolTablesToSupportAliasedSymbols::visit(): Unnamed namespaces shuld be mangled to reflect the lack of a name \n");
#endif
               mangledNamespaceName += "_unnamed_namespace";
             }

#if ALIAS_SYMBOL_DEBUGGING
          printf ("namespace definition associated mangled name = %s \n",mangledNamespaceName.str());
#endif
#if ALIAS_SYMBOL_DEBUGGING
          printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: associated mangled name = %s namespaceMap size = %" PRIuPTR " \n",mangledNamespaceName.str(),namespaceMap.size());
#endif
          std::map<SgName,std::vector<SgNamespaceDefinitionStatement*> >::iterator i = namespaceMap.find(mangledNamespaceName);
          if (i != namespaceMap.end())
             {
               std::vector<SgNamespaceDefinitionStatement*> & namespaceVector = i->second;
#if ALIAS_SYMBOL_DEBUGGING
               printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: (found an entry): Namespace vector size = %" PRIuPTR " \n",namespaceVector.size());
#endif
            // Testing each entry...
               for (size_t j = 0; j < namespaceVector.size(); j++)
                  {
                    ROSE_ASSERT(namespaceVector[j] != NULL);
                    SgName existingNamespaceName = namespaceVector[j]->get_namespaceDeclaration()->get_name();
#if ALIAS_SYMBOL_DEBUGGING
                    printf ("Existing namespace (SgNamespaceDefinitionStatement) %p = %s \n",namespaceVector[j],existingNamespaceName.str());
#endif
                    if (j > 0)
                       {
                         ROSE_ASSERT(namespaceVector[j]->get_previousNamespaceDefinition() != NULL);
                       }

                    if (namespaceVector.size() > 1 && j < namespaceVector.size() - 2)
                       {
                         ROSE_ASSERT(namespaceVector[j]->get_nextNamespaceDefinition() != NULL);
                       }
                  }

#error "DEAD CODE"

               size_t namespaceListSize = namespaceVector.size();
               if (namespaceListSize > 0)
                  {
                    size_t lastNamespaceIndex = namespaceListSize - 1;

                 // DQ (5/9/2013): Before setting these, I think they should be unset (to NULL values).
                 // ROSE_ASSERT(namespaceVector[lastNamespaceIndex]->get_nextNamespaceDefinition() == NULL);
                 // ROSE_ASSERT(namespaceDefinition->get_previousNamespaceDefinition() == NULL);
                 // ROSE_ASSERT(namespaceVector[lastNamespaceIndex]->get_nextNamespaceDefinition() == NULL);
                    ROSE_ASSERT(namespaceDefinition->get_previousNamespaceDefinition() != NULL);

                 // namespaceVector[lastNamespaceIndex]->set_nextNamespaceDefinition(namespaceDefinition);
#if 1
                    printf ("namespaceVector[lastNamespaceIndex]->get_nextNamespaceDefinition() = %p \n",namespaceVector[lastNamespaceIndex]->get_nextNamespaceDefinition());
#endif
                    if (namespaceVector[lastNamespaceIndex]->get_nextNamespaceDefinition() == NULL)
                       {
                         namespaceVector[lastNamespaceIndex]->set_nextNamespaceDefinition(namespaceDefinition);
                       }
                      else
                       {
                      // DQ (5/9/2013): If this is already set then make sure it was set to the correct value.
                         ROSE_ASSERT(namespaceVector[lastNamespaceIndex]->get_nextNamespaceDefinition() == namespaceDefinition);
                       }

#error "DEAD CODE"

                 // DQ (5/9/2013): If this is already set then make sure it was set to the correct value.
                 // namespaceDefinition->set_previousNamespaceDefinition(namespaceVector[lastNamespaceIndex]);
                    ROSE_ASSERT(namespaceDefinition->get_previousNamespaceDefinition() != NULL);
                    ROSE_ASSERT(namespaceDefinition->get_previousNamespaceDefinition() == namespaceVector[lastNamespaceIndex]);

                 // DQ (5/9/2013): I think I can assert this.
                    ROSE_ASSERT(namespaceVector[lastNamespaceIndex]->get_namespaceDeclaration()->get_name() == namespaceDefinition->get_namespaceDeclaration()->get_name());
                    ROSE_ASSERT(namespaceDefinition->get_previousNamespaceDefinition() != NULL);
#if 1
                    printf ("namespaceDefinition = %p namespaceDefinition->get_nextNamespaceDefinition() = %p \n",namespaceDefinition,namespaceDefinition->get_nextNamespaceDefinition());
#endif
                 // ROSE_ASSERT(namespaceDefinition->get_nextNamespaceDefinition()     == NULL);
                 // ROSE_ASSERT(namespaceVector[lastNamespaceIndex]->get_nextNamespaceDefinition() == NULL);
                  }

            // Add the namespace matching a previous name to the list.
               namespaceVector.push_back(namespaceDefinition);

#error "DEAD CODE"

            // Setup scopes as sources and distinations of alias symbols.
               SgNamespaceDefinitionStatement* referencedScope = namespaceDefinition->get_previousNamespaceDefinition();
               ROSE_ASSERT(referencedScope != NULL);
               SgNamespaceDefinitionStatement* currentScope = namespaceDefinition;
               ROSE_ASSERT(currentScope != NULL);

#if ALIAS_SYMBOL_DEBUGGING
               printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: Suppress injection of symbols from one namespace to the other for each reintrant namespace \n");
               printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: referencedScope #symbols = %d currentScope #symbols = %d \n",referencedScope->get_symbol_table()->size(),currentScope->get_symbol_table()->size());
               printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: referencedScope = %p currentScope = %p \n",referencedScope,currentScope);
#endif
#if 1
            // Generate the alias symbols from the referencedScope and inject into the currentScope.
               injectSymbolsFromReferencedScopeIntoCurrentScope(referencedScope,currentScope,SgAccessModifier::e_default);
#endif
             }
            else
             {
#if ALIAS_SYMBOL_DEBUGGING
               printf ("In FixupAstSymbolTablesToSupportAliasedSymbols: (entry NOT found): Insert namespace %p for name = %s into the namespaceMap \n",namespaceDefinition,mangledNamespaceName.str());
#endif
               std::vector<SgNamespaceDefinitionStatement*> list(1);
               ROSE_ASSERT(list.size() == 1);

#error "DEAD CODE"

               list[0] = namespaceDefinition;
#if 0
            // DQ (3/11/2012): New code, but maybe we should instead put the implicit "std" namespace into the global scope more directly.
               if (mangledNamespaceName == "std" && false)
                  {
                 // This case has to be handled special since the implicit "std" namespace primary declaration was 
                 // constructed but not added to the global scope.  But maybe it should be.
                  }
                 else
                  {
                 // DQ (7/24/2011): get_nextNamespaceDefinition() == NULL is false in the case of the AST copy tests 
                 // (see tests/nonsmoke/functional/CompileTests/copyAST_tests/copytest2007_30.C). Only  get_nextNamespaceDefinition() 
                 // appears to sometimes be non-null, so we reset them both to NULL just to make sure.
                    namespaceDefinition->set_nextNamespaceDefinition(NULL);
                    namespaceDefinition->set_previousNamespaceDefinition(NULL);

                    ROSE_ASSERT(namespaceDefinition->get_nextNamespaceDefinition()     == NULL);
                    ROSE_ASSERT(namespaceDefinition->get_previousNamespaceDefinition() == NULL);
                  }
#else
            // DQ (7/24/2011): get_nextNamespaceDefinition() == NULL is false in the case of the AST copy tests 
            // (see tests/nonsmoke/functional/CompileTests/copyAST_tests/copytest2007_30.C). Only  get_nextNamespaceDefinition() 
            // appears to sometimes be non-null, so we reset them both to NULL just to make sure.
               namespaceDefinition->set_nextNamespaceDefinition(NULL);
               namespaceDefinition->set_previousNamespaceDefinition(NULL);

               ROSE_ASSERT(namespaceDefinition->get_nextNamespaceDefinition()     == NULL);
               ROSE_ASSERT(namespaceDefinition->get_previousNamespaceDefinition() == NULL);
#endif
               namespaceMap.insert(std::pair<SgName,std::vector<SgNamespaceDefinitionStatement*> >(mangledNamespaceName,list));

#error "DEAD CODE"

#if ALIAS_SYMBOL_DEBUGGING
               printf ("namespaceMap.size() = %" PRIuPTR " \n",namespaceMap.size());
#endif
             }
        }

#error "DEAD CODE"

#else
  // DQ (5/23/2013): Commented out since we now have a newer and better namespace support for symbol handling.
  // printf ("NOTE:: COMMENTED OUT old support for namespace declarations in FixupAstSymbolTablesToSupportAliasedSymbols traversal \n");
#endif

     SgUseStatement* useDeclaration = isSgUseStatement(node);
     if (useDeclaration != NULL)
        {
       // This must be done in the Fortran AST construction since aliased symbols must be inserted
       // before they are looked up as part of name resolution of variable, functions, and types.
       // For C++ we can be more flexible and support the construction of symbol aliases within 
       // post-processing.
        }

  // DQ (4/14/2010): Added this C++ specific support.
  // In the future we may want to support the injection of alias symbols for C++ "using" directives and "using" declarations.
     SgUsingDeclarationStatement* usingDeclarationStatement = isSgUsingDeclarationStatement(node);
     if (usingDeclarationStatement != NULL)
        {
#if ALIAS_SYMBOL_DEBUGGING
          printf ("Found the SgUsingDeclarationStatement \n");
#endif
          SgScopeStatement* currentScope = usingDeclarationStatement->get_scope();
          ROSE_ASSERT(currentScope != NULL);

          SgDeclarationStatement* declaration     = usingDeclarationStatement->get_declaration();
          SgInitializedName*      initializedName = usingDeclarationStatement->get_initializedName();

       // Only one of these can be non-null.
          ROSE_ASSERT(initializedName != NULL || declaration != NULL);
          ROSE_ASSERT( (initializedName != NULL && declaration != NULL) == false);

          if (declaration != NULL)
             {
#if ALIAS_SYMBOL_DEBUGGING
               printf ("In FixupAstSymbolTablesToSupportAliasedSymbols::visit(): declaration = %p = %s \n",declaration,declaration->class_name().c_str());
#endif
             }
            else
             {
               if (initializedName != NULL)
                  {
#if ALIAS_SYMBOL_DEBUGGING
                    printf ("In FixupAstSymbolTablesToSupportAliasedSymbols::visit(): initializedName = %s \n",initializedName->get_name().str());
#endif
                  }
                 else
                  {
                    printf ("Error: both declaration and initializedName in SgUsingDeclarationStatement are NULL \n");
                    ROSE_ASSERT(false);
                  }
             }

#if 0
          printf ("Exiting at the base of FixupAstSymbolTablesToSupportAliasedSymbols::visit() \n");
          ROSE_ASSERT(false);
#endif
        }

     SgUsingDirectiveStatement* usingDirectiveStatement = isSgUsingDirectiveStatement(node);
     if (usingDirectiveStatement != NULL)
        {
#if ALIAS_SYMBOL_DEBUGGING
          printf ("Found the SgUsingDirectiveStatement \n");
#endif
          SgNamespaceDeclarationStatement* namespaceDeclaration = usingDirectiveStatement->get_namespaceDeclaration();
          ROSE_ASSERT(namespaceDeclaration != NULL);

          SgScopeStatement* currentScope    = usingDirectiveStatement->get_scope();

       // To be more specific this is really a SgNamespaceDefinitionStatement
          SgScopeStatement* referencedScope = namespaceDeclaration->get_definition();

          if (referencedScope == NULL)
             {
            // DQ (5/21/2010): Handle case of using "std" (predefined namespace in C++), but it not having been explicitly defined (see test2005_57.C).
               if (namespaceDeclaration->get_name() != "std")
                  {
                    printf ("ERROR: namespaceDeclaration has no valid definition \n");
                    namespaceDeclaration->get_startOfConstruct()->display("ERROR: namespaceDeclaration has no valid definition");

                 // DQ (5/20/2010): Added assertion to trap this case.
                    printf ("Exiting because referencedScope could not be identified.\n");
                    ROSE_ASSERT(false);
                  }
             }

       // Note that "std", as a predefined namespace, can have a null definition, so we can't 
       // insist that we inject all symbols in namespaces that we can't see explicitly.
          if (referencedScope != NULL)
             {
               ROSE_ASSERT(referencedScope != NULL);
               ROSE_ASSERT(currentScope != NULL);
#if 0
               printf ("Calling injectSymbolsFromReferencedScopeIntoCurrentScope() for usingDirectiveStatement = %p = %s \n",node,node->class_name().c_str());
#endif
               injectSymbolsFromReferencedScopeIntoCurrentScope(referencedScope,currentScope,usingDirectiveStatement,SgAccessModifier::e_default);
             }

#if 0
          printf ("Exiting at the base of FixupAstSymbolTablesToSupportAliasedSymbols::visit() \n");
          ROSE_ASSERT(false);
#endif
        }

  // DQ (5/6/2011): Added support to build SgAliasSymbols in derived class scopes that reference the symbols of the base classes associated with protected and public declarations.
     SgClassDefinition* classDefinition = isSgClassDefinition(node);
     if (classDefinition != NULL)
        {
       // Handle any derived classes.
          SgBaseClassPtrList & baseClassList = classDefinition->get_inheritances();
          SgBaseClassPtrList::iterator i = baseClassList.begin();
          for ( ; i != baseClassList.end(); ++i)
             {
            // Check each base class.
               SgBaseClass* baseClass = *i;
               ROSE_ASSERT(baseClass != NULL);

               /* skip processing for SgExpBaseClasses (which don't have to define p_base_class) */
               if (baseClass->variantT() == V_SgExpBaseClass) {
                   continue;
               }

            // printf ("baseClass->get_baseClassModifier().displayString()                      = %s \n",baseClass->get_baseClassModifier().displayString().c_str());
            // printf ("baseClass->get_baseClassModifier().get_accessModifier().displayString() = %s \n",baseClass->get_baseClassModifier().get_accessModifier().displayString().c_str());

            // if (baseClass->get_modifier() == SgBaseClass::e_virtual)
               if (baseClass->get_baseClassModifier().get_modifier() == SgBaseClassModifier::e_virtual)
                  {
                 // Not clear if virtual as a modifier effects the handling of alias symbols.
                 // printf ("Not clear if virtual as a modifier effects the handling of alias symbols. \n");
                  }

            // DQ (6/22/2011): Define the access level for alias symbol's declarations to be included.
               SgAccessModifier::access_modifier_enum accessLevel = baseClass->get_baseClassModifier().get_accessModifier().get_modifier();

               SgClassDeclaration* tmpClassDeclaration    = baseClass->get_base_class();
               ROSE_ASSERT(tmpClassDeclaration != NULL);
#if 0
            // ROSE_ASSERT(tmpClassDeclaration->get_definingDeclaration() != NULL);
               SgClassDeclaration* targetClassDeclaration = isSgClassDeclaration(tmpClassDeclaration->get_definingDeclaration());
               ROSE_ASSERT(targetClassDeclaration != NULL);
               SgScopeStatement*   referencedScope  = targetClassDeclaration->get_definition();
            // We need this function to restrict it's injection of symbol to just those that are associated with public and protected declarations.
               injectSymbolsFromReferencedScopeIntoCurrentScope(referencedScope,classDefinition,accessLevel);
#else
            // DQ (2/25/2012) We only want to inject the symbol where we have identified the defining scope.
               if (tmpClassDeclaration->get_definingDeclaration() != NULL)
                  {
                    SgClassDeclaration* targetClassDeclaration = isSgClassDeclaration(tmpClassDeclaration->get_definingDeclaration());
                    ROSE_ASSERT(targetClassDeclaration != NULL);
                    SgScopeStatement*   referencedScope  = targetClassDeclaration->get_definition();
#if 0
                    printf ("Calling injectSymbolsFromReferencedScopeIntoCurrentScope() for classDefinition = %p = %s baseClass = %p accessLevel = %d \n",
                         node,node->class_name().c_str(),baseClass,accessLevel);
#endif
                 // DQ (7/12/2014): Use the SgBaseClass as the causal node that has triggered the insertion of the SgAliasSymbols.
                 // We need this function to restrict it's injection of symbol to just those that are associated with public and protected declarations.
                    injectSymbolsFromReferencedScopeIntoCurrentScope(referencedScope,classDefinition,baseClass,accessLevel);
                  }
                 else
                  {
                 // DQ (2/25/2012): Print a warning message when this happens (so far only test2012_08.C).
                    if (SgProject::get_verbose() > 0)
                       {
                         mprintf ("WARNING: In FixupAstSymbolTablesToSupportAliasedSymbols::visit(): Not really clear how to handle this case where tmpClassDeclaration->get_definingDeclaration() == NULL! \n");
                       }
                  }
#endif
             }
        }


     SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(node);
     if (functionDeclaration != NULL)
        {
#if ALIAS_SYMBOL_DEBUGGING
          printf ("Found a the SgFunctionDeclaration \n");
#endif
       // SgScopeStatement*  functionScope   = functionDeclaration->get_scope();
          SgScopeStatement*  currentScope    = isSgScopeStatement(functionDeclaration->get_parent());
          SgClassDefinition* classDefinition = isSgClassDefinition(currentScope);

          if (classDefinition != NULL)
             {
            // This is a function declared in a class definition, test of friend (forget why it is important to test for isOperator().
               if (functionDeclaration->get_declarationModifier().isFriend() == true || functionDeclaration->get_specialFunctionModifier().isOperator() == true)
                  {
                 // printf ("Process all friend function with a SgAliasSymbol to where they are declared in another scope (usually global scope) \n");
#if 0
                    SgName name = functionDeclaration->get_name();

                    SgSymbol* symbol = functionDeclaration->search_for_symbol_from_symbol_table();
                    ROSE_ASSERT ( symbol != NULL );

                    SgAliasSymbol* aliasSymbol = new SgAliasSymbol (symbol);

                 // Use the current name and the alias to the symbol
                    currentScope->insert_symbol(name,aliasSymbol);
#endif
#if 0
                    printf ("Error: friend functions not processed yet! \n");
                    ROSE_ASSERT(false);
#endif
                  }
             }
        }

#if ALIAS_SYMBOL_DEBUGGING
     printf ("Leaving FixupAstSymbolTablesToSupportAliasedSymbols::visit() (preorder AST traversal) node = %p = %s \n",node,node->class_name().c_str());
#endif
   }
Exemplo n.º 13
0
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);
   }
Exemplo n.º 14
0
bool
ReplacementMapTraversal::verifyODR( SgNode* node, SgNode* duplicateNodeFromOriginalAST )
   {
     bool passesODR = false;
  // printf ("Verify that node = %p is equivalent to duplicateNodeFromOriginalAST = %p = %s \n",node,duplicateNodeFromOriginalAST,duplicateNodeFromOriginalAST->class_name().c_str());

  // Verify that these strings match
     ROSE_ASSERT (duplicateNodeFromOriginalAST->variantT() == node->variantT());
     ROSE_ASSERT (duplicateNodeFromOriginalAST->class_name() == node->class_name());
  // ROSE_ASSERT (generateUniqueName(duplicateNodeFromOriginalAST) == generateUniqueName(node));

     string nodeString;
     string duplicateNodeFromOriginalASTstring;

#if 0
  // DQ (2/3/2007): This is a test to debug the ODR checking.
  // I think that the unparser has some state specific to the output of access protections.
  // if the unparsing changes the state then the access permission (public, protected, private) 
  // is output and this cause a falue trigger to the ODR string match.  This is a temp fix to
  // absorbe any change of state, but we need a mechanism to clear the state in the unparser.
     string absorbeUnparserStateChange_A = node->unparseToString();
     string absorbeUnparserStateChange_B = duplicateNodeFromOriginalAST->unparseToString();
#endif
#if 0
  // DQ (2/3/2007): Make sure that there are close to being related. It appears that if these are
     if (node->get_parent()->variantT() == duplicateNodeFromOriginalAST->get_parent()->variantT())
        {
          nodeString                         = node->unparseToString();
          duplicateNodeFromOriginalASTstring = duplicateNodeFromOriginalAST->unparseToString();
        }
#endif

     bool skip_ODR_test = false;

     bool nodeIsCompilerGenerated = 
          (node->get_file_info() != NULL) ? node->get_file_info()->isCompilerGenerated() : false;
     bool duplicateNodeFromOriginalASTIsCompilerGenerated = 
          (duplicateNodeFromOriginalAST->get_file_info() != NULL) ? duplicateNodeFromOriginalAST->get_file_info()->isCompilerGenerated() : false;

     bool nodeIsFrontendSpecific = 
          (node->get_file_info() != NULL) ? node->get_file_info()->isFrontendSpecific() : false;
     bool duplicateNodeFromOriginalASTIsFrontendSpecific = 
          (duplicateNodeFromOriginalAST->get_file_info() != NULL) ? duplicateNodeFromOriginalAST->get_file_info()->isFrontendSpecific() : false;

  // If this is a template declaration for a function then it might have been a part of another template declaration 
  // for the template class and thus might not exist explicitly in the AST (and thus not have enough information from 
  // which to generate a meaningful mangled name).  Skip ODR testing of these cases.
     bool isTemplateMemberFunctionInTemplatedClass = false;
     SgTemplateDeclaration* templateDeclaration = isSgTemplateDeclaration(node);
     if (templateDeclaration != NULL)
        {
          SgTemplateDeclaration* dup_templateDeclaration = isSgTemplateDeclaration(duplicateNodeFromOriginalAST);
          ROSE_ASSERT(dup_templateDeclaration != NULL);
          if ( templateDeclaration->get_string().is_null() && dup_templateDeclaration->get_string().is_null() )
             {
               isTemplateMemberFunctionInTemplatedClass = true;
             }
        }

     if (isTemplateMemberFunctionInTemplatedClass == true)
        {
          printf ("ODR not tested isTemplateMemberFunctionInTemplatedClass == true. \n");
          skip_ODR_test = true;
        }

     if (nodeIsFrontendSpecific == true || duplicateNodeFromOriginalASTIsFrontendSpecific == true || nodeIsCompilerGenerated == true || duplicateNodeFromOriginalASTIsCompilerGenerated == true)
        {
       // printf ("ODR not tested for frontend specific compiler generated code. \n");
          skip_ODR_test = true;
        }

  // DQ (1/20/2007): The unparse will not generate a string if the code is frontend specific or compiler generated (I forget which).
  // if (nodeIsFrontendSpecific == true || duplicateNodeFromOriginalASTIsFrontendSpecific == true)
     if (skip_ODR_test == true)
        {
       // printf ("ODR not tested for frontend specific compiler generated code. \n");
          passesODR = true;
        }
       else
        {
          SgUnparse_Info info_a;
          SgUnparse_Info info_b;

       // DQ (2/6/2007): Force qualified names to be used uniformally (note that info.set_requiresGlobalNameQualification() 
       // causes an error) info.set_requiresGlobalNameQualification();
          info_a.set_forceQualifiedNames();
          info_b.set_forceQualifiedNames();

          nodeString                         = node->unparseToString(&info_a);

       // DQ (2/6/2007): The SgUnparse_Info object carries state which controls the use of access qualification and the 
       // first call to unparseToString might have set the access (e.g. to "public") and the second call would drop the 
       // access qualification.  We unset the access qualification state in the SgUnparse_Info object so that both will 
       // be unparsed the same (we could have alternatively used two separate SgUnparse_Info objects.
       // info.set_isUnsetAccess();

          duplicateNodeFromOriginalASTstring = duplicateNodeFromOriginalAST->unparseToString(&info_b);

          passesODR = (nodeString == duplicateNodeFromOriginalASTstring);
        }

  // Don't count the cases where the unparse fails to to invalid parent in redundant SgClassDeclaration (fix these later)
     if (passesODR == false && nodeString.empty() == false && duplicateNodeFromOriginalASTstring.empty() == false)
        {
#if 1
          if (SgProject::get_verbose() > 0)
               printf ("##### In ReplacementMapTraversal::verifyODR() is false: node = %p = %s duplicateNodeFromOriginalAST = %p = %s \n",
                    node,node->class_name().c_str(),duplicateNodeFromOriginalAST,duplicateNodeFromOriginalAST->class_name().c_str());

       // printf ("##### passesODR = %s \n",passesODR ? "true" : "false");
       // printf ("duplicateNodeFromOriginalASTstring = \n---> %s\n",duplicateNodeFromOriginalASTstring.c_str());
       // printf ("nodeString                         = \n---> %s\n",nodeString.c_str());
          if (node->get_file_info() != NULL && duplicateNodeFromOriginalAST->get_file_info() != NULL)
             {
               if (SgProject::get_verbose() > 0)
                  {
                    SgNode* parent_node = node->get_parent();

                 // DQ (9/13/2011): Reported as possible NULL value in static analysis of ROSE code.
                    ROSE_ASSERT(parent_node != NULL);

                    printf ("parent_node = %p = %s = %s \n",parent_node,parent_node->class_name().c_str(),SageInterface::get_name(parent_node).c_str());
                    SgNode* parent_dup = duplicateNodeFromOriginalAST->get_parent();

                 // DQ (9/13/2011): Reported as possible NULL value in static analysis of ROSE code.
                    ROSE_ASSERT(parent_dup != NULL);

                    printf ("parent_dup = %p = %s = %s \n",parent_dup,parent_dup->class_name().c_str(),SageInterface::get_name(parent_dup).c_str());

                    printf ("\nPosition of error: \n");
                    node->get_file_info()->display("In ReplacementMapTraversal::verifyODR(node) is false: debug");
                    duplicateNodeFromOriginalAST->get_file_info()->display("In ReplacementMapTraversal::verifyODR(duplicateNodeFromOriginalAST) is false: debug");
                    printf ("\nPosition of error: \n");

                    printf ("\nPosition of error (parent IR node): \n");
                    parent_node->get_file_info()->display("In ReplacementMapTraversal::verifyODR(parent_node) is false: debug");
                    parent_dup->get_file_info()->display("In ReplacementMapTraversal::verifyODR(parent_dup) is false: debug");
                    printf ("\nPosition of error (parent IR node): \n");
                  }
             }
            else
             {
               SgClassType* classType = isSgClassType(node);
               SgClassType* duplicateNodeFromOriginalAST_classType = isSgClassType(duplicateNodeFromOriginalAST);
               if (classType != NULL)
                  {
                    if (SgProject::get_verbose() > 0)
                       {
                         SgClassDeclaration* classDeclaration = isSgClassDeclaration(classType->get_declaration());
                         ROSE_ASSERT(classDeclaration != NULL);
                         classDeclaration->get_file_info()->display("In ReplacementMapTraversal::verifyODR(node) is false (classType)");
                         printf ("classDeclaration = %p definingDeclaration = %p nondefiningDeclaration = %p \n",
                              classDeclaration,
                              classDeclaration->get_definingDeclaration(),
                              classDeclaration->get_firstNondefiningDeclaration());

                         ROSE_ASSERT(duplicateNodeFromOriginalAST_classType != NULL);
                         SgClassDeclaration* duplicateNodeFromOriginalAST_classDeclaration = isSgClassDeclaration(duplicateNodeFromOriginalAST_classType->get_declaration());
                         ROSE_ASSERT(duplicateNodeFromOriginalAST_classDeclaration != NULL);
                         duplicateNodeFromOriginalAST_classDeclaration->get_file_info()->display("In ReplacementMapTraversal::verifyODR(node) is false (duplicateNodeFromOriginalAST_classType)");
                         printf ("duplicateNodeFromOriginalAST_classDeclaration = %p definingDeclaration = %p nondefiningDeclaration = %p \n",
                              duplicateNodeFromOriginalAST_classDeclaration,
                              duplicateNodeFromOriginalAST_classDeclaration->get_definingDeclaration(),
                              duplicateNodeFromOriginalAST_classDeclaration->get_firstNondefiningDeclaration());
                       }
                  }
             }
#endif
          odrViolations.push_back(pair<SgNode*,SgNode*>(node,duplicateNodeFromOriginalAST));
        }
#if 0
     printf ("duplicateNodeFromOriginalASTstring = %p = %s \n---> %s\n",
          duplicateNodeFromOriginalAST,duplicateNodeFromOriginalAST->class_name().c_str(),duplicateNodeFromOriginalASTstring.c_str());
     printf ("nodeString                         = %p = %s \n---> %s\n",
          node,node->class_name().c_str(),nodeString.c_str());
#endif
#if 0
     SgClassType* original = isSgClassType(duplicateNodeFromOriginalAST);
     SgClassType* target   = isSgClassType(node);
     if (original != NULL && target != NULL)
        {
          printf ("original declaration = %p \n",original->get_declaration());
          printf ("target declaration   = %p \n",target->get_declaration());
        }
#endif
#if 1
     if (passesODR == false)
        {
          if (SgProject::get_verbose() > 0)
             {
               string node_generatedName         = SageInterface::generateUniqueName(node,false);
               string originalNode_generatedName = SageInterface::generateUniqueName(duplicateNodeFromOriginalAST,false);

               printf ("ODR Violation Source code: nodeString                         = \n%s\n \n",nodeString.c_str());
               printf ("ODR Violation Source code: duplicateNodeFromOriginalASTstring = \n%s\n \n",duplicateNodeFromOriginalASTstring.c_str());
               printf ("nodeString = %s \n",nodeString.c_str());
               printf ("node_generatedName         = %s \n",node_generatedName.c_str());
               printf ("originalNode_generatedName = %s \n",originalNode_generatedName.c_str());

               printf ("node                         = %p = %s = %s \n",node,node->class_name().c_str(),SageInterface::get_name(node).c_str());
               printf ("duplicateNodeFromOriginalAST = %p = %s = %s \n",duplicateNodeFromOriginalAST,duplicateNodeFromOriginalAST->class_name().c_str(),SageInterface::get_name(duplicateNodeFromOriginalAST).c_str());

               printf ("node (unique string)                         = %s \n",generateUniqueName(node,true).c_str());
               printf ("duplicateNodeFromOriginalAST (unique string) = %s \n",generateUniqueName(duplicateNodeFromOriginalAST,true).c_str());

               SgDeclarationStatement* declarationStatement = isSgDeclarationStatement(node);
               if (declarationStatement != NULL)
                  {
                    printf ("declarationStatement->get_definingDeclaration()         = %p \n",declarationStatement->get_definingDeclaration());
                    printf ("declarationStatement->get_firstNondefiningDeclaration() = %p \n",declarationStatement->get_firstNondefiningDeclaration());
                  }

               SgDeclarationStatement* declarationStatement2 = isSgDeclarationStatement(duplicateNodeFromOriginalAST);
               if (declarationStatement2 != NULL)
                  {
                    printf ("declarationStatement2->get_definingDeclaration()         = %p \n",declarationStatement2->get_definingDeclaration());
                    printf ("declarationStatement2->get_firstNondefiningDeclaration() = %p \n",declarationStatement2->get_firstNondefiningDeclaration());
                  }

               printf ("Source code positions of ORD violation: \n");
               node->get_file_info()->display("In ReplacementMapTraversal::verifyODR(node) is false: debug");
               duplicateNodeFromOriginalAST->get_file_info()->display("In ReplacementMapTraversal::verifyODR(duplicateNodeFromOriginalAST) is false: debug");
             }
        }
#endif
  // ROSE_ASSERT(nodeString == duplicateNodeFromOriginalASTstring);
     ROSE_ASSERT(passesODR == true);

     return passesODR;
   }
Exemplo n.º 15
0
DOTSynthesizedAttribute
AstDOTGeneration::evaluateSynthesizedAttribute(SgNode* node, DOTInheritedAttribute ia, SubTreeSynthesizedAttributes l)
   {
     SubTreeSynthesizedAttributes::iterator iter;
     ROSE_ASSERT(node);

  // printf ("AstDOTGeneration::evaluateSynthesizedAttribute(): node = %s \n",node->class_name().c_str());

  // DQ (5/3/2006): Skip this IR node if it is specified as such in the inherited attribute
     if (ia.skipSubTree == true)
        {
       // I am unclear if I should return NULL or node as a parameter to DOTSynthesizedAttribute
       // Figured this out: if we return a valid pointer then we get a node in the DOT graph 
       // (with just the pointer value as a label), where as if we return a DOTSynthesizedAttribute 
       // with a NUL pointer then the node will NOT appear in the DOT graph.
       // return DOTSynthesizedAttribute(node);
          return DOTSynthesizedAttribute(NULL);
        }

     string nodeoption;
     if(AstTests::isProblematic(node))
        {
       // cout << "problematic node found." << endl;
          nodeoption="color=\"orange\" ";
        }
     string nodelabel=string("\\n")+node->class_name();

  // DQ (1/24/2009): Added support for output of isForward flag in the dot graph.
     SgDeclarationStatement* genericDeclaration = isSgDeclarationStatement(node);
     if (genericDeclaration != NULL)
        {
       // At the moment the mnemonic name is stored, but it could be computed in the 
       // future from the kind and the tostring() function.
          string name = (genericDeclaration->isForward() == true) ? "isForward" : "!isForward";
          ROSE_ASSERT(name.empty() == false);

       // DQ (3/20/2011): Added class names to the generated dot file graphs of the AST.
          SgClassDeclaration* classDeclaration = isSgClassDeclaration(genericDeclaration);
          if (classDeclaration != NULL)
             {
               nodelabel += string("\\n") + classDeclaration->get_name();
             }

       // DQ (3/20/2011): Added function names to the generated dot file graphs of the AST.
          SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(genericDeclaration);
          if (functionDeclaration != NULL)
             {
               nodelabel += string("\\n") + functionDeclaration->get_name();
             }

          nodelabel += string("\\n") + name;
        }

  // DQ (4/6/2011): Added support for output of the name for SgInitializedName IR nodes.
     SgInitializedName* initializedName = isSgInitializedName(node);
     if (initializedName != NULL)
        {
          nodelabel += string("\\n") + initializedName->get_name();
        }

  // DQ (4/6/2011): Added support for output of the name for SgInitializedName IR nodes.
     SgIntVal* intValue = isSgIntVal(node);
     if (intValue != NULL)
        {
          nodelabel += string("\\n value = ") + StringUtility::numberToString(intValue->get_value());
        }

  // DQ (4/6/2011): Added support for output of the name for SgInitializedName IR nodes.
     SgVarRefExp* varRefExp = isSgVarRefExp(node);
     if (varRefExp != NULL)
        {
          SgVariableSymbol* variableSymbol = varRefExp->get_symbol();
          ROSE_ASSERT(variableSymbol != NULL);
          string name = variableSymbol->get_name();
          nodelabel += string("\\n name = ") + name;
        }

  // DQ (1/19/2009): Added support for output of what specific instrcution this is in the dot graph.
     SgAsmInstruction* genericInstruction = isSgAsmInstruction(node);
     if (genericInstruction != NULL)
        {
#ifdef ROSE_BUILD_BINARY_ANALYSIS_SUPPORT
       // At the moment the mnemonic name is stored, but it could be computed in the 
       // future from the kind and the tostring() function.
#if 1
          string unparsedInstruction = unparseInstruction(genericInstruction);
          string addressString       = StringUtility::numberToString( (void*) genericInstruction->get_address() );
       // string name = genericInstruction->get_mnemonic();
          string name = unparsedInstruction + "\\n address: " + addressString;
#else
          string name = unparsedInstruction + "\\n" + addressString;
#endif
          ROSE_ASSERT(name.empty() == false);

          nodelabel += string("\\n") + name;
#else
          printf ("Warning: In AstDOTGeneration.C ROSE_BUILD_BINARY_ANALYSIS_SUPPORT is not defined \n");
#endif
        }

     SgAsmExpression* genericExpression = isSgAsmExpression(node);
     if (genericExpression != NULL)
        {
#ifdef ROSE_BUILD_BINARY_ANALYSIS_SUPPORT
          string name = unparseExpression(genericExpression, NULL, NULL);
          ROSE_ASSERT(name.empty() == false);
          nodelabel += string("\\n") + name;
#else
          printf ("Warning: In AstDOTGeneration.C ROSE_BUILD_BINARY_ANALYSIS_SUPPORT is not defined \n");
#endif
        }

  // DQ (10/29/2008): Added some support for additional output of internal names for specific IR nodes.
  // In generall there are long list of these IR nodes in the binary and this helps make some sense of 
  // the lists (sections, symbols, etc.).
     SgAsmExecutableFileFormat* binaryFileFormatNode = isSgAsmExecutableFileFormat(node);
     if (binaryFileFormatNode != NULL)
        {
#ifdef ROSE_BUILD_BINARY_ANALYSIS_SUPPORT
       // The case of binary file format IR nodes can be especially confusing so we want the 
       // default to output some more specific information for some IR nodes (e.g. sections).
          string name;

          SgAsmGenericSection* genericSection = isSgAsmGenericSection(node);
          if (genericSection != NULL)
             {
               SgAsmGenericString* genericString = genericSection->get_name();
               ROSE_ASSERT(genericString != NULL);

               name = genericString->get_string();
             }

          SgAsmGenericSymbol* genericSymbol = isSgAsmGenericSymbol(node);
          if (genericSymbol != NULL)
             {
               SgAsmGenericString* genericString = genericSymbol->get_name();
               ROSE_ASSERT(genericString != NULL);

               name = genericString->get_string();

               if (name.empty() == true)
                    name = "no_name_for_symbol";
             }

          SgAsmGenericDLL* genericDLL = isSgAsmGenericDLL(node);
          if (genericDLL != NULL)
             {
               SgAsmGenericString* genericString = genericDLL->get_name();
               ROSE_ASSERT(genericString != NULL);

               name = genericString->get_string();
             }

          SgAsmPEImportItem* peImportItem = isSgAsmPEImportItem(node);
          if (peImportItem != NULL)
             {
               SgAsmGenericString* genericString = peImportItem->get_name();
               ROSE_ASSERT(genericString != NULL);

               name = genericString->get_string();
             }

          SgAsmDwarfLine* asmDwarfLine = isSgAsmDwarfLine(node);
          if (asmDwarfLine != NULL)
             {
               char buffer[100];

            // It does not work to embed the "\n" into the single sprintf parameter.
            // sprintf(buffer," Addr: 0x%08"PRIx64" \n line: %d col: %d ",asmDwarfLine->get_address(),asmDwarfLine->get_line(),asmDwarfLine->get_column());

               sprintf(buffer,"Addr: 0x%08"PRIx64,asmDwarfLine->get_address());
               name = buffer;
               sprintf(buffer,"line: %d col: %d",asmDwarfLine->get_line(),asmDwarfLine->get_column());
               name += string("\\n") + buffer;
             }

          SgAsmDwarfConstruct* asmDwarfConstruct = isSgAsmDwarfConstruct(node);
          if (asmDwarfConstruct != NULL)
             {
               name = asmDwarfConstruct->get_name();
             }

#if 0
       // This might not be the best way to implement this, since we want to detect common base classes of IR nodes.
          switch (node->variantT())
             {
               case V_SgAsmElfSection:
                  {
                    SgAsmElfSection* n = isSgAsmElfSection(node);
                    name = n->get_name();
                    break;
                  }

               default:
                  {
                 // No additional information is suggested for the default case!
                  }
             }
#endif

          if (name.empty() == false)
               nodelabel += string("\\n") + name;
#else
          printf ("Warning: In AstDOTGeneration.C ROSE_BUILD_BINARY_ANALYSIS_SUPPORT is not defined \n");
#endif
        }

  // DQ (11/29/2008): Output the directives in the label of the IR node.
     SgC_PreprocessorDirectiveStatement* preprocessorDirective = isSgC_PreprocessorDirectiveStatement(node);
     if (preprocessorDirective != NULL)
        {
          string s = preprocessorDirective->get_directiveString();

       // Change any double quotes to single quotes so that DOT will not misunderstand the generated lables.
          while (s.find("\"") != string::npos)
             {
               s.replace(s.find("\""),1,"\'");
             }

          if (s.empty() == false)
               nodelabel += string("\\n") + s;
        }

     nodelabel += additionalNodeInfo(node);

  // DQ (11/1/2003) added mechanism to add additional options (to add color, etc.)
  // nodeoption += additionalNodeOptions(node);
     string additionalOptions = additionalNodeOptions(node);
  // printf ("nodeoption = %s size() = %ld \n",nodeoption.c_str(),nodeoption.size());
  // printf ("additionalOptions = %s size() = %ld \n",additionalOptions.c_str(),additionalOptions.size());

     string x;
     string y;
     x += additionalOptions;

     nodeoption += additionalOptions;

     DOTSynthesizedAttribute d(0);

  // DQ (7/27/2008): Added mechanism to support pruning of AST
     bool commentoutNode = commentOutNodeInGraph(node);
     if (commentoutNode == true)
        {
       // DQ (11/10/2008): Fixed to only output message when (verbose_level > 0); command-line option.
       // DQ (7/27/2008): For now just return to test this mechanism, then we want to add comment "//" propoerly to generated DOT file.
          if (SgProject::get_verbose() > 0)
             {
               printf ("Skipping the use of this IR node in the DOT Graph \n");
             }
        }
       else
        {

// **************************

     switch(traversal)
        {
          case TOPDOWNBOTTOMUP:
               dotrep.addNode(node,dotrep.traceFormat(ia.tdbuTracePos,tdbuTrace)+nodelabel,nodeoption);
               break;
          case PREORDER:
          case TOPDOWN:
               dotrep.addNode(node,dotrep.traceFormat(ia.tdTracePos)+nodelabel,nodeoption);
               break;
          case POSTORDER:
          case BOTTOMUP:
               dotrep.addNode(node,dotrep.traceFormat(buTrace)+nodelabel,nodeoption);
               break;
          default:
               assert(false);
        }
  
     ++tdbuTrace;
     ++buTrace;

  // add edges or null values
     int testnum=0;
     for (iter = l.begin(); iter != l.end(); iter++)
        {
          string edgelabel = string(node->get_traversalSuccessorNamesContainer()[testnum]);
          string toErasePrefix = "p_";

          if (AstTests::isPrefix(toErasePrefix,edgelabel))
             {
               edgelabel.erase(0, toErasePrefix.size());
             }

          if ( iter->node == NULL)
             {
            // SgNode* snode=node->get_traversalSuccessorContainer()[testnum];
               AstSuccessorsSelectors::SuccessorsContainer c;
               AstSuccessorsSelectors::selectDefaultSuccessors(node,c);
               SgNode* snode=c[testnum];

            // isDefault shows that the default constructor for synth attribute was used
               if (l[testnum].isDefault() && snode && (visitedNodes.find(snode) != visitedNodes.end()) )
                  {
                 // handle bugs in SAGE
                    dotrep.addEdge(node,edgelabel,snode,"dir=forward arrowhead=\"odot\" color=red ");
                  }
                 else
                  {
                    if (snode == NULL)
                       {
                         dotrep.addNullValue(node,"",edgelabel,"");
                       }
                  }
             }
            else
             {
            // DQ (3/5/2007) added mechanism to add additional options (to add color, etc.)
               string edgeoption = additionalEdgeOptions(node,iter->node,edgelabel);

               switch(traversal)
                  {
                    case TOPDOWNBOTTOMUP:
                         dotrep.addEdge(node,edgelabel,(*iter).node,edgeoption + "dir=both");
                         break;
                    case PREORDER:
                    case TOPDOWN:
                         dotrep.addEdge(node,edgelabel,(*iter).node,edgeoption + "dir=forward");
                         break;
                    case POSTORDER:
                    case BOTTOMUP:
                         dotrep.addEdge(node,edgelabel,(*iter).node,edgeoption + "dir=back");
                         break;
                    default:
                         assert(false);
                  }
             }

          testnum++;
        }

// **************************
        }



  // DQ (7/4/2008): Support for edges specified in AST attributes
     AstAttributeMechanism* astAttributeContainer = node->get_attributeMechanism();
     if (astAttributeContainer != NULL)
        {
       // Loop over all the attributes at this IR node
          for (AstAttributeMechanism::iterator i = astAttributeContainer->begin(); i != astAttributeContainer->end(); i++)
             {
            // std::string name = i->first;
               AstAttribute* attribute = i->second;
               ROSE_ASSERT(attribute != NULL);

            // This can return a non-empty list in user-defined attributes (derived from AstAttribute).
            // printf ("Calling attribute->additionalNodeInfo() \n");
               std::vector<AstAttribute::AttributeNodeInfo> nodeList = attribute->additionalNodeInfo();
            // printf ("nodeList.size() = %lu \n",nodeList.size());

               for (std::vector<AstAttribute::AttributeNodeInfo>::iterator i_node = nodeList.begin(); i_node != nodeList.end(); i_node++)
                  {
                    SgNode* nodePtr   = i_node->nodePtr;
                    string nodelabel  = i_node->label;
                    string nodeoption = i_node->options;
                 // printf ("In AstDOTGeneration::evaluateSynthesizedAttribute(): Adding a node nodelabel = %s nodeoption = %s \n",nodelabel.c_str(),nodeoption.c_str());
                 // dotrep.addNode(NULL,dotrep.traceFormat(ia.tdTracePos)+nodelabel,nodeoption);
                    dotrep.addNode( nodePtr, dotrep.traceFormat(ia.tdTracePos) + nodelabel, nodeoption );
                  }

            // printf ("Calling attribute->additionalEdgeInfo() \n");
               std::vector<AstAttribute::AttributeEdgeInfo> edgeList = attribute->additionalEdgeInfo();
            // printf ("edgeList.size() = %lu \n",edgeList.size());
               for (std::vector<AstAttribute::AttributeEdgeInfo>::iterator i_edge = edgeList.begin(); i_edge != edgeList.end(); i_edge++)
                  {
                    string edgelabel  = i_edge->label;
                    string edgeoption = i_edge->options;
                 // printf ("In AstDOTGeneration::evaluateSynthesizedAttribute(): Adding an edge from i_edge->fromNode = %p to i_edge->toNode = %p edgelabel = %s edgeoption = %s \n",i_edge->fromNode,i_edge->toNode,edgelabel.c_str(),edgeoption.c_str());
                    dotrep.addEdge(i_edge->fromNode,edgelabel,i_edge->toNode,edgeoption + "dir=forward");
                  }
             }
        }



     switch(node->variantT())
        {
       // DQ (9/1/2008): Added case for output of SgProject rooted DOT file.
       // This allows source code and binary files to be combined into the same DOT file.
          case V_SgProject: 
             {
               SgProject* project = dynamic_cast<SgProject*>(node);
               ROSE_ASSERT(project != NULL);

               string generatedProjectName = SageInterface::generateProjectName( project );
            // printf ("generatedProjectName (from SgProject) = %s \n",generatedProjectName.c_str());
               if (generatedProjectName.length() > 40)
                  {
                 // printf ("Warning: generatedProjectName (from SgProject) = %s \n",generatedProjectName.c_str());
                    generatedProjectName = "aggregatedFileNameTooLong";
                    printf ("Proposed (generated) filename is too long, shortened to: %s \n",generatedProjectName.c_str());
                  }

               string filename = string("./") + generatedProjectName + ".dot";

            // printf ("generated filename for dot file (from SgProject) = %s \n",filename.c_str());
               if ( SgProject::get_verbose() >= 1 )
                    printf ("Output the DOT graph from the SgProject IR node (filename = %s) \n",filename.c_str());

               dotrep.writeToFileAsGraph(filename);
               break;
             }

       // case V_SgFile: 
          case V_SgSourceFile: 
          case V_SgBinaryComposite: 
             {
               SgFile* file = dynamic_cast<SgFile*>(node);
               ROSE_ASSERT(file != NULL);

               string original_filename = file->getFileName();

            // DQ (7/4/2008): Fix filenamePostfix to go before the "."
            // string filename = string("./") + ROSE::stripPathFromFileName(original_filename) + "."+filenamePostfix+"dot";
               string filename = string("./") + ROSE::stripPathFromFileName(original_filename) + filenamePostfix + ".dot";

            // printf ("generated filename for dot file (from SgSourceFile or SgBinaryComposite) = %s file->get_parent() = %p \n",filename.c_str(),file->get_parent());

            // printf ("file->get_parent() = %p \n",file->get_parent());
            // cout << "generating DOT file (from SgSourceFile or SgBinaryComposite): " << filename2 << " ... ";

            // DQ (9/1/2008): this effects the output of DOT files when multiple files are specified 
            // on the command line.  A SgProject is still built even when a single file is specificed 
            // on the command line, however there are cases where a SgFile can be built without a 
            // SgProject and this case allows those SgFile rooted subtrees to be output as DOT files.
            // If there is a SgProject then output the dot file from there, else output as a SgFile.
               if (file->get_parent() == NULL)
                  {
                 // If there is no SgProject then output the file now!
                    if ( SgProject::get_verbose() >= 1 )
                         printf ("Output the DOT graph from the SgFile IR node (no SgProject available) \n");

                    dotrep.writeToFileAsGraph(filename);
                  }
                 else
                  {
                 // There is a SgProject IR node, but if we will be traversing it we want to output the 
                 // graph then (so that the graph will include the SgProject IR nodes and connect multiple 
                 // files (SgSourceFile or SgBinaryComposite IR nodes).
                    if ( visitedNodes.find(file->get_parent()) == visitedNodes.end() )
                       {
                      // This SgProject node was not input as part of the traversal, 
                      // so we will not be traversing the SgProject IR nodes and we 
                      // have to output the graph now!

                         if ( SgProject::get_verbose() >= 1 )
                              printf ("Output the DOT graph from the SgFile IR node (SgProject was not traversed) \n");

                         dotrep.writeToFileAsGraph(filename);
                       }
                      else
                       {
                         if ( SgProject::get_verbose() >= 1 )
                              printf ("Skip the output of the DOT graph from the SgFile IR node (SgProject will be traversed) \n");
                       }
                  }
               
            // cout << "done." << endl;
               break;
             }

       // DQ (7/23/2005): Implemented default case to avoid g++ warnings 
       // about enum values not handled by this switch
          default: 
             {
            // nothing to do here
               break;
             }
        }

     d.node = node;
     return d;
   }
Exemplo n.º 16
0
SynthesizedAttribute
Traversal::evaluateSynthesizedAttribute ( SgNode* astNode, InheritedAttribute inheritedAttribute, SynthesizedAttributesList childAttributes )
   {
     SynthesizedAttribute localResult;

  // printf ("evaluateSynthesizedAttribute(): astNode = %p = %s inheritedAttribute.isFirstFile = %s \n",astNode,astNode->class_name().c_str(),inheritedAttribute.isFirstFile ? "true" : "false");

  // Accumulate any valid pointer to main on a child node and pass it to the local synthesized attribute.
     for (size_t i = 0; i < childAttributes.size(); i++)
        {
          if (childAttributes[i].main_function != NULL)
             {
               localResult.main_function = childAttributes[i].main_function;
             }
        }

     if (inheritedAttribute.isFirstFile == true)
        {
          SgGlobal* globalScope = isSgGlobal(astNode);
          if (globalScope != NULL)
             {
            // Gather all of the functions in global scope of the first file.

               vector<SgDeclarationStatement*> globalScopeDeclarationsToMove = globalScope->get_declarations();
               inheritedAttribute.statements_from_first_file = globalScopeDeclarationsToMove;

            // printf ("evaluateSynthesizedAttribute(): Gather all of the functions in global scope of the first file inheritedAttribute.statements_from_first_file.size() = %zu \n",inheritedAttribute.statements_from_first_file.size());

            // Erase the declarations in the global scope of the first file.
               globalScope->get_declarations().clear();
             }

          SgDeclarationStatement* declarationStatement = isSgDeclarationStatement(astNode);
          if (declarationStatement != NULL && isSgGlobal(declarationStatement->get_parent()) != NULL)
             {
            // Mark as a transformation (recursively mark the whole subtree).
            // printf ("*** Mark as a transformation: declarationStatement = %p \n",declarationStatement);
               markAsTransformation(declarationStatement);
               if (declarationStatement->get_firstNondefiningDeclaration() != NULL)
                    markAsTransformation(declarationStatement->get_firstNondefiningDeclaration());
             }
        }
       else
        {
          SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(astNode);
          if (functionDeclaration != NULL && functionDeclaration->get_name() == "main")
             {
            // Save the pointer to the main function (in the second file).
               localResult.main_function = functionDeclaration;
            // printf ("Found the main function ...(saved pointer) inheritedAttribute.main_function = %p \n",localResult.main_function);
             }

       // printf ("evaluateSynthesizedAttribute(): localResult.main_function = %p \n",localResult.main_function);

       // Test for the selected insertion point in the 2nd file for the declarations gathered from the first file.
          SgGlobal* globalScope = isSgGlobal(astNode);
          if (globalScope != NULL && localResult.main_function != NULL)
             {
               printf ("evaluateSynthesizedAttribute(): Found the main function ...\n");
               vector<SgDeclarationStatement*>::iterator i = find(globalScope->get_declarations().begin(),globalScope->get_declarations().end(),localResult.main_function);
               globalScope->get_declarations().insert(i,inheritedAttribute.statements_from_first_file.begin(),inheritedAttribute.statements_from_first_file.end());
#if 0
            // Set the parents of each declaration to match the new location (avoids warning that might later be an error).
               for (size_t i = 0; i < inheritedAttribute.statements_from_first_file.size(); i++)
                  {
                    inheritedAttribute.statements_from_first_file[i]->set_parent(globalScope);
                  }
#endif
             }
        }

     return localResult;
   }
Exemplo n.º 17
0
void
SgNode::insertSourceCode ( SgProject & project,
                           const char* sourceCodeString,
                           const char* localDeclaration,
                           const char* globalDeclaration,
                           bool locateNewCodeAtTop,
                           bool isADeclaration )
   {
  // If this function is useful only for SgBasicBlock then it should be put into that class directly.
  // This function is used to insert code into AST object for which insertion make sense:
  // (specifically any BASIC_BLOCK_STMT)

     if (variant() != BASIC_BLOCK_STMT)
        {
          printf ("ERROR: insert only make since for BASIC_BLOCK_STMT statements (variant() == variant()) \n");
          ROSE_ABORT();
        }

     SgBasicBlock* currentBlock = isSgBasicBlock(this);
     ROSE_ASSERT (currentBlock != NULL);

  // printf ("##### Calling SgNode::generateAST() \n");

#if 0
     printf ("In insertSourceCode(): globalDeclaration = \n%s\n",globalDeclaration);
     printf ("In insertSourceCode(): localDeclaration  = \n%s\n",localDeclaration);
     printf ("In insertSourceCode(): sourceCodeString  = \n%s\n",sourceCodeString);
#endif

  // SgNode* newTransformationAST = generateAST (project,sourceCodeString,globalDeclaration);
  // ROSE_ASSERT (newTransformationAST != NULL);
     SgStatementPtrList* newTransformationStatementListPtr =
          generateAST (project,sourceCodeString,localDeclaration,globalDeclaration,isADeclaration);
     ROSE_ASSERT (newTransformationStatementListPtr != NULL);
     ROSE_ASSERT (newTransformationStatementListPtr->size() > 0);

  // printf ("##### DONE: Calling SgNode::generateAST() \n");

  // get a reference to the statement list out of the basic block
     SgStatementPtrList & currentStatementList = currentBlock->get_statements();

     if (locateNewCodeAtTop == true)
        {
       // Insert at top of list (pull the elements off the bottom of the new statement list to get the order correct
       // printf ("Insert new statements (new statement list size = %d) at the top of the block (in reverse order to preset the order in the final block) \n",newTransformationStatementListPtr->size());
          SgStatementPtrList::reverse_iterator transformationStatementIterator;
          for (transformationStatementIterator = newTransformationStatementListPtr->rbegin();
               transformationStatementIterator != newTransformationStatementListPtr->rend();
               transformationStatementIterator++)
             {
            // Modify where a statement is inserted to avoid dependent variables from being inserted
            // before they are declared.

            // Get a list of the variables
            // Generate the list of types used within the target subtree of the AST
               list<string> typeNameStringList = NameQuery::getTypeNamesQuery ( *transformationStatementIterator );

               int statementCounter         = 0;
               int previousStatementCounter = 0;

            // Declaration furthest in source sequence of all variables referenced in code to be inserted (last in source sequence order)
//             SgStatementPtrList::iterator furthestDeclarationInSourceSequence = NULL;
               SgStatementPtrList::iterator furthestDeclarationInSourceSequence;

#if 0
               string unparsedDeclarationCodeString = (*transformationStatementIterator)->unparseToString();
               ROSE_ASSERT (unparsedDeclarationCodeString.c_str() != NULL);
               printf ("unparsedDeclarationCodeString = %s \n",unparsedDeclarationCodeString.c_str());
#endif
               if ( typeNameStringList.size() > 0 )
                  {
                 // There should be at least one type in the statement
                    ROSE_ASSERT (typeNameStringList.size() > 0);
                 // printf ("typeNameStringList.size() = %d \n",typeNameStringList.size());

                 // printf ("This statement has a dependence upon a variable of some type \n");

                 // Loop over all the types and get list of variables of each type
                 // (so they can be declared properly when the transformation is compiled)
                    list<string>::iterator typeListStringElementIterator;
                    for (typeListStringElementIterator = typeNameStringList.begin();
                         typeListStringElementIterator != typeNameStringList.end();
                         typeListStringElementIterator++)
                       {
                      // printf ("Type = %s \n",(*typeListStringElementIterator).c_str());

                      // Find a list of names of variable of type (*listStringElementIterator)
                         list<string> operandNameStringList =
                              NameQuery::getVariableNamesWithTypeNameQuery
                                 ( *transformationStatementIterator, *typeListStringElementIterator );

                      // There should be at least one variable of that type in the statement
                         ROSE_ASSERT (operandNameStringList.size() > 0);
                      // printf ("operandNameStringList.size() = %d \n",operandNameStringList.size());

                      // Loop over all the types and get list of variable of each type
                         list<string>::iterator variableListStringElementIterator;
                         for (variableListStringElementIterator = operandNameStringList.begin();
                              variableListStringElementIterator != operandNameStringList.end();
                              variableListStringElementIterator++)
                            {
#if 0
                              printf ("Type = %s Variable = %s \n",
                                   (*typeListStringElementIterator).c_str(),
                                   (*variableListStringElementIterator).c_str());
#endif
                              string variableName = *variableListStringElementIterator;
                              string typeName     = *typeListStringElementIterator;

                              SgName name = variableName.c_str();
                              SgVariableSymbol* symbol = currentBlock->lookup_var_symbol(name);
                              if ( symbol != NULL )
                                 {
                                // found a variable with name -- make sure that the declarations 
                                // represented by *transformationStatementIterator are inserted 
                                // after their declaration.
#if 0
                                   printf ("Found a valid symbol corresponding to Type = %s Variable = %s (must be defined in the local scope) \n",
                                        (*typeListStringElementIterator).c_str(),
                                        (*variableListStringElementIterator).c_str());
#endif
                                   ROSE_ASSERT (symbol != NULL);
                                   SgInitializedName* declarationInitializedName = symbol->get_declaration();
                                   ROSE_ASSERT (declarationInitializedName != NULL);
                                   SgDeclarationStatement* declarationStatement  =
                                        declarationInitializedName->get_declaration();
                                   ROSE_ASSERT (declarationStatement != NULL);
#if 0
                                   printf ("declarationStatementString located at line = %d of file = %s \n",
                                        rose::getLineNumber(declarationStatement),
                                        rose::getFileName(declarationStatement));
                                   string declarationStatementString = declarationStatement->unparseToString();
                                   printf ("declarationStatementString = %s \n",declarationStatementString.c_str());
#endif
                                   statementCounter = 1;

                                   SgStatementPtrList::iterator i = currentStatementList.begin();
                                   bool declarationFound = false;
                                   while ( ( i != currentStatementList.end() ) && ( declarationFound == false ) )
                                      {
                                     // searching for the declarationStatement
#if 0
                                        printf ("statementCounter = %d previousStatementCounter = %d \n",
                                             statementCounter,previousStatementCounter);
                                        string currentStatementString = (*i)->unparseToString();
                                        printf ("currentStatementString = %s \n",currentStatementString.c_str());
#endif
                                        if ( (*i == declarationStatement) &&
                                             (statementCounter > previousStatementCounter) )
                                           {
                                          // printf ("Found the declarationStatement at position (statementCounter = %d previousStatementCounter = %d) \n",statementCounter,previousStatementCounter);
                                             declarationFound = true;
                                           }
                                          else
                                           {
                                          // printf ("Not the declaration we are looking for! \n");
                                             i++;
                                             statementCounter++;
                                           }
                                      }

                                // Save a reference to the variable declaration that is furthest in
                                // the source sequence so that we can append the new statement just
                                // after it (so that variables referenced in the new statement will
                                // be defined).
                                   if ( (statementCounter > previousStatementCounter) && ( declarationFound == true ) )
                                      {
                                        previousStatementCounter = statementCounter;
                                        furthestDeclarationInSourceSequence = i;
                                      }
#if 0
                                   printf ("AFTER LOOP OVER STATEMENTS: previousStatementCounter = %d \n",previousStatementCounter);
                                   string lastStatementString = (*furthestDeclarationInSourceSequence)->unparseToString();
                                   printf ("lastStatementString = %s \n",lastStatementString.c_str());
#endif
                                 }
                                else
                                 {
                                // If the variable is not found then insert the new statement at the front of the list
#if 0
                                   printf ("Can NOT find a valid symbol corresponding to Type = %s Variable = %s (so it is not declared in the local scope) \n",
                                        (*typeListStringElementIterator).c_str(),
                                        (*variableListStringElementIterator).c_str());
#endif
                                // currentStatementList.push_front(*transformationStatementIterator);
                                 }
#if 0
                              printf ("BOTTOM OF LOOP OVER VARIABLES: previousStatementCounter = %d \n",previousStatementCounter);
#endif
                            }

                         if (statementCounter > previousStatementCounter)
                              previousStatementCounter = statementCounter;

#if 0
                         printf ("BOTTOM OF LOOP OVER TYPES: previousStatementCounter = %d \n",previousStatementCounter);
#endif
#if 0
                         printf ("Exiting in insertSourceCode(): transformationStatementIterator loop (type = %s) ... \n",(*typeListStringElementIterator).c_str());
                         ROSE_ABORT();
#endif
                       }

#if 0
                    printf ("Exiting in loop insertSourceCode (type = %s) ... \n",(*typeListStringElementIterator).c_str());
                    ROSE_ABORT();
#endif
                 // Now append the new statement AFTER the declaration that we have found
                 // currentStatementList.insert(*targetDeclarationStatementIterator,*transformationStatementIterator);
                 // currentStatementList.insert(lastStatementIterator,*transformationStatementIterator);
#if 1
                 // printf ("BEFORE ADDING NEW STATEMENT: previousStatementCounter = %d \n",previousStatementCounter);
                    if (previousStatementCounter == 0)
                       {
                         printf ("##### Prepend new statement to the top of the local scope \n");
                      // currentStatementList.push_front(*transformationStatementIterator);
                         currentBlock->prepend_statement (*transformationStatementIterator);
                       }
                      else
                       {
                      // printf ("##### Append the new statement after the last position where a dependent variable is declared in the local scope \n");
                      // Use new function added to append/prepend at a specified location in the list of statements
                         currentBlock->append_statement (furthestDeclarationInSourceSequence,*transformationStatementIterator);
                       }
#else
                    SgStatementPtrList::iterator tempIterator = furthestDeclarationInSourceSequence;
                    tempIterator++;
                 // Handle the case of appending at the end of the list
                    if ( tempIterator == currentStatementList.end() )
                       {
                         currentBlock->append_statement (*transformationStatementIterator);
                       }
                      else
                       {
                         currentBlock->insert_statement (tempIterator,*transformationStatementIterator);
                       }
#endif
                  }
                 else
                  {
                 // This statement has no type information (so it has no dependence upon any non-primative type)
                 // "int x;" would be an example of a statement that would not generate a type (though perhaps it should?)
                 // printf ("This statement has no type information (so it has no dependence upon any non-primative type) \n");

                 // So this statment can be places at the front of the list of statements in this block
                 // *** Note that we can't use the STL function directly since it does not set the parent information ***
                 // currentStatementList.push_front(*transformationStatementIterator);
                    currentBlock->insert_statement (currentStatementList.begin(),*transformationStatementIterator);
                  }

#if 0
               string bottomUnparsedDeclarationCodeString = (*transformationStatementIterator)->unparseToString();
               ROSE_ASSERT (bottomUnparsedDeclarationCodeString.c_str() != NULL);
               printf ("bottomUnparsedDeclarationCodeString = %s \n",bottomUnparsedDeclarationCodeString.c_str());
#endif
             }

#if 0
          printf ("Exiting in insertSourceCode(): case of locateNewCodeAtTop == true ... \n");
          ROSE_ABORT();
#endif
        }
       else
        {
       // Put the new statements at the end of the list (traverse the new statements from first to last)
       // But put it before any return statement! So find the last statement!
          SgStatementPtrList::iterator lastStatement = currentStatementList.begin();
          bool foundEndOfList = false;
          while ( (foundEndOfList == false) && (lastStatement != currentStatementList.end()) )
             {
               SgStatementPtrList::iterator tempStatement = lastStatement;
               tempStatement++;
               if (tempStatement == currentStatementList.end())
                    foundEndOfList = true;
                 else
                    lastStatement++;
             }
          ROSE_ASSERT ( *lastStatement != NULL );

       // printf ("(*lastStatement)->sage_class_name() = %s \n",(*lastStatement)->sage_class_name());

       // printf ("Insert new statements at the bottom of the block \n");
          SgStatementPtrList::iterator transformationStatementIterator;
          for (transformationStatementIterator = newTransformationStatementListPtr->begin();
               transformationStatementIterator != newTransformationStatementListPtr->end();
               transformationStatementIterator++)
             {
            // If there is a RETURN_STMT in the block then insert the new statement just before the
            // existing RETURN_STMT
               if ( (*lastStatement)->variant() == RETURN_STMT)
                  {
                 // printf ("Backing away from the end of the list to find the last non-return statement \n");
                 // lastStatement--;
                    currentBlock->insert_statement(lastStatement,*transformationStatementIterator);
                  }
                 else
                  {
                    currentStatementList.push_back(*transformationStatementIterator);
                  }
             }
        }

  // printf ("$CLASSNAME::insertSourceCode taking (SgProject,char*,char*) not implemented yet! \n");
  // ROSE_ABORT();
   }
Exemplo n.º 18
0
string
nodeColor( SgStatement* statement )
   {
  /* color: colorCode:red:on
     color: colorCode:orange:on 
     color: colorCode:yellow:on 
     color: colorCode:blue:on 
     color: colorCode:green:on 
     color: colorCode:violet:on 
     color: colorCode:brown:on 
     color: colorCode:purple:on 
     color: colorCode:lightblue:on 
     color: colorCode:lightgreen:on 
     color: colorCode:lightred:on 
     color: colorCode:black:on 
     color: colorCode:darkblue:on 
     color: colorCode:grey:on 
     color: colorCode:darkgrey:on 
     color: colorCode:olivegreen:on 
     color: colorCode:darkgreen:on 
  */
     string returnString;

     SgDeclarationStatement* declarationStatement = isSgDeclarationStatement(statement);
     if (declarationStatement != NULL)
        {
          switch (declarationStatement->variantT())
             {
               case V_SgFunctionDeclaration:
               case V_SgMemberFunctionDeclaration:
               case V_SgTemplateInstantiationFunctionDecl:
               case V_SgTemplateInstantiationMemberFunctionDecl:
                    returnString = "orange";
                    break;

               case V_SgClassDeclaration:
               case V_SgTemplateInstantiationDecl:
                    returnString = "yellow";
                    break;

               case V_SgAsmStmt:
               case V_SgCtorInitializerList:
               case V_SgEnumDeclaration:
               case V_SgFunctionParameterList:
               case V_SgNamespaceAliasDeclarationStatement:
               case V_SgNamespaceDeclarationStatement:
               case V_SgPragmaDeclaration:
               case V_SgTemplateDeclaration:
               case V_SgTemplateInstantiationDirectiveStatement:
               case V_SgTypedefDeclaration:
               case V_SgUsingDeclarationStatement:
               case V_SgUsingDirectiveStatement:
               case V_SgVariableDeclaration:
               case V_SgVariableDefinition:
                    returnString = "lightred";
                    break;

            // DQ (11/11/2012): Added support for newer IR nodes in edg4x work.
               case V_SgTemplateMemberFunctionDeclaration:
               case V_SgTemplateClassDeclaration:
               case V_SgTemplateFunctionDeclaration:
               case V_SgTemplateVariableDeclaration:
                    returnString = "red";
                    break;

               default:
                    returnString = "ERROR DEFAULT REACHED";
                    printf ("Default reached in nodeColor() exiting ... (%s) \n",declarationStatement->class_name().c_str());
                    ROSE_ASSERT(false);
                    break;
             }
        }

     SgScopeStatement* scopeStatement = isSgScopeStatement(statement);
     if (scopeStatement != NULL)
        {
          switch (scopeStatement->variantT())
             {
               case V_SgBasicBlock:
                    returnString = "lightblue";
                    break;

               case V_SgClassDefinition:
                    returnString = "lightblue";
                    break;

               case V_SgTemplateInstantiationDefn:
               case V_SgFunctionDefinition:
                    returnString = "lightblue";
                    break;

               case V_SgWhileStmt:
               case V_SgDoWhileStmt:
               case V_SgForStatement:
                    returnString = "darkblue";
                    break;

               case V_SgGlobal:
               case V_SgIfStmt:
               case V_SgNamespaceDefinitionStatement:
               case V_SgSwitchStatement:
               case V_SgCatchOptionStmt:
                    returnString = "black";
                    break;

            // DQ (11/11/2012): Added support for newer IR nodes in edg4x work.
               case V_SgTemplateClassDefinition:
               case V_SgTemplateFunctionDefinition:
                    returnString = "red";
                    break;

               default:
                    returnString = "ERROR DEFAULT REACHED";
                    printf ("Default reached in nodeColor() exiting ... (%s) \n",scopeStatement->class_name().c_str());
                    ROSE_ASSERT(false);
                    break;
             }
        }

     if (scopeStatement == NULL && declarationStatement == NULL)
        {
          switch (statement->variantT())
             {
               case V_SgExprStatement:
                    returnString = "violet";
                    break;

          case V_SgBreakStmt:
          case V_SgCaseOptionStmt:
          case V_SgCatchStatementSeq:
          case V_SgContinueStmt:
          case V_SgDefaultOptionStmt:
          case V_SgClinkageStartStatement:
          case V_SgForInitStatement:
          case V_SgFunctionTypeTable:
          case V_SgGotoStatement:
          case V_SgLabelStatement:
          case V_SgNullStatement:
          case V_SgReturnStmt:
          case V_SgSpawnStmt:
          case V_SgTryStmt:
          case V_SgVariantStatement:
               returnString = "brown";
               break;

          default:
               returnString = "ERROR DEFAULT REACHED";
               printf ("Default reached in nodeColor() exiting ... (%s) \n",statement->class_name().c_str());
               ROSE_ASSERT(false);
               break;
        }
        }

     return returnString;
   }
bool isDeclaredVirtualWithinClassAncestry(SgFunctionDeclaration *functionDeclaration, SgClassDefinition *classDefinition)
{
  SgType *functionType =
    functionDeclaration->get_type();
  ROSE_ASSERT(functionType != NULL);

  // Look in each of the class' parent classes.
  SgBaseClassPtrList & baseClassList = classDefinition->get_inheritances(); 
  for (SgBaseClassPtrList::iterator i = baseClassList.begin(); 
       i != baseClassList.end(); ++i) {
 
    SgBaseClass *baseClass = *i;
    ROSE_ASSERT(baseClass != NULL);

    SgClassDeclaration *classDeclaration = baseClass->get_base_class(); 
    ROSE_ASSERT(classDeclaration != NULL);

    SgDeclarationStatement *definingDecl =
      classDeclaration->get_definingDeclaration();
    if ( definingDecl == NULL )
      continue;
    
    SgClassDeclaration *definingClassDeclaration =
      isSgClassDeclaration(definingDecl);
    ROSE_ASSERT(classDeclaration != NULL);

    SgClassDefinition *parentClassDefinition =
      definingClassDeclaration->get_definition();

    if ( parentClassDefinition == NULL )
      continue;

    // Visit all methods in the parent class.
    SgDeclarationStatementPtrList &members = 
      parentClassDefinition->get_members(); 

    bool isDeclaredVirtual = false;

    for (SgDeclarationStatementPtrList::iterator it = members.begin(); 
	 it != members.end(); ++it) { 
    
      SgDeclarationStatement *declarationStatement = *it; 
      ROSE_ASSERT(declarationStatement != NULL);
      
      switch(declarationStatement->variantT()) {
      
      case V_SgMemberFunctionDeclaration:
	{
	  SgMemberFunctionDeclaration *memberFunctionDeclaration =  
	    isSgMemberFunctionDeclaration(declarationStatement); 

	  if ( isVirtual(memberFunctionDeclaration) ) {

	    SgType *parentMemberFunctionType =
	      memberFunctionDeclaration->get_type();
	    ROSE_ASSERT(parentMemberFunctionType != NULL);

	    if ( parentMemberFunctionType == functionType ) {
	      return true;
	    }

	  }
	  break;

	}
      default:
	{
	  break;
	}

      }

    }

    if ( isDeclaredVirtualWithinClassAncestry(functionDeclaration, 
					      parentClassDefinition) ) {
      return true;
    }

  }

  return false;
}
// DQ (8/23/2011): Made this a static function so that I could call it from the Java support.
void
FixupAstSymbolTablesToSupportAliasedSymbols::injectSymbolsFromReferencedScopeIntoCurrentScope ( SgScopeStatement* referencedScope, SgScopeStatement* currentScope, SgNode* causalNode, SgAccessModifier::access_modifier_enum accessLevel )
   {
     ROSE_ASSERT(referencedScope != NULL);
     ROSE_ASSERT(currentScope    != NULL);

#if ALIAS_SYMBOL_DEBUGGING || 0
     printf ("In injectSymbolsFromReferencedScopeIntoCurrentScope(): referencedScope = %p = %s currentScope = %p = %s accessLevel = %d \n",referencedScope,referencedScope->class_name().c_str(),currentScope,currentScope->class_name().c_str(),accessLevel);
#endif

     SgSymbolTable* symbolTable = referencedScope->get_symbol_table();
     ROSE_ASSERT(symbolTable != NULL);
     
#if 0
     printf ("AST Fixup: Building Symbol Table for %p = %s at: \n",scope,scope->sage_class_name());
     referencedScope->get_file_info()->display("Symbol Table Location");
#endif

     SgClassDefinition* classDefinition = isSgClassDefinition(referencedScope);
     if (classDefinition != NULL)
        {
       // If this is a class definition, then we need to make sure that we only for alias symbols for those declarations.
#if ALIAS_SYMBOL_DEBUGGING
          printf ("Injection of symbols from a class definition needs to respect access priviledge (private, protected, public) declarations \n");
#endif
        }

     SgSymbolTable::BaseHashType* internalTable = symbolTable->get_table();
     ROSE_ASSERT(internalTable != NULL);

     int counter = 0;
     SgSymbolTable::hash_iterator i = internalTable->begin();
     while (i != internalTable->end())
        {
       // DQ: removed SgName casting operator to char*
       // cout << "[" << idx << "] " << (*i).first.str();
          ROSE_ASSERT ( (*i).first.str() != NULL );
          ROSE_ASSERT ( isSgSymbol( (*i).second ) != NULL );

#if ALIAS_SYMBOL_DEBUGGING
          printf ("Symbol number: %d (pair.first (SgName) = %s) pair.second (SgSymbol) class_name() = %s \n",counter,(*i).first.str(),(*i).second->class_name().c_str());
#endif
          SgName name      = (*i).first;
          SgSymbol* symbol = (*i).second;

          ROSE_ASSERT ( symbol != NULL );

       // Make sure that this is not a SgLabelSymbol, I think these should not be aliased
       // (if only because I don't think that C++ support name qualification for labels).
          ROSE_ASSERT ( isSgLabelSymbol(symbol) == NULL );

       // DQ (6/22/2011): For now skip the handling of alias symbol from other scopes.
       // ROSE_ASSERT(isSgAliasSymbol(symbol) == NULL);
          if (isSgAliasSymbol(symbol) != NULL)
             {
#if ALIAS_SYMBOL_DEBUGGING
               printf ("WARNING: Not clear if we want to nest SgAliasSymbol inside of SgAliasSymbol \n");
#endif
            // DQ (9/22/2012): We need to avoid building chains of SgAliasSymbol (to simplify the representation in the AST).
               while (isSgAliasSymbol(symbol) != NULL)
                  {
#if ALIAS_SYMBOL_DEBUGGING
                    printf (" --- Iterating to root of alias: symbol = %p = %s \n",symbol,symbol->class_name().c_str());
#endif
                    symbol = isSgAliasSymbol(symbol)->get_alias();
                    ROSE_ASSERT(symbol != NULL);
                  }

#if ALIAS_SYMBOL_DEBUGGING
               printf ("Resolved aliased symbol to root symbol: symbol = %p = %s \n",symbol,symbol->class_name().c_str());
#endif
             }

          SgNode* symbolBasis = symbol->get_symbol_basis();
          ROSE_ASSERT(symbolBasis != NULL);
#if ALIAS_SYMBOL_DEBUGGING
          printf ("symbolBasis = %p = %s \n",symbolBasis,symbolBasis->class_name().c_str());
#endif
       // SgDeclarationStatement* declarationFromSymbol = symbol->get_declaration();
          SgDeclarationStatement* declarationFromSymbol = isSgDeclarationStatement(symbolBasis);

          SgAccessModifier::access_modifier_enum declarationAccessLevel = SgAccessModifier::e_unknown;

       // ROSE_ASSERT(declarationFromSymbol != NULL);
          if (declarationFromSymbol != NULL)
             {
            // DQ (6/22/2011): Can I, or should I, do relational operations on enum values (note that the values are designed to allow this).
               declarationAccessLevel = declarationFromSymbol->get_declarationModifier().get_accessModifier().get_modifier();
             }
            else
             {
               SgInitializedName* initializedNameFromSymbol = isSgInitializedName(symbolBasis);
               ROSE_ASSERT(initializedNameFromSymbol != NULL);

            // DQ (9/8/2014): This fails for test2013_234, 235, 240, 241, 242, 246.C.
            // ROSE_ASSERT(initializedNameFromSymbol->get_declptr() != NULL);
            // declarationAccessLevel = initializedNameFromSymbol->get_declptr()->get_declarationModifier().get_accessModifier().get_modifier();
               if (initializedNameFromSymbol->get_declptr() != NULL)
                  {
                    declarationAccessLevel = initializedNameFromSymbol->get_declptr()->get_declarationModifier().get_accessModifier().get_modifier();
                  }
                 else
                  {
                    mprintf ("WARNING: In injectSymbolsFromReferencedScopeIntoCurrentScope(): initializedNameFromSymbol->get_declptr() == NULL: initializedNameFromSymbol->get_name() = %s \n",initializedNameFromSymbol->get_name().str());
                  }
             }

#if ALIAS_SYMBOL_DEBUGGING || 0
          printf ("declarationAccessLevel = %d accessLevel = %d \n",declarationAccessLevel,accessLevel);
#endif

#if 0
       // DQ (12/23/2015): Is this only supporting the SgBaseClass IR nodes? No, another example is the case of a SgUsingDirectiveStatement.
          ROSE_ASSERT(causalNode != NULL);
          if (isSgBaseClass(causalNode) == NULL)
             {
               printf ("ERROR: This is not a SgBaseClass: causalNode = %p = %s \n",causalNode,causalNode->class_name().c_str());
               ROSE_ASSERT(false);
             }
#endif

       // DQ (12/23/2015): See test2015_140.C for where even private base classes will require representations 
       // of it's symbols in the derived class (to support correct name qualification).
       // if (declarationAccessLevel >= accessLevel)
          if ( (declarationAccessLevel >= accessLevel) || isSgBaseClass(causalNode) != NULL)
             {
            // This declaration is visible, so build an alias.

            // DQ (7/24/2011): Need to make sure that the symbol is not already present in the symbol table 
            // (else injection would be redundant. This is a likely key to the problem we are having with 
            // symbol table explosions for some codes.  This should be refactored to a member function of 
            // the symbol table support.
            // Note that this change improves the performance from 15 minutes to 5 seconds for the outlining example.
               bool alreadyExists = currentScope->symbol_exists(name);
               if (alreadyExists == true)
                  {
                 // Just because the names match is not strong enough.
                 // SgSymbol* symbol currentScope->symbol_exists(name);
                    switch (symbol->variantT())
                       {
                         case V_SgAliasSymbol:
                            {
                           // not clear what to do here...
                           // I think we need more symbol table support for detecting matching symbols.
                           // I think we also need more alias symbol specific query support.
                              break;
                            }

                      // DQ (11/10/2014): Added support for templated typedef symbols.
                         case V_SgTemplateTypedefSymbol:

                         case V_SgEnumSymbol:
                         case V_SgVariableSymbol:
                         case V_SgTemplateClassSymbol:
                         case V_SgClassSymbol:
                         case V_SgTemplateFunctionSymbol:
                         case V_SgTemplateMemberFunctionSymbol:
                         case V_SgFunctionSymbol:
                         case V_SgMemberFunctionSymbol:
                         case V_SgTypedefSymbol:
                         case V_SgEnumFieldSymbol:
                         case V_SgNamespaceSymbol:
                         case V_SgTemplateSymbol:
                         case V_SgLabelSymbol:
                         {
                           // Liao, 10/31/2012. 
                           // Using lookup_function_symbol () etc. is not good enough since it returns the first match only.
                           // There might be multiple hits. We have to go through them all instead of checking only the first hit
                              alreadyExists = false; // reset to be false
                             // using less expensive equal_range(), which can be O(logN) instead of O(N)
                              // This matters since this function is called inside another loop with complexity of O(N) already.
                              rose_hash_multimap * internal_table = currentScope->get_symbol_table()->get_table();
                              ROSE_ASSERT (internal_table != NULL);
                              std::pair<rose_hash_multimap::iterator, rose_hash_multimap::iterator> range = internal_table ->equal_range (name);
                              for (rose_hash_multimap::iterator i = range.first; i != range.second; ++i)
                              {
                                SgSymbol * orig_current_symbol = i->second; 
                                ROSE_ASSERT (orig_current_symbol != NULL);
                                // strip off alias symbols
                                SgSymbol * non_alias_symbol = orig_current_symbol; 
                                while (isSgAliasSymbol(non_alias_symbol))
                                {
                                  non_alias_symbol = isSgAliasSymbol(non_alias_symbol) ->get_alias();
                                  ROSE_ASSERT (non_alias_symbol != NULL);
                                }
                                SgNode* associatedDeclaration = i->second->get_symbol_basis();
                                assert(associatedDeclaration != NULL);
                                // same basis and same symbol type
                                // The assumption is that no two symbols can share the same basis declaration TODO double check this!
                                if (associatedDeclaration == symbolBasis && (non_alias_symbol->variantT() == symbol->variantT()))
                                {
                                  alreadyExists = true;
                                  break;
                                }
                              } // end for
                              break;
                           }


#if 0 // uniform handling by code above now
                         case V_SgEnumSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_enum_symbol(name) != NULL);
                              SgEnumSymbol* tmpSymbol = currentScope->lookup_enum_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }

                         case V_SgVariableSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_variable_symbol(name) != NULL);
                              SgVariableSymbol* tmpSymbol = currentScope->lookup_variable_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }

                      // DQ (2/12/2012): Not clear if this is the best way to add this support.
                         case V_SgTemplateClassSymbol:
                         case V_SgClassSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_class_symbol(name) != NULL);
                              SgClassSymbol* tmpSymbol = currentScope->lookup_class_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }
#if 0
                      // DQ (2/12/2012): Added support for SgTemplateFunctionSymbol.
                         case V_SgTemplateFunctionSymbol:
                            {
                              SgTemplateFunctionSymbol* tmpSymbol = currentScope->lookup_template_function_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }

                      // DQ (2/12/2012): Added support for SgTemplateMemberFunctionSymbol.
                         case V_SgTemplateMemberFunctionSymbol:
                            {
                              SgTemplateMemberFunctionSymbol* tmpSymbol = currentScope->lookup_template_member_function_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }
#else
                      // DQ (2/12/2012): Not clear if this is the best way to add this support.
                         case V_SgTemplateFunctionSymbol:
                         case V_SgTemplateMemberFunctionSymbol:
#endif
                         case V_SgFunctionSymbol:
                         case V_SgMemberFunctionSymbol:
                            {
                            // alreadyExists = (currentScope->lookup_function_symbol(name) != NULL);
                              SgFunctionSymbol* tmpSymbol = currentScope->lookup_function_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                             break;
                            }
                         case V_SgTypedefSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_typedef_symbol(name) != NULL);
                              SgTypedefSymbol* tmpSymbol = currentScope->lookup_typedef_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }
                         case V_SgEnumFieldSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_enum_field_symbol(name) != NULL);
                              SgEnumFieldSymbol* tmpSymbol = currentScope->lookup_enum_field_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }

                         case V_SgNamespaceSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_namespace_symbol(name) != NULL);
                              SgNamespaceSymbol* tmpSymbol = currentScope->lookup_namespace_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }

                         case V_SgTemplateSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_template_symbol(name) != NULL);
                              SgTemplateSymbol* tmpSymbol = currentScope->lookup_template_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }

                         case V_SgLabelSymbol:
                            {
                           // alreadyExists = (currentScope->lookup_label_symbol(name) != NULL);
                              SgLabelSymbol* tmpSymbol = currentScope->lookup_label_symbol(name);
                              if (tmpSymbol != NULL)
                                 {
                                   SgNode* tmpSymbolBasis = tmpSymbol->get_symbol_basis();
                                   ROSE_ASSERT(tmpSymbolBasis != NULL);
                                   alreadyExists = (tmpSymbolBasis == symbolBasis);
                                 }
                              break;
                            }

#endif
                         default:
                              printf ("Error: default reached in switch symbol = %p = %s \n",symbol,symbol->class_name().c_str());
                              ROSE_ASSERT(false);
                              break;
                       }
                  }
               
               if ( alreadyExists == false)
                  {
#if 0
                    printf ("Building a SgAliasSymbol \n");
#endif
                 // DQ: The parameter to a SgAliasSymbol is a SgSymbol (but should not be another SgAliasSymbol).
                    SgAliasSymbol* aliasSymbol = new SgAliasSymbol(symbol);
                    ROSE_ASSERT(aliasSymbol != NULL);

                 // DQ (7/12/2014): Added support to trace back the SgAliasSymbol to the declarations that caused it to be added.
                    ROSE_ASSERT(causalNode != NULL);
                    aliasSymbol->get_causal_nodes().push_back(causalNode);

#if ALIAS_SYMBOL_DEBUGGING
                 // printf ("In injectSymbolsFromReferencedScopeIntoCurrentScope(): Adding symbol to new scope as a SgAliasSymbol = %p causalNode = %p = %s \n",aliasSymbol,causalNode,causalNode->class_name().c_str());
                    printf ("In injectSymbolsFromReferencedScopeIntoCurrentScope(): Adding symbol to new scope (currentScope = %p = %s) as a SgAliasSymbol = %p causalNode = %p = %s \n",currentScope,currentScope->class_name().c_str(),aliasSymbol,causalNode,causalNode->class_name().c_str());
#endif
                 // Use the current name and the alias to the symbol
                    currentScope->insert_symbol(name, aliasSymbol);

#if ALIAS_SYMBOL_DEBUGGING
                    printf ("In injectSymbolsFromReferencedScopeIntoCurrentScope(): DONE: Adding symbol to new scope (currentScope = %p = %s) as a SgAliasSymbol = %p causalNode = %p = %s \n",currentScope,currentScope->class_name().c_str(),aliasSymbol,causalNode,causalNode->class_name().c_str());
#endif
                  }
             }
            else
             {
#if ALIAS_SYMBOL_DEBUGGING
               printf ("NO SgAliasSymbol ADDED (wrong permissions): declarationFromSymbol = %p \n",declarationFromSymbol);
#endif
             }
#if 0
       // Older version of code...
       // SgAliasSymbol* aliasSymbol = new SgAliasSymbol (SgSymbol *alias=NULL, bool isRenamed=false, SgName new_name="")
          SgAliasSymbol* aliasSymbol = new SgAliasSymbol (symbol);

       // Use the current name and the alias to the symbol
          currentScope->insert_symbol(name, aliasSymbol);
#endif

       // Increment iterator and counter
          i++;
          counter++;
        }

#if 0
  // debugging
     symbolTable->print("In injectSymbolsFromReferencedScopeIntoCurrentScope(): printing out the symbol tables");
#endif
#if ALIAS_SYMBOL_DEBUGGING
     printf ("In injectSymbolsFromReferencedScopeIntoCurrentScope(): referencedScope = %p = %s currentScope = %p = %s accessLevel = %d \n",referencedScope,referencedScope->class_name().c_str(),currentScope,currentScope->class_name().c_str(),accessLevel);
#endif
   }
Exemplo n.º 21
0
void
MangledNameMapTraversal::visit ( SgNode* node)
   {
     ROSE_ASSERT(node != NULL);

#if 0
     printf ("MangledNameMapTraversal::visit: node = %s \n",node->class_name().c_str());
#endif

  // Keep track of the number of IR nodes visited
     numberOfNodes++;

  // DQ (7/4/2010): Optimizations:
  //   1) Only process each IR node once
  //   2) Only process declarations that we want to share (can we be selective?).

  // DQ (7/4/2010): To optimize performance, build a set of previously visited IR nodes
  // so that we only test IR nodes once to add them into the mangled name map. This 
  // should be especially important where the AST is sharing nodes since shared nodes 
  // are visited multiple times (as if they were not shared).
  // We need to tet if this actually optimizes the performance.
     if (setOfNodesPreviouslyVisited.find(node) == setOfNodesPreviouslyVisited.end())
        {
          setOfNodesPreviouslyVisited.insert(node);
        }
       else
        {
          return;
        }

     bool sharable = shareableIRnode(node);

#if 0
     printf ("MangledNameMapTraversal::visit: node = %p = %s sharable = %s \n",node,node->class_name().c_str(),sharable ? "true" : "false");
#endif

  // DQ (7/10/2010): This is a test of the AST merge to investigate robustness.
#if 1

     if (sharable == true)
        {
       // Initially we will only merge things in global scope!  Then
       // we will operate on namespaces! Then I think we are done!
       // Basically we can simplify the problem by skipping merging of things in 
       // function definitions since if the function definitions are the same they 
       // will be merged directly.

       // Keep track of the number of IR nodes that were considered sharable
          numberOfNodesSharable++;

       // Here is where we get much more specific about what is sharable!
          switch (node->variantT())
             {
            // Since we abstract out the generation of the key we can simplify this code!
#if 1
            // DQ (7/11/2010): This fails for tests/nonsmoke/functional/CompileTests/mergeAST_tests/mergeTest_06.C, I don't know why!
               case V_SgFunctionDeclaration:
#endif
#if 1
            // DQ (7/20/2010): Testing this case...
               case V_SgVariableDeclaration:
               case V_SgClassDeclaration:

            // DQ (2/10/2007): These need to be shared (but I still see "xxxxx____Lnnnn" based names)
               case V_SgTemplateInstantiationDecl:

            // DQ (2/10/2007): These should be shared
               case V_SgPragmaDeclaration:
               case V_SgTemplateInstantiationDirectiveStatement:

               case V_SgTypedefDeclaration:
               case V_SgEnumDeclaration:
               case V_SgTemplateDeclaration:
               case V_SgUsingDeclarationStatement:
               case V_SgUsingDirectiveStatement:

            // DQ (2/3/2007): Added additional declarations that we should share
               case V_SgMemberFunctionDeclaration:
               case V_SgTemplateInstantiationFunctionDecl:
               case V_SgTemplateInstantiationMemberFunctionDecl:
#endif
#if 1
            // DQ (2/3/2007): Added support for symbols
               case V_SgClassSymbol:
               case V_SgEnumFieldSymbol:
               case V_SgEnumSymbol:
               case V_SgFunctionSymbol:
               case V_SgMemberFunctionSymbol:
               case V_SgLabelSymbol:
               case V_SgNamespaceSymbol:

            // DQ (2/10/2007): This case has been a problem previously
               case V_SgTemplateSymbol:

               case V_SgTypedefSymbol:
               case V_SgVariableSymbol:

#endif
#if 0
            // DQ (7/20/2010): These nodes are a problem to merge, but also not important to merge 
            // since they are contained within associated declarations.

            // DQ (2/20/2007): Added to list so that it could be process to build the delete list
            // statement fo the SgBasicBlock have to be considerd for the delete list. However,
            // it is still not meaningful since we don't generate a unique name for the SgBasicBlock
            // so it will never be shared.
            // case V_SgBasicBlock:

               case V_SgClassDefinition:
               case V_SgTemplateInstantiationDefn:
               case V_SgFunctionDefinition:
               case V_SgVariableDefinition:
#endif
#if 1
            // DQ (5/29/2006): Added support for types
               case V_SgFunctionType:
               case V_SgMemberFunctionType:
               case V_SgModifierType:
               case V_SgPointerType:

            // DQ (5/29/2006): Added support for types
               case V_SgClassType:
               case V_SgEnumType:
               case V_SgTypedefType:

            // DQ (2/10/2007): Add this case
               case V_SgTemplateArgument:

            // DQ (3/17/2007): These should be shared, I think!
               case V_SgPragma:
            // DQ (5/20/2006): Initialized names are held in SgVariableDeclaration IR
            // nodes or other sharable structures so we don't have to share these.
            // But we have to permit them all to be shared because all pointers to 
            // them need to be reset they all need to be reset.
               case V_SgInitializedName:
#endif
#if 1
                  {
                 // DQ (7/4/2010): To improve the performance avoid regenerating the unique name for the same IR nodes when it is revisited!

                 // Make the use of false in generateUniqueName() more clear.  We need to 
                 // distinguish between defining and non-defining declarations in the generation 
                 // of unique names for the AST merge.
                 // string key = generateUniqueName(node,false);
                    bool ignoreDifferenceBetweenDefiningAndNondefiningDeclarations = false;
                    string key = SageInterface::generateUniqueName(node,ignoreDifferenceBetweenDefiningAndNondefiningDeclarations);
                    ROSE_ASSERT(key.empty() == false);
#if 1
                    SgDeclarationStatement* declaration = isSgDeclarationStatement(node);
                    if (declaration != NULL)
                       {
                      // ROSE_ASSERT(declaration->get_symbol_from_symbol_table() != NULL);

                      // DQ (7/4/2007): Some SgDeclarationStatement IR nodes don't have a representation 
                      // in the symbol table (the list of SgInitializedName object have them instead).
                         if (isSgVariableDeclaration(declaration) == NULL && 
                             isSgVariableDefinition(declaration) == NULL && 
                             isSgUsingDeclarationStatement(declaration) == NULL && 
                             isSgUsingDirectiveStatement(declaration) == NULL && 
                             isSgTemplateInstantiationDirectiveStatement(declaration) == NULL && 
                             isSgPragmaDeclaration(declaration) == NULL)
                            {
                           // DQ (6/8/2010): Only do this test for non compiler generated variable...(e.g. __default_member_function_pointer_name 
                           // is compiler generated to handle function pointers where no member function id specified).
                              if (declaration->get_startOfConstruct()->isCompilerGenerated() == false)
                                 {
                                   SgSymbol* symbol = declaration->search_for_symbol_from_symbol_table();
                                   if (symbol == NULL)
                                      {
                                     // Output more information to support debugging!
                                        printf ("declaration = %p = %s = %s \n",declaration,declaration->class_name().c_str(),SageInterface::get_name(declaration).c_str());
                                        SgScopeStatement* scope = declaration->get_scope();
                                        ROSE_ASSERT(scope != NULL);
                                        printf ("     scope = %p = %s = %s \n",scope,scope->class_name().c_str(),SageInterface::get_name(scope).c_str());
                                        declaration->get_startOfConstruct()->display("declaration->search_for_symbol_from_symbol_table() == NULL");
                                      }
                                   ROSE_ASSERT(symbol != NULL);
                                 }
                            }
#if 0
                      // DQ (6/23/2010): Added the base type of the typedef
                         SgTypedefDeclaration* typedefDeclaration = isSgTypedefDeclaration(declaration);
                         if (typedefDeclaration != NULL)
                            {
                            }
#endif 
                       }
#endif

                    addToMap(key,node);

                 // Keep track of the number of IR nodes that were evaluated for mangled name matching
                    numberOfNodesEvaluated++;
                    break;
                  }
#endif
               default:
                  {
                 // Nothing to do here
                  }
             }
        }
#endif
   }
void
FixupAstDeclarationScope::visit ( SgNode* node )
   {
  // DQ (6/11/2013): This corrects where EDG can set the scope of a friend declaration to be different from the defining declaration.
  // We need it to be a rule in ROSE that the scope of the declarations are consistant between defining and all non-defining declaration).

#if 0
     printf ("In FixupAstDeclarationScope::visit(node = %p = %s) \n",node,node->class_name().c_str());
#endif

     SgDeclarationStatement* declaration = isSgDeclarationStatement(node);
     if (declaration != NULL)
        {
       // SgDeclarationStatement* definingDeclaration         = declaration->get_definingDeclaration();
          SgDeclarationStatement* firstNondefiningDeclaration = declaration->get_firstNondefiningDeclaration();

       // Note that these declarations don't follow the same rules (namely the get_firstNondefiningDeclaration() can be NULL).
          if ( isSgFunctionParameterList(node) != NULL || isSgVariableDefinition(node) != NULL)
             {
#if 0
               printf ("In FixupAstDeclarationScope::visit(): node = %p = %s firstNondefiningDeclaration = %p (skipping this processing) \n",node,node->class_name().c_str(),firstNondefiningDeclaration);
#endif
             }
            else
             {
            // DQ (6/15/2013): The older tutorial examples demonstrate addition of new functions using older rules that allows 
            // there to not be a non-defining declaration.  We need to remove these tutrial example in favor of the AST builder
            // API to build functions that will follow the newer AST constistancy rules.  Until we do this work in the tutorial
            // we can't inforce this below else the older tutorial examples (e.g. addFunctionDeclaration.C) will fail.  So I will
            // allow this for now and output a warning when (firstNondefiningDeclaration == NULL).
            // ROSE_ASSERT(firstNondefiningDeclaration != NULL);
               if (firstNondefiningDeclaration == NULL)
                  {
                    printf ("WARNING: In FixupAstDeclarationScope::visit(): firstNondefiningDeclaration == NULL for case of node = %p = %s (allowed for tutorial example transformations only) \n",node,node->class_name().c_str());
                  }
                 else
                  {
                    if (mapOfSets.find(firstNondefiningDeclaration) == mapOfSets.end())
                       {
                         std::set<SgDeclarationStatement*>* new_empty_set = new std::set<SgDeclarationStatement*>();
                         ROSE_ASSERT(new_empty_set != NULL);
#if 0
                         printf ("In FixupAstDeclarationScope::visit(): Adding a set of declarations to the mapOfSets: new_empty_set = %p \n",new_empty_set);
#endif
                      // DQ (3/2/2015): Added assertion.
                         ROSE_ASSERT(firstNondefiningDeclaration != NULL);

                         mapOfSets.insert(std::pair<SgDeclarationStatement*,std::set<SgDeclarationStatement*>*>(firstNondefiningDeclaration,new_empty_set));
                       }

                    ROSE_ASSERT(mapOfSets.find(firstNondefiningDeclaration) != mapOfSets.end());

                 // DQ (3/2/2015): Added assertion.
                    ROSE_ASSERT(declaration != NULL);
#if 0
                    printf ("In FixupAstDeclarationScope::visit(): Adding a declaration = %p = %s to a specific set in the mapOfSets: mapOfSets[firstNondefiningDeclaration=%p] = %p \n",
                         declaration,declaration->class_name().c_str(),firstNondefiningDeclaration,mapOfSets[firstNondefiningDeclaration]);
                    printf ("   --- declaration->get_firstNondefiningDeclaration() = %p \n",declaration->get_firstNondefiningDeclaration());
#endif
                 // DQ (3/2/2015): Added assertion.
                 // ROSE_ASSERT(declaration == declaration->get_firstNondefiningDeclaration());

                 // mapOfSets[firstNondefiningDeclaration]->insert(firstNondefiningDeclaration);
                    mapOfSets[firstNondefiningDeclaration]->insert(declaration);
                  }
             }
        }
   }
void fixupAstDeclarationScope( SgNode* node )
   {
  // This function was designed to fixup what I thought were inconsistancies in how the 
  // defining and some non-defining declarations associated with friend declarations had 
  // their scope set.  I now know this this was not a problem, but it is helpful to enforce the
  // consistancy.  It might also be useful to process declarations with scopes set to 
  // namespace definitions, so that the namespace definition can be normalized to be 
  // consistant across all of the different re-entrant namespace definitions.  This is 
  // possible within the new namespace support in ROSE.

     TimingPerformance timer ("Fixup declaration scopes:");

  // This simplifies how the traversal is called!
     FixupAstDeclarationScope astFixupTraversal;

  // DQ (1/29/2007): This traversal now uses the memory pool (so that we will visit declaration hidden in types (e.g. SgClassType)
  // SgClassType::traverseMemoryPoolNodes(v);
     astFixupTraversal.traverseMemoryPool();

  // Now process the map of sets of declarations.
     std::map<SgDeclarationStatement*,std::set<SgDeclarationStatement*>* > & mapOfSets = astFixupTraversal.mapOfSets;

#if 0
     printf ("In fixupAstDeclarationScope(): mapOfSets.size() = %" PRIuPTR " \n",mapOfSets.size());
#endif

     std::map<SgDeclarationStatement*,std::set<SgDeclarationStatement*>* >::iterator i = mapOfSets.begin();
     while (i != mapOfSets.end())
        {
          SgDeclarationStatement* firstNondefiningDeclaration = i->first;

       // DQ (3/2/2015): Added assertion.
          ROSE_ASSERT(firstNondefiningDeclaration != NULL);

       // DQ (3/2/2015): Added assertion.
          ROSE_ASSERT(firstNondefiningDeclaration->get_firstNondefiningDeclaration() != NULL);
 
       // DQ (3/2/2015): Make this assertion a warning: fails in outlining example seq7a_test2006_78.C.
       // ROSE_ASSERT(firstNondefiningDeclaration == firstNondefiningDeclaration->get_firstNondefiningDeclaration());
          if (firstNondefiningDeclaration != firstNondefiningDeclaration->get_firstNondefiningDeclaration())
             {
               printf ("WARNING: In fixupAstDeclarationScope(): firstNondefiningDeclaration != firstNondefiningDeclaration->get_firstNondefiningDeclaration() \n");
               printf ("   --- firstNondefiningDeclaration = %p = %s \n",
                    firstNondefiningDeclaration,firstNondefiningDeclaration->class_name().c_str());
               printf ("   --- firstNondefiningDeclaration->get_firstNondefiningDeclaration() = %p = %s \n",
                    firstNondefiningDeclaration->get_firstNondefiningDeclaration(),firstNondefiningDeclaration->get_firstNondefiningDeclaration()->class_name().c_str());
             }

          SgScopeStatement* correctScope = firstNondefiningDeclaration->get_scope();
          ROSE_ASSERT(correctScope != NULL);

#if 0
          printf ("In FixupAstDeclarationScope::visit(): node = %p = %s firstNondefiningDeclaration = %p correctScope = %p = %s \n",node,node->class_name().c_str(),firstNondefiningDeclaration,correctScope,correctScope->class_name().c_str());
#endif

          std::set<SgDeclarationStatement*>* declarationSet = i->second;
          ROSE_ASSERT(declarationSet != NULL);

#if 0
          printf ("In fixupAstDeclarationScope(): mapOfSets[%p]->size() = %" PRIuPTR " \n",firstNondefiningDeclaration,mapOfSets[firstNondefiningDeclaration]->size());
#endif

          std::set<SgDeclarationStatement*>::iterator j = declarationSet->begin();
          while (j != declarationSet->end())
             {
               SgScopeStatement* associatedScope = (*j)->get_scope();
               ROSE_ASSERT(associatedScope != NULL);

            // DQ (6/11/2013): This is triggered by namespace definition scopes that are different 
            // due to re-entrant namespace declarations.  We should maybe fix this.
            // TV (7/22/13): This is also triggered when for global scope accross files.
               if (associatedScope != correctScope)
                  {
                 // DQ (1/30/2014): Cleaning up some output spew.
                    if (SgProject::get_verbose() > 0)
                       {
                         mprintf ("WARNING: This is the wrong scope (declaration = %p = %s): associatedScope = %p = %s correctScope = %p = %s \n",
                              *j,(*j)->class_name().c_str(),associatedScope,associatedScope->class_name().c_str(),correctScope,correctScope->class_name().c_str());
                       }
#if 0
                    printf ("Make this an error for now! \n");
                    ROSE_ASSERT(false);
#endif
                  }

               j++;
             }

          i++;
        }

#if 0
     printf ("Leaving fixupAstDeclarationScope() node = %p = %s \n",node,node->class_name().c_str());
#endif
   }
Exemplo n.º 24
0
// void FixupTemplateArguments::visit ( SgNode* node )
void
FixupTemplateArguments::processTemplateArgument ( SgTemplateArgument* templateArgument, SgScopeStatement* targetScope )
   {
  // ROSE_ASSERT(node != NULL);
     ROSE_ASSERT(templateArgument != NULL);

#if DEBUGGING_USING_RECURSIVE_DEPTH
  // For debugging, keep track of the recursive depth.
     printf ("In FixupTemplateArguments::visit: global_depth = %zu \n",global_depth);
     ROSE_ASSERT(global_depth < 50);
#endif

  // DQ (2/11/2017): Change this traversal to not use memory pools.
  // SgTemplateArgument* templateArgument = isSgTemplateArgument(node);
     ROSE_ASSERT(templateArgument != NULL);

#if DEBUGGING_USING_RECURSIVE_DEPTH
     global_depth++;
#endif

     bool result = contains_private_type(templateArgument,targetScope);

#if DEBUGGING_USING_RECURSIVE_DEPTH
     global_depth--;
#endif

     if (result == true)
        {
       // This type will be a problem to unparse, because it contains parts that are private (or protected).
#if DEBUG_VISIT_PRIVATE_TYPE
          printf ("\n\nWARNING: This template parameter can NOT be unparsed (contains references to private types): templateArgument = %p = %s \n",templateArgument,templateArgument->unparseToString().c_str());
          SgNode* parent = templateArgument->get_parent();
          SgDeclarationStatement* parentDeclaration = isSgDeclarationStatement(parent);
          if (parentDeclaration != NULL)
             {
               if (parentDeclaration->get_file_info() != NULL)
                  {
#if 0
                    parentDeclaration->get_file_info()->display("location of parent non-defining declaration using templateArgument: debug");
                    SgDeclarationStatement* parentDefiningDeclaration = isSgDeclarationStatement(parentDeclaration->get_definingDeclaration());
                    if (parentDefiningDeclaration != NULL)
                       {
                         parentDefiningDeclaration->get_file_info()->display("location of parent defining declaration using templateArgument: debug");
                       }
#endif
                  }
             }
            else
             {
               if (parent->get_file_info() != NULL)
                  {
#if 0
                    parent->get_file_info()->display("location of parent node using templateArgument: debug");
#endif
                  }
             }
#endif
        }
       else
        {
       // This type is fine to unparse
#if DEBUG_PRIVATE_TYPE
          printf ("Template parameter CAN be unparsed (no private types) \n\n");
#endif
        }
   }
Exemplo n.º 25
0
void
FixupAstSymbolTables::visit ( SgNode* node )
   {
  // DQ (6/27/2005): Output the local symbol table from each scope.
  // printf ("node = %s \n",node->sage_class_name());

     SgScopeStatement* scope = isSgScopeStatement(node);
     if (scope != NULL)
        {
#if 0
          printf ("AST Fixup: Fixup Symbol Table for %p = %s at: \n",scope,scope->class_name().c_str());
#endif
          SgSymbolTable* symbolTable = scope->get_symbol_table();
          if (symbolTable == NULL)
             {
#if 0
               printf ("AST Fixup: Fixup Symbol Table for %p = %s at: \n",scope,scope->class_name().c_str());
               scope->get_file_info()->display("Symbol Table Location");
#endif
               SgSymbolTable* tempSymbolTable = new SgSymbolTable();
               ROSE_ASSERT(tempSymbolTable != NULL);

            // name this table as compiler generated! The name is a static member used to store 
            // state for the next_symbol() functions. It is meaningless to set these.
            // tempSymbolTable->set_name("compiler-generated symbol table");

               scope->set_symbol_table(tempSymbolTable);

            // reset the symbolTable using the get_symbol_table() member function
               symbolTable = scope->get_symbol_table();
               ROSE_ASSERT(symbolTable != NULL);

            // DQ (2/16/2006): Set this parent directly (now tested)
               symbolTable->set_parent(scope);
               ROSE_ASSERT(symbolTable->get_parent() != NULL);
             }
          ROSE_ASSERT(symbolTable != NULL);

          if (symbolTable->get_parent() == NULL)
             {
               printf ("Warning: Fixing up symbolTable, calling symbolTable->set_parent() (parent not previously set) \n");
               symbolTable->set_parent(scope);
             }
          ROSE_ASSERT(symbolTable->get_parent() != NULL);

       // Make sure that the internal hash table used in the symbol table is also present!
          if (symbolTable->get_table() == NULL)
             {
            // DQ (6/27/2005): There are a lot of these built, perhaps more than we really need!
#if 0
               printf ("AST Fixup: Building internal Symbol Table hash table (rose_hash_multimap) for %p = %s at: \n",
                    scope,scope->sage_class_name());
               scope->get_file_info()->display("Symbol Table Location");
#endif
               rose_hash_multimap* internalHashTable = new rose_hash_multimap();
               ROSE_ASSERT(internalHashTable != NULL);
               symbolTable->set_table(internalHashTable);
             }
          ROSE_ASSERT(symbolTable->get_table() != NULL);

          SgSymbolTable::BaseHashType* internalTable = symbolTable->get_table();
          ROSE_ASSERT(internalTable != NULL);


       // DQ (6/23/2011): Note: Declarations that reference types that have not been seen yet may be placed into the 
       // wronge scope, then later when we see the correct scope we have a symbol in two or more symbol tables.  The 
       // code below detects and fixes this problem.

       // DQ (6/16/2011): List of symbols we need to remove from symbol tables where they are multibily represented.
          std::vector<SgSymbol*> listOfSymbolsToRemove;

       // DQ (6/12/2011): Fixup symbol table by removing symbols that are not associated with a declaration in the current scope.
          int idx = 0;
          SgSymbolTable::hash_iterator i = internalTable->begin();
          while (i != internalTable->end())
             {
            // DQ: removed SgName casting operator to char*
            // cout << "[" << idx << "] " << (*i).first.str();
               ROSE_ASSERT ( (*i).first.str() != NULL );
               ROSE_ASSERT ( isSgSymbol( (*i).second ) != NULL );

            // printf ("Symbol number: %d (pair.first (SgName) = %s) pair.second (SgSymbol) sage_class_name() = %s \n",
            //      idx,(*i).first.str(),(*i).second->sage_class_name());

               SgSymbol* symbol = isSgSymbol((*i).second);
               ROSE_ASSERT ( symbol != NULL );

            // We have to look at each type of symbol separately!  This is because there is no virtual function,
            // the reason for this is that each get_declaration() function returns a different type!
            // ROSE_ASSERT ( symbol->get_declaration() != NULL );
               switch(symbol->variantT())
                  {
                    case V_SgClassSymbol:
                       {
                         SgClassSymbol* classSymbol = isSgClassSymbol(symbol);
                         ROSE_ASSERT(classSymbol != NULL);
                         ROSE_ASSERT(classSymbol->get_declaration() != NULL);

                         SgDeclarationStatement* declarationToFindInScope = NULL;

                      // Search for the declaration in the associated scope.
                         declarationToFindInScope = classSymbol->get_declaration();
                         ROSE_ASSERT(declarationToFindInScope != NULL);

                         SgClassDeclaration* classDeclaration = isSgClassDeclaration(declarationToFindInScope);
                         ROSE_ASSERT(classDeclaration != NULL);

                         SgName name = classDeclaration->get_name();

                      // SgType* declarationType = declarationToFindInScope->get_type();
                         SgType* declarationType = classDeclaration->get_type();
                         ROSE_ASSERT(declarationType != NULL);

                         if (declarationToFindInScope->get_definingDeclaration() != NULL)
                            {
                              declarationToFindInScope = declarationToFindInScope->get_definingDeclaration();
                              SgClassDeclaration* definingClassDeclaration = isSgClassDeclaration(declarationToFindInScope);
                              ROSE_ASSERT(definingClassDeclaration != NULL);

                           // SgType* definingDeclarationType = declarationToFindInScope->get_type();
                              SgType* definingDeclarationType = definingClassDeclaration->get_type();
                              ROSE_ASSERT(definingDeclarationType != NULL);

                           // DQ (6/22/2011): This assertion fails for CompileTests/copyAST_tests/copytest2007_24.C
                           // A simple rule that all declarations should follow (now that we have proper global type tables).
                           // ROSE_ASSERT(definingDeclarationType == declarationType);
                              if (definingDeclarationType != declarationType)
                                 {
                                   printf ("In fixupSymbolTables.C: Note that definingDeclarationType != declarationType \n");
                                 }
                            }

                         SgNamedType* namedType = isSgNamedType(declarationType);
                         ROSE_ASSERT(namedType != NULL);

                         SgDeclarationStatement* declarationAssociatedToType = namedType->get_declaration();
                         ROSE_ASSERT(declarationAssociatedToType != NULL);
#if 0
                         printf ("Found a symbol without a matching declaration in the current scope (declList): declarationToFindInScope = %p = %s \n",declarationToFindInScope,declarationToFindInScope->class_name().c_str());
                         printf ("Symbol number: %d (pair.first (SgName) = %s) pair.second (SgSymbol) class_name() = %s \n",idx,(*i).first.str(),(*i).second->class_name().c_str());
#endif
                         SgScopeStatement* scopeOfDeclarationToFindInScope      = declarationToFindInScope->get_scope();
                         SgScopeStatement* scopeOfDeclarationAssociatedWithType = declarationAssociatedToType->get_scope();
#if 0
                         printf ("declarationToFindInScope = %p declarationToFindInScope->get_scope() = %p = %s \n",declarationToFindInScope,declarationToFindInScope->get_scope(),declarationToFindInScope->get_scope()->class_name().c_str());
                         printf ("declarationAssociatedToType = %p declarationAssociatedToType->get_scope() = %p = %s \n",declarationAssociatedToType,declarationAssociatedToType->get_scope(),declarationAssociatedToType->get_scope()->class_name().c_str());
#endif
                         if (scopeOfDeclarationToFindInScope != scopeOfDeclarationAssociatedWithType)
                            {
                           // DQ (6/12/2011): Houston, we have a problem!  The trick is to fix it...
                           // A symbol has been placed into a scope when we could not be certain which scope it should be placed.
                           // We have a default of placing such symbols into the global scope, but it might be better to just have 
                           // a special scope where such symbols could be placed so that we could have them separate from the global 
                           // scope and then fix them up more clearly.

                           // Note that test2011_80.C still fails but the AST is at least correct (I think).
                              SgGlobal* scopeOfDeclarationToFindInScope_GlobalScope      = isSgGlobal(scopeOfDeclarationToFindInScope);
                           // SgGlobal* scopeOfDeclarationAssociatedWithType_GlobalScope = isSgGlobal(scopeOfDeclarationAssociatedWithType);

                              if (scopeOfDeclarationToFindInScope_GlobalScope != NULL)
                                 {
                                // In general which ever scope is the global scope is where the error is...???
                                // This is because when we don't know where to put a symbol (e.g. from a declaration of a pointer) we put it into global scope.
                                // There is even an agrument that this is correct as a default for C/C++, but only if it must exist (see test2011_80.C).
                                // Remove the symbol from the symbol table of the global scope.

                                   printf ("Remove the associated symbol in the current symbol table \n");

                                // DQ (6/22/2011): This assertion fails for CompileTests/copyAST_tests/copytest2007_24.C
                                // ROSE_ASSERT (declarationToFindInScope->get_scope() == declarationAssociatedToType->get_scope());
                                   if (declarationToFindInScope->get_scope() != declarationAssociatedToType->get_scope())
                                        printf ("In fixupSymbolTables.C: Note that declarationToFindInScope->get_scope() != declarationAssociatedToType->get_scope() \n");
                                 }
                                else
                                 {
                                   listOfSymbolsToRemove.push_back(classSymbol);
                                 }
                            }
                      // ROSE_ASSERT (declarationToFindInScope->get_scope() == declarationAssociatedToType->get_scope());

                         break;
                       }

                    default:
                       {
                      // It night be there are are no other types of symbols to consider...

                      // printf ("Ignoring non SgClassSymbols (fixupSymbolTables.C) symbol = %s \n",symbol->class_name().c_str());
                      // ROSE_ASSERT(false);
                       }
                  }

            // Increment iterator!
               i++;

            // Increment counter!
               idx++;
             }

       // DQ (6/18/2011): Now that we are through with the symbol table we can support removal of any 
       // identified problematic symbol without worrying about STL iterator invalidation.
          for (size_t j = 0; j < listOfSymbolsToRemove.size(); j++)
             {
            // Remove these symbols.
               SgSymbol* removeSymbol = listOfSymbolsToRemove[j];
               ROSE_ASSERT(removeSymbol != NULL);
               SgSymbolTable* associatedSymbolTable = isSgSymbolTable(removeSymbol->get_parent());
               ROSE_ASSERT(associatedSymbolTable != NULL);

               ROSE_ASSERT(associatedSymbolTable == symbolTable);

               associatedSymbolTable->remove(removeSymbol);

               printf ("Redundant symbol removed...from symbol table \n");
            // ROSE_ASSERT(false);
             }
#if 0
       // debugging
          symbolTable->print("In FixupAstSymbolTables::visit(): printing out the symbol tables");
#endif
        }
   }
IntermediateRepresentationNodeGraph::IntermediateRepresentationNodeGraph(ofstream & inputFile, SgProject* project, const std::vector<VariantT> & inputNodeKindList)
   : file(inputFile), 
     nodeKindList(inputNodeKindList)
   {
     for (size_t i = 0; i < nodeKindList.size(); i++)
        {
          printf ("Adding nodeKindList[%" PRIuPTR "] = %d = %s to nodeKindSet \n",i,Cxx_GrammarTerminalNames[nodeKindList[i]].variant,Cxx_GrammarTerminalNames[nodeKindList[i]].name.c_str());
          include_nodeKindSet.insert(nodeKindList[i]);
        }

  // Build a list of functions within the AST
  // Rose_STL_Container<SgNode*> functionDeclarationList = NodeQuery::querySubTree (project,V_SgFunctionDeclaration);
  // Rose_STL_Container<SgNode*> functionDeclarationList = NodeQuery::querySubTree (project,V_SgDeclarationStatement);
     Rose_STL_Container<SgNode*> functionDeclarationList = NodeQuery::querySubTree (project,V_SgStatement);

  // include_nodeSet.insert(functionDeclarationList.begin(),functionDeclarationList.end());

     int maxNumberOfNodes = 5000;
     int numberOfNodes = (int)functionDeclarationList.size();
     printf ("Number of IR nodes in IntermediateRepresentationNodeGraph = %d \n",numberOfNodes);

#if 1
     int counter = 0;
     for (Rose_STL_Container<SgNode*>::iterator i = functionDeclarationList.begin(); i != functionDeclarationList.end(); i++)
        {
          SgStatement*            statement           = isSgStatement(*i);
          SgDeclarationStatement* declaration         = isSgDeclarationStatement(*i);
          SgFunctionDeclaration*  functionDeclaration = isSgFunctionDeclaration(*i);

          SgTemplateInstantiationFunctionDecl*  templateInstantiationFunctionDeclaration = isSgTemplateInstantiationFunctionDecl(*i);

       // if (declaration != NULL && declaration->get_file_info()->isCompilerGenerated() == false)
          if (statement != NULL && statement->get_file_info()->isCompilerGenerated() == false)
             {
               include_nodeSet.insert(statement);
             }

          if (templateInstantiationFunctionDeclaration != NULL)
             {
               include_nodeSet.insert(statement);
             }
           
#if 0
       // Build a pointer to the current type so that we can call the get_name() member function.
          SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(*i);
          if (functionDeclaration != NULL)
             {
            // DQ (3/5/2006): Only output the non-compiler generated IR nodes
               if ( (*i)->get_file_info()->isCompilerGenerated() == false)
                  {
                 // output the function number and the name of the function
                    printf ("Function #%2d name is %s at line %d \n",counter++,functionDeclaration->get_name().str(),functionDeclaration->get_file_info()->get_line());
                  }
                 else
                  {
                 // Output something about the compiler-generated builtin functions
                    printf ("Compiler-generated (builtin) function #%2d name is %s \n",counter++,functionDeclaration->get_name().str());
                  }
             }
            else
             {
               SgDeclarationStatement* declaration = isSgDeclarationStatement(*i);
               ROSE_ASSERT(declaration != NULL);
               printf ("--- declaration #%2d is: %p = %s \n",counter++,declaration,declaration->class_name().c_str());
             }
#endif
        }
#endif

     if (numberOfNodes <= maxNumberOfNodes)
        {
       // Ouput nodes.
          for (std::set<SgNode*>::iterator i = include_nodeSet.begin(); i != include_nodeSet.end(); i++)
             {
               SgNode* node = *i;
               file << "\"" << StringUtility::numberToString(node) << "\"[" << "label=\"" << node->class_name() << "\\n" << StringUtility::numberToString(node) << "\"];" << endl;
             }

       // Output edges
          for (std::set<SgNode*>::iterator i = include_nodeSet.begin(); i != include_nodeSet.end(); i++)
             {
               SgNode* node = *i;

               std::vector<std::pair<SgNode*,std::string> > listOfIRnodes = node->returnDataMemberPointers();
               std::vector<std::pair<SgNode*,std::string> >::iterator j = listOfIRnodes.begin();
               while (j != listOfIRnodes.end())
                  {
                    if (include_nodeSet.find(j->first) != include_nodeSet.end())
                       {
                         file << "\"" << StringUtility::numberToString(node) << "\" -> \"" << StringUtility::numberToString(j->first) << "\"[label=\"" << j->second << "\"];" << endl;
                       }

                    j++;
                  }
             }
        }
       else
        {
          printf ("WARNING: IntermediateRepresentationNodeGraph is too large to generate: numberOfNodes = %d (max size = %d) \n",numberOfNodes,maxNumberOfNodes);
        }
   }