oonski94 (1158312), страница 3

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

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

Similarfunctions exist for the denitions of the variable. SgConstantSymb represents names of program constants. Instances can be constructed by givingan identier, a scope statement and an expression that denes the value. SgFunctionSymb represents function and subroutine names. Methods allow access to the symbolsin the formal parameter list, the result symbol, and the recursive ag, for Fortran. SgMemberFuncSymb represents symbols for member functions of classes and structs. Theconstructor allows specication of the identier, type, enclosing class and protection status of thefunction. Methods return the protection status of the function and the symbol table entry of thedening class.

SgFieldSymb This class is used for elds in a C enum statement, or the elds in a struct or class.It has methods similar to those in SgMemberFuncSymb.SgClassSymb represents names of classes, unions, structs, and pC++ collections (A data-parallellanguage extension). Its methods provide access to the elds and functions of the classes it represents.SgTypeSymb is used for symbols from a C typedef.SgLabelSymb is for C labels.SgLabelVarSymb is for Fortran label variables.SgExternalSymb is for Fortran external functions.SgConstructSymb is for Fortran construct names.SgInterfaceSymb is for Fortran 90 module interfaces.Traversing the symbol table is a very common Sage++ task.

For example, consider the problem oflooking for the symbol table entry for a given member function in a given class. There are several waysto do this. The code below searches the table for the name of the class. Then it searches the eld list forthe name of the member function, and nally returns the pointer to the symbol object (if it is found).SgSymbol *findMemberFunction(char *className, char *functionName){SgSymbol *s, *fld;SgClassSymb *cl;SgMemberFuncSymb *f;int i;for (s=file.firstSymbol(); s ; s = s->next())if (!strcmp(s->identifier(), className))break;if (s == NULL)return NULL;if (cl = isSgClassSymb(s)){for(i = 1, fld = cl->field(i); fld; fld = cl->field(i++)){if ((f = isSgMemberFuncSymb(fld)) &&!strcmp(f->identifier(), functionName))return f;}}return NULL;}3.5.2 TypesThe Sage++ type classes hold basic information about the symbols. As with symbols, Sage++ puts thetypes from a source le into a list of objects whose head can be accessed through a method of SgFile.The base class for types is SgType.

Many types are dened in terms of other types. For example, anarray type has a base type that may be a pointer type which has a base type that may be an integer ora class, etc. Methods of SgType can copy types, and test whether two types are equivalent.There are eight basic subclasses of SgType: SgTypeInt, SgTypeFloat, SgTypeChar, ... are the basic types. SgArrayType is used to represent array types. The parser gives each array variable its own arraytype descriptor object. Member functions can add new dimensions, return the shape and base typeof the array, and change the base type.SgClassType represents types of C structs, Fortran records, C++ classes, C unions, C enums,and pC++ collections.SgPointerType represents pointer types.SgReferenceType represents C++ reference types, i.e.

of the form int &x.SgFunctionType represents types of symbols for functions. A method returns the type of thefunction's return value; another method allows modication of that type.SgDerivedType represents the type of C symbols coming from typedef, as well as the type ofvariables that are of class type.SgDescriptType is a descriptor object that serves to modify another type object. For example,in the C statement long volatile int x; long and volatile are modiers and int is the base type.The type of x is represented by an SgDescriptType object that holds the information about themodiers and the base type.To illustrate the use of the type table, consider the simple problem of identifying if a variable is of agiven user dened class. More specically, in analyzing the codeclass myClass;myClass x, y;y = x + 2;if e is the expression representing the variable reference to x, we would like a function isVarRefOfClass(e, \myClass") that will return 1 when the class type matches and 0 otherwise.

