oonski94 (1158312)

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

Текст из файла

Sage++: An Object-Oriented Toolkit and Class Libraryfor Building Fortran and C++ Restructuring Tools Francois Bodin, Irisa, University of RennesPeter Beckman, Dennis Gannon, Jacob Gotwals, Srinivas Narayana,Suresh Srinivas, Beata Winnicka, Department of Computer Science, Indiana UniversityAbstractSage++ is an object oriented toolkit for building program transformation and preprocessing tools. Itcontains parsers for Fortran 77 with many Fortran 90 extensions, C, and C++, integrated with a C++class library.

The library provides a means to access and restructure the program tree, symbol andtype tables, and source-level programmer annotations. Sage++ provides an underlying infrastructureon which all types of program preprocessors can be built, including parallelizing compilers, performanceanalysis tools, and source code optimizers.1 IntroductionDesigning and building a source-to-source translation system is a very time consuming task.

However, such systems are often a prerequisite for many compiler and language extension research projects.Sage++ was designed to be a toolkit for such projects. It provides an integrated set of parsers thattransform the source program into an internal representation, which we call a program tree; a library ofobject-oriented methods that manipulate the program tree and give tool builders complete freedom inrestructuring it; and an unparser that generates new source code from the restructured internal form.Such translation systems are used, for example, in studies of language extensions that permit theexplicit representation of parallelism, where they are necessary for the construction of compilers thatgenerate target-specic source code containing calls to run-time systems that support concurrency. Examples include the Fortran-D and Fortran 90D compilers [1], and the pC++ compiler [5].

Source-tosource translation systems are also used to construct compilers that tackle the problem of discoveringparallelism in sequential source code. These compilers apply restructuring transformations to generatea version of the program that uses directives or explicit parallel constructs understood by the \native"compiler on the parallel machine.

Examples of these include the compilers for Parafrase and Parafrase-II[6], and Superb [2]. Sage++ also makes it possible to build library specic optimizations that can beadded as a portable preprocessing stage to the C++ compiler.Often called preprocessors because they do not generate native machine code, all of these systemsuse extensive syntactic and semantic analysis and sophisticated global optimization to transform source This research is supported by ARPA under contract AF 30602-92-C-0135 and Esprit APPARCcode.

In each case, these systems have been based on a layer of compiler technology that has requiredyears for each research group to develop. Sage++ makes this layer available in a generalized form. Bystarting from Sage++ rather than starting from scratch, researchers in these elds can potentially cutyears o their development time.A second motivation for releasing Sage++ is in response to a frequent request by programmers foraccess to tools that allow them to go beyond simple macros, and create extensions to C++ or Fortran.2 Sage++ as a Meta-ToolSage++ is designed to be a tool with which other tools can be constructed.

