sagexx_attr (Раздаточные материалы)

PDF-файл sagexx_attr (Раздаточные материалы) Модели параллельных вычислений и DVM технология разработки параллельных программ (53471): Другое - 7 семестрsagexx_attr (Раздаточные материалы) - PDF (53471) - СтудИзба2019-09-18СтудИзба

Описание файла

Файл "sagexx_attr" внутри архива находится в следующих папках: Раздаточные материалы, SAGE. PDF-файл из архива "Раздаточные материалы", который расположен в категории "". Всё это находится в предмете "модели параллельных вычислений и dvm технология разработки параллельных программ" из 7 семестр, которые можно найти в файловом архиве МГУ им. Ломоносова. Не смотря на прямую связь этого архива с МГУ им. Ломоносова, его также можно найти и в других разделах. .

Просмотр PDF-файла онлайн

Текст из PDF

1 Attributes in SageIt is possible to add information to the Sage nodes using attributes. An attribute has twovalues:1. a type: the type is a positive integer, negative integers are reserved for the system.2. data: the data eld is a pointer to void that can be used to store any information.Attributes can be attached to SgStatement, SgExpression, SgType or SgSymbol objects.The attributes for all nodes in a le can be saved in a separate le and read back from ale to allow multiple passes. The following methods of class SgFile are provided: void saveAttributes(char *le): saves the attributes data elds in le.

The datais assumed to be contiguous in memory and of size given by getAttributeSize(). void saveAttributes(char *le, void (*savefunction)(void *dat, FILE *f)):saves the attributes using the provided data copy function. This is useful for instancewhen the attributes data have pointers to more data. void readAttributes(char *le): Reads the attribute le generated by void saveAttributes(char *le). void readAttributes(char *le, void * (*readfunction)(FILE *f)): Readsthe attribute le generated by void saveAttributes(char *le, void (*savefunction)(void *dat,FILE *f))int numberOfAttributes(): gives the total number of attributes in a le.SgAttribute *attribute(int i): accesses the ith attribute of the le ( = 0 1 ).i;; :::No special initialization routines are necessary to use the attribute system.

However, onlyone .dep le can be processed at a time. The selection of the le is done by the SgProjectmethod project- le(i) which sets the current le. As a consequence, when adding anattribute to a node (for instance an SgStatement object) the le that the node belongs tomust be the current le. This limitation is consistent with the multi-le behavior of Sage.>Warning: if the .dep le is modied before being saved, the saving of theattributes must be done last so the node numbers are consistent. Saving thedatabase in a le modies the identiers of Sage nodes.1.1 Attribute Methods in the SgStatement, SgExpression, SgSymbol, SgType Classesint numberOfAttributes(): gives the number of attributes attached to the SgStatement (or SgExpression, SgSymbol, SgType) object.1int numberOfAttributes(int type): gives the number of attributes of type typeattached to the object.

The parameter type acts as a lter.void *attributeValue(int i): returns the data eld of the ith attribute ( = 0 1 )i;; :::attached to the node. Returns NULL if the node does not exist.int attributeType(int i): returns the type of the ith attribute ( = 0 1 ) attachedto the node. Returns 0 if the node does not exist.void *attributeValue(int i,int type): same as void *attributeValue(int i) butonly consider the attribute of type type.void *deleteAttribute(int i): removes the ith attribute ( = 0 1 ) in the attributelist of the object.

The data eld is returned so it can be deleted if appropriate.void addAttribute(int type, void *a, int size): adds an attribute to a node.There are no limits (except the available memory).void addAttribute(int type): adds an attribute without data eld. Data eld isset to NULL.void addAttribute(void *a, int size): adds an attribute with only a data eld.void addAttribute(SgAttribute *at): adds an attribute that has already beenconstructed.SgAttribute *getAttribute(int i): returns the ith ( = 0 1 ) attribute of anobject.SgAttribute *getAttribute(int i,int type): returns the ith attribute of type typeattached to the object.iii;;;; :::; :::; :::1.2 The Attributes Class: class SgAttributeSgAttribute(int t, void *pt, int size, SgStatement &st, int lenum): constructor for SgStatement attribute.

The parameter t is the type of the attribute, pta pointer to the data and size the size of the data (in bytes). This last parameter isuseful if no function is given for reading and saving the attributes. The parameter stis the statement the attribute is attached to. When an attribute is created this way,it does not appear in the attributes list of the SgStatement node, but it can be addedusing the addAttribute(SgAttribute *att) method.SgAttribute(int t, void *pt, int size, SgSymbol &st, int lenum): constructorfor SgSymbol attribute.SgAttribute(int t, void *pt, int size, SgExpression &st, int lenum): constructor for SgExpression attribute.2SgAttribute(int t, void *pt, int size, SgType &st, int lenum): constructorfor SgType attribute.int getAttributeType(): get the type of an attribute.void setAttributeType(int t): set the type of an attribute.void *getAttributeData(): get the data eld of an attribute.void *setAttributeData(void *d): set the data eld of an attribute.int getAttributeSize(): get the size of the data eld of an attribute.void setAttributeSize(int s): set the size of the data eld of an attribute.typenode getTypeNode(): get the type of the node the attribute is attached to.The type is an enumerate: enum typenode fBIFNODE, LLNODE, SYMBNODE, TYPENODE,...g corresponding respectively to SgStatement, SgExpression,SgSymbol and SgType.void *getPtToSage(): return a pointer to sage node the attribute is attached to.According to getTypeNode() this value can be casted to the right type.void setPtToSage(void *sa): set the pointer to the Sage node.void resetPtToSage(): set the pointer to the Sage node to NULL.void setPtToSage(SgStatement &st): set the pointer to the Sage node and alsothe data accessed by getTypeNode().void setPtToSage(SgSymbol &st): idem for Symbol.void setPtToSage(SgExpression &st): idem for SgExpression.void setPtToSage(SgType &st): idem for SgType.SgStatement *getStatement(): return the SgStatement pointer if it exists and ifthe attribute is attached to an SgStatement node.

