Escape analysis

In compiler optimization, escape analysis is a method for determining the dynamic scope of pointers – where in the program a pointer can be accessed. It is related to pointer analysis and shape analysis.

When a variable (or an object) is allocated in a subroutine, a pointer to the variable can escape to other threads of execution, or to calling subroutines. If an implementation uses tail call optimization (usually required for functional languages), objects may also be seen as escaping to called subroutines. If a language supports first-class continuations (as do Scheme and Standard ML of New Jersey), portions of the call stack may also escape.

If a subroutine allocates an object and returns a pointer to it, the object can be accessed from undetermined places in the program – the pointer has "escaped". Pointers can also escape if they are stored in global variables or other data structures that, in turn, escape the current procedure.

Escape analysis determines all the places where a pointer can be stored and whether the lifetime of the pointer can be proven to be restricted only to the current procedure and/or thread.

Optimizations

A compiler can use the results of escape analysis as a basis for optimizations:[1]

  • Converting heap allocations to stack allocations.[2] If an object is allocated in a subroutine, and a pointer to the object never escapes, the object may be a candidate for stack allocation instead of heap allocation. In garbage-collected languages this can reduce how often the collector needs to run.
  • Synchronization elision. If an object is found to be accessible from one thread only, operations on the object can be performed without synchronization.
  • Breaking up objects or scalar replacement.[3] An object may be found to be accessed in ways that do not require the object to exist as a sequential memory structure. This may allow parts (or all) of the object to be stored in CPU registers instead of in memory.

Practical considerations

In object-oriented programming languages, dynamic compilers are particularly good candidates for performing escape analysis. In traditional static compilation, method overriding can make escape analysis impossible, as any called method might be overridden by a version that allows a pointer to escape. Dynamic compilers can perform escape analysis using the available information on overloading, and re-do the analysis when relevant methods are overridden by dynamic code loading.[1]

The popularity of the Java programming language has made escape analysis a target of interest. Java's combination of heap-only object allocation, built-in threading, the Sun HotSpot dynamic compiler, and OpenJ9's just-in-time compiler (JIT) creates a candidate platform for escape analysis related optimizations (see Escape analysis in Java). Escape analysis is implemented in Java Standard Edition 6. Some JVMs support a stronger variant of escape analysis called partial escape analysis that makes scalar replacement of an allocated object possible even if the object escapes in some paths of a function.[4]

Example (Java)

class Main {
    public static void main(String[] args) {
        example();
    }
    public static void example() {
        Foo foo = new Foo(); //alloc
        Bar bar = new Bar(); //alloc
        bar.setFoo(foo);
    }
}

class Foo {}

class Bar {
    private Foo foo;
    public void setFoo(Foo foo) {
        this.foo = foo;
    }
}

In this example, two objects are created (commented with alloc), and one of them is given as an argument to a method of another. The method setFoo() stores a reference to a received Foo object. If the Bar object was on the heap then the reference to Foo would escape. But in this case a compiler can determine, with escape analysis, that the Bar object itself does not escape the invocation of example(). As a result, the reference to Foo cannot escape either, and the compiler can safely allocate both objects on the stack.

Examples (Scheme)

In the following example, the vector p does not escape into g, so it can be allocated on the stack and then removed from the stack before calling g.

(define (f x)
   (let ((p (make-vector 10000)))
      (fill-vector-with-good-stuff p)
      (g (vector-ref p 7023))))

If, however, we had

(define (f x)
   (let ((p (make-vector 10000)))
      (fill-vector-with-good-stuff p)
      (g p)))

then either p would need to be allocated on the heap or (if g is known to the compiler when f is compiled, and behaves well) allocated on the stack in such a fashion that it can remain in place when g is called.

If continuations are used to implement exception-like control structures, escape analysis can often detect this to avoid having to actually allocate a continuation and copy the call stack into it. For example, in

