sagexx_ug (1158317), страница 2

Файл №1158317 sagexx_ug (Раздаточные материалы) 2 страницаsagexx_ug (1158317) страница 22019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 2)

One way is to access each subroutine and function by means of the `numberOfFunctions()'and `functions(i)' methods.For example, to print the names of all the subroutinesin the project:Chapter 2: Projects and Files10SgProject *project;.../* from Sage++ demo 'instrument', in function InitFunctionTable()) */for (int i = 0; i < project->numberOfFiles(); i++) {SgFile *f;f = &(project->file(i));int num_routines;num_routines = f->numberOfFunctions();for (int j = 0; j < num_routines; j++){SgStatement *sub;SgSymbol *subsym;sub = f->functions(j);subsym = sub->symbol();}}printf("Function %d's name is %s\n", i*Files+j, subsym->identifier());The other way to traverse a le is to access it in lexical order starting with `firstStatement()':voidtraverseFile(SgFile *f){SgStatement *s;}for (s = f->firstStatement(); s; s = s->lexNext()) {/* Do something to the statement */}Chapter 3: Statements113 StatementsFiles are broken down into statements.

`SgStatement' is the base class for the representationof statements. SgStatement has many derived classes, corresponding to the many dierent kindsof statements in the languages Sage++ can deal with.Each statement has a unique integer identier id, and an integer variant tag which can beused to identify its type. These are available through SgStatement's `id()' and `variant()' member functions. SgStatement's `thebif' member provides access to the low level representation ofstatements, bif nodes.Each statement has a context: it may have a lexical predecessor and a lexical successor, and itmay be nested within a control block of another statement, or in a block structured denition likea C struct. This enclosing statement is called the control parent; it denes the basic structure ofthe parse tree.3.1 SgStatementclass SgStatement {// Discuss about control parent, BIF structure etcpublic:PTR_BFND thebif;SgStatement(int variant);SgStatement(PTR_BFND bif);// info about statementintlineNumber();//intid();//intvariant();//SgExpression * expr(int i); // i = 0,1,2source text line numberunique id;the type of the statementreturns the i-th expression.inthasSymbol(); // returns TRUE if tmt has symbol, FALSE otherwise// returns the symbol field.

Used by loop headers to point to the// loop variable symbol; Used by function and subroutine headers to// point to the function or subroutine name.SgSymbol *symbol();// returns the symbol field.char *fileName();intSgLabel *hasLabel();label();// returns 1 if there is a label on the stmt.// the labelChapter 3: Statements12// modifying the info.voidsetlineNumber(int n); // change the line number infovoidsetId(int n);// cannot change the id infovoidsetVariant(int n);// change the type of the statementvoidsetExpression(int i, SgExpression &e); // change the i-th expressionvoidsetLabel(SgLabel &l); // change the labelvoidsetSymbol(SgSymbol &s); // change the symbol// Control structureSgStatement * lexNext();// the next statement in lexical order.SgStatement * lexPrev();// the previous stmt in lexical order.SgStatement * controlParent(); // the enclosing control statementvoidvoidsetLexNext(SgStatement &s); // change the lexical orderingsetControlParent(SgStatement &s); // change the control parent.// Access statement using the tree structure// Describe BLOB lists here?intintSgStatement *SgStatement *SgStatement *numberOfChildrenList1();numberOfChildrenList2();childList1(int i);childList2(int i);nextInChildList();Chapter 3: Statements13SgStatement * lastDeclaration();SgStatement * lastExecutable();SgStatement * lastNodeOfStmt();SgStatement * nodeBefore();voidinsertStmtBefore(SgStatement &s);voidinsertStmtBefore(SgStatement &s, SgStatement &cp);voidinsertStmtAfter(SgStatement &s);voidinsertStmtAfter(SgStatement &s, SgStatement &cp);SgStatement * extractStmt();SgStatement * extractStmtBody();voidreplaceWithStmt(SgStatement &s);voiddeleteStmt();SgStatement & copy();intisIncludedInStmt(SgStatement &s);voidreplaceSymbByExp(SgSymbol &symb, SgExpression &exp);voidreplaceSymbBySymb(SgSymbol &symb, SgSymbol &newsymb);voidreplaceSymbBySymbSameName(SgSymbol &symb, SgSymbol &newsymb);voidreplaceTypeInStmt(SgType &old, SgType &newtype);char*unparse();voidunparsestdout();voidsunparse(char *buffer); //unparsing functions.char *comments();//preceding comment lines.voidaddComment(char *com);intnumberOfComments(); //number of preceeding comments.inthasAnnotations();//1 if there are annotations; 0 otherwise// These function must be removed.

Doesn't make sense here.intIsSymbolInScope(SgSymbol &symb); // TRUE if symbol is in scopeintIsSymbolReferenced(SgSymbol &symb);SgStatement * getScopeForDeclare(); // return where a variable can be declared;};SgStatement is used in the following places in the example programs: see [Restructure - addStuToProgram], page 135 see hundenedi [Instrument], page hundenedi see [Instrument - InitFunctionTable], page 141 see [Instrument - InsertFCallNode], page 142 see [Instrument - FixLoops], page 143 see [Instrument - FInstrumentSub], page 143 see [Instrument - FInstrument], page 144 see [Instrument - UnparseSub], page 145 see [Instrument - VistaInstrument], page 145 see [Instrument - FAnalyze], page 145 see [Instrument - inMethodOfTheElement], page 149Chapter 3: Statements14see [Instrument - whichFunctionAmI], page 150see [Instrument - isReferenceToCollection], page 150see [Instrument - ListCollections], page 153see [Instrument - ListCollectionInstances], page 153see [Instrument - ListCollectionInvocations], page 153see [Instrument - InsertCCallNode], page 155see [Instrument - CTimingInstrumentSub], page 156see hundenedi [Expand Syntax], page hundenedisee [Expand Syntax - ExpandSyntax], page 162see [Expand Syntax - SearchInExpForCollectionArrayRef], page 162see [Expand Syntax - ReplaceWithGetElemPart], page 163see [Expand Syntax - Init], page 166see [Dump Info - classifyStatements], page 170see [Dump Info - doRoutineHeader], page 176see [Dump Info - doIfStmts], page 176see [Dump Info - doLoopStmts], page 177see [Dump Info - doIOStmts], page 178see [Dump Info - doGoToStmt], page 178see [Dump Info - doVarDecl], page 178Member Functions:SgStatement(int variant)SgStatement(PTR BFND bif)int lineNumber()int id()int variant()SgExpression * expr(int i)There can be up to three expressions associated with any statement.

For example, the C `for'loop is of the form `for(expr_1; expr_2; expr_3)'.int hasSymbol()SgSymbol * symbol()Used for the name of a subroutine in a subroutine header statement and the induction variableof a DO loop.Chapter 3: Statements15char * leName()int hasLabel()SgLabel * label()void setlineNumber(int n)void setId(int n)void setVariant(int n)void setExpression(int i, SgExpression &e)void setLabel(SgLabel &l)void setSymbol(SgSymbol &s)SgStatement * lexNext()SgStatement * lexPrev()SgStatement * controlParent()void setLexNext(SgStatement &s)void setControlParent(SgStatement &s)int numberOfChildrenList1()int numberOfChildrenList2()SgStatement * childList1(int i)SgStatement * childList2(int i)SgStatement * nextInChildList()SgStatement * lastDeclaration()If the statement is not a leaf of the parse tree, this function returns a pointer to the lastdeclaration in the subtree the statement represents.SgStatement * lastExecutable()SgStatement * lastNodeOfStmt()If the statement is not a leaf of the parse tree, this function returns a pointer to the last statementin the subtree it denes.SgStatement * nodeBefore()void insertStmtBefore(SgStatement &s)Chapter 3: Statementsvoid insertStmtBefore(SgStatement &s, SgStatement &cp)void insertStmtAfter(SgStatement &s)void insertStmtAfter(SgStatement &s, SgStatement &cp)SgStatement * extractStmt()SgStatement * extractStmtBody()void replaceWithStmt(SgStatement &s)void deleteStmt()SgStatement & copy()int isIncludedInStmt(SgStatement &s)void replaceSymbByExp(SgSymbol &symb, SgExpression &exp)void replaceSymbBySymb(SgSymbol &symb, SgSymbol &newsymb)void replaceSymbBySymbSameName(SgSymbol &symb, SgSymbol &newsymb)void replaceTypeInStmt(SgType &old, SgType &newtype)char* unparse()void unparsestdout()void sunparse(char *buer)char * comments()Comments preceding or appended on the right of the statement.void addComment(char *com)int numberOfComments()int hasAnnotations()int IsSymbolInScope(SgSymbol &symb)int IsSymbolReferenced(SgSymbol &symb)SgStatement * getScopeForDeclare()16Chapter 3: Statements17SgStatement UsageOnce a statement has been extracted from the parse tree one may make a copy of it with`copy()' and insert the copy or the original in another position: S1.insertStmtAfter(S2) will insertS2 in the lexical position following S1.One may also search a statement and its subexpressions for a symbol and replace all occurrenceswith another symbol or expression.

Similarly, one may replace any reference to a given type withanother type.To illustrate the use of the statement classes consider the following simple example. Supposewe wish to traverse a le and apply the unrolling transformation to all the inner most loops whosebody consists of only assignment statements. The function that accomplishes this is shown below.void UnrollLoops(SgFile *file, int unroll_factor){SgStatement *s = file->firstStatement();SgForStmt *loop;while(s){if(loop = isSgForStmt(s)){if(loop->isAssignLoop()) loop->unrollLoop(unroll_factor);}s = s->lexNext();}}This function illustrates an important aspect of the programming style used in sage++.

Характеристики

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6529
Авторов
на СтудИзбе
301
Средний доход
с одного платного файла
Обучение Подробнее