For example, scienticlibrary designers can use Sage++ to build tools capable of optimizing the source code that links withthe library. As an illustration, consider the problem of optimizing the use of a C++ Matrix librarypackage similar to Lapack++ [4]. The library consists of a C++ classes for Vectors and Matrices, with aspecial mechanism for describing subarrays and subvectors, and where the standard arithmetic operatorshave been overloaded:class GenMat;class Vector{public:Vector(int n){};Vector & operator =(Vector &);Vector & operator +(Vector &);friend Vector &operator *(float x, Vector &v);void vecVecAdd(Vector &left, Vector &right); // this = left*rightvoid matVecMul(GenMat &M, Vector &x);// this = M*xvoid scalarVecMul(float x, Vector &v);// this = x*v};class GenMat{ // general matrixpublic:GenMat(int i, int j);GenMat & operator()( int , int );GenMat & operator()( index &, index &);GenMat & operator =(GenMat &);Vector & operator *(Vector &);};A common problem with such algebraic applications of C++ is managing the high cost of generatingtemporaries and creating copies, in expressions likeGenMat M(100,100);Vector w(100), x(100), y(100), z(100);z = x+ M*(x+3.2*y + w);x = z+w;y = z+x;A naive compiler will allocate temporaries for each of the operations (in this case eight).

Furthermore,the assignment operations may create needless copies of the data (in this case three). The above codefragment can be written to use temporaries much more eciently; member functions that take twoarguments should be used. For example, the expression x = z+w can be written as x.vecVecAdd(z,w).Furthermore, because vector addition does not carry any dependences, we do not have to worry aboutpossible aliases, and expressions like x = z+x can be re-written as x.vecVecAdd(z,x).

However, this isnot true for Matrix Vector multiply. In this case, if x.matVecMul(M,z) is written asfor (i =x[i] =for (jx[i]}0; i < size; i++) {0.0;= 0; j < size; j++)+= M(i,j)*z(j);then we cannot allow x and z to be aliased and a temporary must be generated.Taking these observations about aliases into account, it is easy to write a Sage++ preprocessor thatwill transform the rst set of expressions above into the code below.GenMat M(100,100);Vector w(100),x(100),y(100),z(100);Vector _T0(100);z.scalarVecMul(3.2,y);z.vecVecAdd(x,z);z.vecVecAdd(z,w);_T0.matVecMul(M,z);z.vecVecAdd(x,_T0);x.vecVecAdd(z,w);y.vecVecAdd(z,x);Such a preprocessor would scan the original code looking for expressions involving the Vector orGenMat classes.

A strategy that the preprocessor might use is to employ the left hand side of eachassignment as a free temporary as long as it is not used on the right hand side of the assignment. Noticethat one temporary _T0 was generated because of the alias problem with matVecMul. A more aggressiveoptimization could have discovered that y could be used instead, since it is redened later.A very dierent application of Sage++ is in constructing a tool for automatic instrumentation ofuser code.

A team at the University of Oregon has used Sage++ to automatically add instrumentationfor tracking class member function calls [9]. They use Sage++ to add an instrumentation object to thedenition of each member function to be tracked. When the program is run, invocation of any of theinstrumented methods calls the constructor of the instrumentation object, which can log the method'sinvocation. Upon exit from the method, the instrumentation object's destructor can log that event aswell.Yet another application of Sage++ is in the construction of preprocessors for Fortran programs. Thebest example is the Fortran-S [3] system designed at the University of Rennes.

This system relies on userlevel annotations embedded in comments, which are extracted by Sage++, and invoke transformationssuch as loop vectorization, blocking and interchange, which are all coded using Sage++.Sage++ is also being used in a project at Argonne National Laboratory to perform automatic dierentiation of numerical algorithms written in C.

Automatic dierentiation is the process of augmentingSgFileSgStatementGLOBALFirstFirstFirstStmtExprSymb TypeSgExpressionlexNextnextInExprTable......FirstSgSymbolDEFAULTnext...SgTypeT_INTnext...Figure 1: The Four Threaded Trees Linked to SgFilefunctions in the original code to produce derivative values in addition to the original function outputs [10].Another Fortran example is a system at the University of Colorado that optimizes certain expressionsfor parallel execution on the KSR-1.

The resulting tool is used by an NSF Grand Challenge projectthere.3 Using Sage++This section provides an overview of the Sage++ library. The library contains four families of classes:project and le classes, corresponding to multi-source application projects and the source les theycontain; statement classes, corresponding to the basic source statements in Fortran (with many Fortran90 extensions), C and C++; expression classes, representing the expressions contained within statements;symbol classes, representing the basic user dened identiers; and type classes, representing the typesassociated with each identier and expression (see Figure 1).3.1 ParsingTo transform an application program with Sage++, each source le must rst be parsed, using eitherthe Fortran parser f2dep, or the C/C++ parser pC++2dep.

The result is a set of machine independentbinary les called .dep les. Each .dep le corresponds to one program tree. .dep les are completetranslations of the source les they represent, including comments, so they can be used to regeneratethe original source. The contents of a .dep le can be examined using the dumpdep program.3.2 Project and File ClassesThe Sage++ class SgProject represents the set of application source les to be transformed.

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

Тип файла PDF

PDF-формат наиболее широко используется для просмотра любого типа файлов на любом устройстве. В него можно сохранить документ, таблицы, презентацию, текст, чертежи, вычисления, графики и всё остальное, что можно показать на экране любого устройства. Именно его лучше всего использовать для печати.

Например, если Вам нужно распечатать чертёж из автокада, Вы сохраните чертёж на флешку, но будет ли автокад в пункте печати? А если будет, то нужная версия с нужными библиотеками? Именно для этого и нужен формат PDF - в нём точно будет показано верно вне зависимости от того, в какой программе создали PDF-файл и есть ли нужная программа для его просмотра.

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

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