Otherwise this function returnsNULL.SgExpression *getExpression(): idem for SgExpression.SgSymbol *getSgSymbol(): idem for Symbol.SgType *getType(): idem for SgType.int getleNumber(): get the le number.3SgAttribute *copy(): get a copy of an attribute. This function does not copy thedata eld.SgAttribute *getNext(): The attributes attached to the same node are chainedvoid setNext(SgAttribute *s): set the list chaining of an attribute.through the next value.Note:From the user's point of view, the preferred way to handle attributes is by using the attributemethods of SgStatement, SgExpression, SgSymbol, and SgType classes. The SgAttributeclass is provided for those, who need non-standard functionality. In particular, the SgAttribute constructors should not be used directly.

Instead, addAttribute and getAttributemethods should be used. For example, one might be tempted to write a code fragment likethat:SgExpression * CurrentExpression;MyExprPtr = new MyExpr ( ... );...SgAttribute *MyAttribute = new SgAttribute ( MY_TYPE,(void *) MyExprPtr,sizeof(MyExpr) ,*CurrentExpression , 0 );MyExprPtr->SetAttribute ( MyAttribute );CurrentExpression->addAttribute ( MyAttribute );Instead, this code should be written as:SgExpression * CurrentExpression;MyExprPtr = new MyExpr ( ...

);...CurrentExpression->addAttribute ( MY_TYPE, (void *) MyExprPtr,sizeof(MyExpr) );MyAttribute = CurrentExpression->getAttribute( 0, MY_TYPE )MyExprPtr->SetAttribute ( MyAttribute );1.3 An ExampleThe following piece of code adds an attribute to all the statements of all the les in aproject......#define MY_ATTRIBUTE_TYPE 24.....nbfile = project->numberOfFiles();for (i=0; i< nbfile; i++){file = &(project->file(i));first =file->firstStatement();temp = first;while (temp){str = new char[256];sprintf(str,"this_is_an_attribute_added_statement_line_%d",temp->lineNumber());temp->addAttribute(MY_ATTRIBUTE_TYPE,(void *) str, strlen(str));temp = temp->lexNext();}}How to retrieve the attributes from the statement list.for (i=0; i< nbfile; i++){file = &(project->file(i));first =file->firstStatement();temp = first;while (temp){for (j=0; j< temp->numberOfAttributes(); j++)printf("Found attribute type %d ---> %s\n",temp->attributeType(j),(char *) temp->attributeValue(j));temp = temp->lexNext();}}How to retrieve the attributes directly from the le:SgFile *file;nba = file->numberOfAttributes();for (i=0 ; i< nba; i++){att = file->attribute(i);}How to save the attribute:5for (i=0; i< nbfile; i++){sprintf(nam,"attribute%d.dump",i);file = &(project->file(i));file->saveAttributes(nam);}the corresponding read:for (i=0; i< nbfile; i++){sprintf(nam,"attribute%d.dump",i);file = &(project->file(i));file->readAttributes(nam);}saving using a user function:void saveatt (void *dat,FILE *f){if (!dat || !f)return;fprintf(f,"%s\n",dat);}........for (i=0; i< nbfile; i++){sprintf(nam,"attribute%d.dump",i);file = &(project->file(i));file->saveAttributes(nam,saveatt);}The corresponding read:void *readatt (FILE *f){char *data;if (!f)return NULL;data = new char[256];fscanf(f,"%s",data);return (void *) data;}........6for (i=0; i< nbfile; i++){sprintf(nam,"attribute%d.dump",i);file = &(project->file(i));file->readAttributes(nam,readatt);}1.4 Predened Attributes #define DEPENDENCE_ATTRIBUTE-1001 #define INDUCTION_ATTRIBUTE-1002 #define ACCESS_ATTRIBUTE-1003 #define DEPGRAPH_ATTRIBUTE-1004 #define USEDLIST_ATTRIBUTE-1005 #define DEFINEDLIST_ATTRIBUTE -1006 #define NOGARBAGE_ATTRIBUTE-1007 #define GARBAGE_ATTRIBUTE-1008 #define ANNOTATION_EXPR_ATTRIBUTE-1009See the information on data dependence analysis and garbage collection for details.1.5 Limitations and BUGSWhen a copy of a node is done the attributes are not copied....2 Garbage Collectionint SgFile::expressionGarbageCollection(int deleteExpressionNode, int verbose): remove all the not referenced SgExpression nodes from a le.

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