;;Reads scheme objects entered by the user. If all of them are numbers,
;;returns a list containing all of them in order. If the user enters one that
;;is not a number, immediately returns #f.
(define (getnumlist)
  (call/cc (lambda (continuation)
    (define (get-numbers)
       (let ((next-object (read)))
          (cond
             ((eof-object? next-object) '())
             ((number? next-object) (cons next-object (get-numbers)))
             (else (continuation #f)))))
    (get-numbers))))

escape analysis will determine that the continuation captured by call/cc doesn't escape, so no continuation structure needs to be allocated, and invoking the continuation by calling continuation can be implemented by unwinding the stack.

See also

References

  1. ^ a b T. Kotzmann and H. Mössenböck, “Escape analysis in the context of dynamic compilation and deoptimization,” in Proceedings of the 1st ACM/USENIX international conference on Virtual execution environments, New York, NY, USA, 2005, pp. 111–120.
  2. ^ Blanchet, Bruno (November 2003). "Escape Analysis for JavaTM: Theory and Practice". ACM Transactions on Programming Languages and Systems. 25 (6): 713–775. doi:10.1145/945885.945886. ISSN 0164-0925.
  3. ^ Kotzmann, Thomas; Mössenböck, Hanspeter (March 2007). "Run-Time Support for Optimizations Based on Escape Analysis". International Symposium on Code Generation and Optimization (CGO'07). pp. 49–60. CiteSeerX 10.1.1.394.5944. doi:10.1109/CGO.2007.34. ISBN 978-0-7695-2764-2. S2CID 16011497.
  4. ^ Stadler, Lukas; Würthinger, Thomas; Mössenböck, Hanspeter (2014). "Partial Escape Analysis and Scalar Replacement for Java". Proceedings of Annual IEEE/ACM International Symposium on Code Generation and Optimization - CGO '14. pp. 165–174. doi:10.1145/2581122.2544157. ISBN 9781450326704.

Read other articles:

Mstislav RostropovitchMstislav Rostropovitch en 1978.FonctionAmbassadeur de bonne volonté de l'UNESCOBiographieNaissance 27 mars 1927Bakou, RSS d'Azerbaïdjan Union soviétiqueDécès 27 avril 2007 (à 80 ans)Moscou RussieSépulture Cimetière de NovodievitchiNom de naissance Мстислав Леопольдович РостроповичNationalités soviétiquerusseFormation Conservatoire Tchaïkovski de MoscouAcadémie russe de musique GnessineActivités Compositeur, violoncelliste,...

 

Adam Forshaw Forshaw jugando para el Brentford F. C. en 2013.Datos personalesNombre completo Adam John ForshawNacimiento Liverpool, Reino Unido8 de octubre de 1991 (32 años)Nacionalidad(es) Británica InglesaAltura 1,74 m (5′ 9″)Peso 71 kg (156 lb)Carrera deportivaDeporte FútbolClub profesionalDebut deportivo 2009(Everton F. C.)Club Norwich City F. C.Liga EFL ChampionshipPosición CentrocampistaTrayectoria Everton F. C. (2009-2012) → Brentford F. C. (2012) Brentfor...

 

Apex LegendsInformasi produksiPengembangRespawn EntertainmentPenerbitElectronic ArtsPengarahSteven FerreiraProduserDrew McCoyTina SanchezPerancangMackey McCandlishSenimanRobert TaubeKaelan De NieseRyan LastimosaBenjamin BissonJung ParkPenulisMohammad AlaviKomponisStephen Barton Data permainanMesinSourceUnreal Engine 4 (seluler)PlatformMicrosoft WindowsPlayStation 4Xbox OneAndroid (akses awal)GenreBattle royale, Tembak-menembak orang-pertamaModeMultipemain PerilisanTanggal rilisWindows, PS4, X...

The following is a list of parks in Brunei Darussalam. Arts and Heritage Parks Tasek Merimbun Heritage Park (7800 square hectares) Recreational Parks Tasek Lama Recreational Park Tasek Sarubing Recreational Park Tasek Lama Recreational Park

 

American sitcom (1964–1972) This article is about the American television sitcom. For other uses, see Bewitched (disambiguation). BewitchedBewitched title cardGenreFantasySitcomCreated bySol SaksWritten byVarious[nb 1]Directed byWilliam Asher (most episodes)[nb 1]StarringElizabeth MontgomeryDick YorkAgnes MooreheadDick SargentDavid WhiteTheme music composerHoward GreenfieldJack KellerComposersWarren Barker (most episodes)Allyn Ferguson (1 episode)Van Alexander (3 episodes)Ji...

 

Ireland-related events during 1845 ← 1844 1843 1842 1841 1840 1845 in Ireland → 1846 1847 1848 1849 1850 Centuries: 17th 18th 19th 20th 21st Decades: 1820s 1830s 1840s 1850s 1860s See also:1845 in the United KingdomOther events of 1845 List of years in Ireland Events from the year 1845 in Ireland. Events 18 February – Devon Commission reports to the British government on the poor living conditions of the Irish population: in many districts their only food is the potato.[1 ...

الرفع والسحب هما مكونان من إجمالي القوة الديناميكية الهوائية التي تعمل على طائرة أو طائرة. في الديناميكا الهوائية، نسبةالرفع إلى السحب (lift-to-drag ratio) أو نسبة إل/دي أ(L/D ratio) هي الرفع الناتجة عن جسم ديناميكي هوائي مثل مُنساب هوائي (aerofoil) أو طائرة، مقسومًا على السحب الديناميكي ال...

 

War between Rome and Macedonia, 214–205 BC This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: First Macedonian War – news · newspapers · books · scholar · JSTOR (March 2020) (Learn how and when to remove this template message) First Macedonian WarPart of the Macedonian Wars and the Second Punic WarThe Mediter...

 

Artikel ini bukan mengenai Ben Kingsley. Kingsley Ben-AdirBen-Adir tahun 2021Lahir28 Februari 1986 (umur 37)[1]London, InggrisPekerjaanAktorTahun aktif2012–sekarang Kingsley Ben-Adir (lahir 28 Februari 1986) adalah aktor asal Inggris. Dia telah tampil di beberapa drama di teater London. Dia berperan sebagai ahli patologi Marcus Summer dalam drama detektif ITV1, Vera dan sebagai detektif swasta Karim Washington pada musim kedua serial Netflix, The OA.[2][3] ...

Travel book by Dervla Murphy Where the Indus Is Young: A Winter in Baltistan Cover of John Murray first edition (1977)AuthorDervla MurphyPublisherJohn MurrayPublication date1977Pages266 (first edition)ISBN071953335XDewey Decimal915.49/13Preceded byOn a Shoestring to Coorg Followed byA Place Apart  Where the Indus Is Young is a book by Irish author Dervla Murphy.[1] [2] It was first published by John Murray in 1977.[3] The book is usually given the s...

 

CeeLo Green discographyGreen performing in 2014Studio albums6Compilation albums1Music videos25Singles39 The discography of American recording artist CeeLo Green consists of six studio albums, one compilation album, thirty-nine singles and twenty-five music videos. Diversified in the genres of hip hop, alternative, and soul music, he began his career as apart of the Atlanta-based hip hop group Goodie Mob, which itself was apart of the collective Dungeon Family. His solo career was embarked upo...

 

Type of lifestyle involving little or no physical activity This article is about the medical term. For the anthropologic concept, see sedentism. Couch potato redirects here. For other uses, see Couch potato (disambiguation). This article needs more reliable medical references for verification or relies too heavily on primary sources. Please review the contents of the article and add the appropriate references if you can. Unsourced or poorly sourced material may be challenged and removed.Find ...

This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Tiszakarád – news · newspapers · books · scholar · JSTOR (October 2012) (Learn how and when to remove this template message) Place in Borsod-Abaúj-Zemplén, HungaryTiszakarád Coat of armsTiszakarádLocation of TiszakarádCoordinates: 48°07′19″N 21°26′03″E / ...

 

Condado portucalense, hacia 1070. Las provincias de Portugal son una antigua división administrativa, una división histórico-cultural del territorio nacional por demarcaciones y regiones que pervive en la memoria colectiva. En la actualidad, las llamadas regiones naturales o provincias históricas no tienen significado administrativo, aunque continúan siendo reconocidas por todos. La división de 1936 en provincias sirvió como base de la Educación nacional durante décadas y, en algunos...

 

Genus of wasps Cerceris Cerceris rybyensis Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Arthropoda Class: Insecta Order: Hymenoptera Family: Crabronidae Tribe: Cercerini Genus: CercerisLatreille, 1802 Type species Cerceris rybyensis(Linnaeus, 1771) Diversity at least 880 species Cerceris is a genus of wasps in the family Crabronidae. It is the largest genus in the family, with over 1030 described species and subspecies.[1] The genus has a cosmopolitan distribu...

Westcliff UniversityTypePrivate for-profit universityEstablished1993 (1993)PresidentAnthony LeeStudents4,902[1]LocationIrvine, California, U.S.33°41′08″N 117°50′53″W / 33.6855°N 117.8480°W / 33.6855; -117.8480Campus24 acres (9.7 ha)ColorsNavy Blue, Royal Blue & Gold     NicknameWarriorsSporting affiliationsNAIA – Cal PacWebsitewww.westcliff.edu Westcliff University (WU) is a private, for-profit university in ...

 

Map of Moldova This is a list of places in Moldova which have standing links to local communities in other countries known as town twinning (usually in Europe) or sister cities (usually in the rest of the world). B Bălți[1] Arad, Israel Białystok, Poland Chernivtsi, Ukraine Comrat, Moldova İzmir, Turkey Khmelnytskyi, Ukraine Lakeland, United States Larissa, Greece Livny, Russia Miercurea Ciuc, Romania Mohyliv-Podilskyi, Ukraine Narva, Estonia Nizhny Novgorod, Russia Orsha, Belarus...

 

  لمعانٍ أخرى، طالع هنري كول (توضيح). هنري كول (بالإنجليزية: Henry Cole)‏    معلومات شخصية الميلاد 15 يوليو 1808[1][2][3][4]  باث  الوفاة 18 أبريل 1882 (73 سنة) [1][2][3][4]  لندن  مكان الدفن مقبرة برومتون  مواطنة المملكة المتحدة لبريطانيا الع...

This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Doe v. Chao – news · newspapers · books · scholar · JSTOR (August 2019) (Learn how and when to remove this template message) 2004 United States Supreme Court caseDoe v. ChaoSupreme Court of the United StatesArgued December 3, 2003Decided February 24, 2004Full case nameBuck Doe v. Elaine L. Chao, Secretary ...

 

American investigative journalist Julia AngwinAngwin in 2020BornChampaign, ILAlma materUniversity of Chicago (BA)Columbia University (MBA Graduate School of Business)Occupation(s)Investigative journalist, Co-founder and Editor-in-Chief of The MarkupAwardsPulitzer Prize for Explanatory ReportingWebsitewww.juliaangwin.com Julia Angwin is a Pulitzer Prize-winning[1] American investigative journalist,[2] New York Times bestselling author, and entrepreneur. She was a co-founde...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!