To write thisfunction, we rst check to see if e is indeed a variable reference. Then, we check to see if the type of thesymbol is a derived type. From the derived type we can nd the name of the class.int isVarRefOfClass(SgExpression *e, char *className){SgSymbol *s;SgDerivedType *d;SgClassSymb *cl;SgVarRefExp *exp;if((exp = isSgVarRefExp(e)) == NULL) return 0;s = exp->symbol();if((d = isSgDerivedType(s->type())) == NULL) return 0;if(cl = isSgClassSymb(d->typeName()))if(!strcmp(cl->identifier(), className))return 1;return 0;}4 Data Dependence and Data Flow AnalysisSage++ provides a general framework for data dependence and ow analysis, similar to the one describedin [7].

This part of Sage++ has been kept as open as possible to facilitate experimentation. Note thatthe data dependence and ow analysis routines in Sage++ are still under development, and are subjectto occasional modication. The current implementation is limited to Fortran 771.4.1 Data Dependence AnalysisThe Omega test [8] is the data dependence test used in Sage++. The data dependence routines inSage++ provide an interface to the Omega software. Functions are provided to extract data from loopsabout induction variables, array access in linear form, and data dependences. Data dependence information is provided in the form of distance and direction vectors (the same data dependence informationas calculated by Omega). The depGraph class stores data dependence information; a subset of that classappears below:class depGraph {depNode*current; // list of dependencesdepNode*first;public:SgStatement *loop; // the loop statementSet *arrayRef;// list of array access in the loop in linear formSet *induc;// set of induction variablesdepGraph(SgFile *fi, SgStatement *f,SgStatement *l);~depGraph();...};The fact that array references are stored in linear form helps to implement the interface to thedependence tests.

The dependence graph and other loop related information can be calculated for anyfunction by callinginitializeDepAnalysisForFunction(file,function)extracts the dependence graph for the named loop.1The data dependence and ow analysis routines in Sage++ were not part of the initial Sage++ distribution.depg = new depGraph(file,function,loop)4.2 Flow AnalysisSage++ provides a framework for data ow analysis, to help users write their own ow analysis routines.For example, to implement an iterative forward data ow analysis, the user writes a set of functions tobuild the gen and kill sets for each statement, and the function equal (which indicates when two elementsof a set are equal), and passes those functions to the following Sage++ function:void iterativeForwardFlowAnalysis(SgFile *file,SgStatement *func,Set *(*giveGenSet)(SgStatement *func,SgStatement *stmt),Set *(*giveKillSet)(SgStatement *func,SgStatement *stmt),int (*equal)(void *e1, void *e2),...);The class Set is provided to help with implementing data sets.The current version also oers a more general ow analysis framework, with functions such ascontrolFlow(SgStatement *stmt,...), which returns successors and predecessors of a statement inthe control ow graph, and defUseVar(SgStatement *stmt,...), which returns a list of data read andwritten by a statement.

These functions can be used to construct more complex ow analysis tools.4.3 Loop TransformationsSage++ provides a set of basic loop transformation tools. The following are some of the loop transformations available:intintintintloopFusion(SgStatement *loop1,SgStatement *loop2)loopInterchange(SgStatement *b, int *permut, int n)tileLoops(SgStatement *func,SgStatement *b, int *size, int nb)distributeLoopSCC(SgStatement *b, int *sccTable,int leadingdim, int numSCC)...These transformation routines do not check for the validity of the transformations they perform. Theconditions required to apply a transformation may be very dierent from one application of Sage++ toanother.

In many cases it is known that a transformation is legal, but still the legality cannot be explicitlychecked. For example, this is the case when a previous transformation has changed the structure of aloop without updating the data dependence graph. Furthermore, program transformations may also bespecied by directives in the code.5 Finding Out More About Sage++For complete details about using Sage++, consult the Sage++ User's Guide (about 250 pages). It isthe most complete reference on Sage++ available. It includes an introduction and overview of Sage++,a complete description of each class in the library, several example programs, and a complete index.The Sage++ development team maintains an automated mail server, FTP archive, and a WWW(world wide web) server.

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

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

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