SlideShare a Scribd company logo
HHVM: Efficient and Scalable PHP/Hack Execution / Guilherme Ottoni (Facebook)
HHVM: Efficient and Scalable
PHP/Hack Execution
Guilherme Ottoni
HHVM Team
Facebook
November 2016
Speaker Intro
3
• Background in compilers,
performance analysis and
optimizations
• 15+ years working in these areas
• Spent last 5.5 years pushing the
limits of PHP performance at
Facebook
Motivation: Why PHP?
• Many claim it’s a poorly designed language
• But it’s pretty successful and widely used,
especially for server-side web development
• Biggest strengths:
– Integration with web servers
– Rapid development cycle
4
FAST
Motivation: Why PHP?
• Top websites [http://www.alexa.com/topsites]:
1. Google
2. Youtube
3. Facebook
4. Baidu
5. Wikipedia
6. Yahoo
5
PHP
Motivation: Why HHVM?
• High load requires high
performance
• Standard PHP
– Not very efficient
– Interpreter-based
– Only industry-strength
implementation of PHP
that existed
6
• HHVM’s goals:
1. Improve performance of PHP execution
2. Compatibility with Standard PHP
0
2
4
6
8
10
12
14
16
18
20
22
24
26
28PerformanceRelativetoPHP5.1running
facebook.com
More Efficient… By How Much?
7
HHVM released to
production
HipHop
Compiler
Motivation: Why HHVM?
• Top websites [http://www.alexa.com/topsites]:
1. Google
2. Youtube
3. Facebook
4. Baidu
5. Wikipedia
6. Yahoo
8
HHVM
• Many other adopters, e.g. Box, Etsy, Slack, Wordpress
• Wikipedia’s CPU usage dropped by 6x when it
switched to HHVM
[http://hhvm.com/blog/7205/wikipedia-on-hhvm]
Overview of HHVM Pipeline
9
PHP AST
Optimize
Parser
HHBC
Bytecode
Emitter
Optimize,
Type Inference
AheadofTime
HHBC HHIR
Optimize
x86Vasm
Optimize
Runtime
Challenges for PHP Performance
1. Lack of static type information
2. Huge amounts of code
a. JIT speed
b. Code locality
3. Reference counting
10
Challenge #1: Dynamic Typing
• HHVM’s basic principle to achieve
performance: operate on type-
specialized code
• Ahead-of-time type inference
– AST-based
– Bytecode-based
11
HHBC
Optimize,
Type Inference
Challenge #1: Dynamic Typing
• Runtime type specialization
1. Tracelet JIT
• Inspect live types & JIT small code blocks as you go
2. Profile-driven Region JIT
• Collect type information in the beginning, then
later compile larger code regions
12
$elem: uncount; stk: dbl
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
$sum: dbl ; $elem: int
$sum: dbl ; $elem: dbl
$sum: int ; $elem: dbl
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
Example
13
81: CGetM <L:0 EL:3>
94: SetL 4
96: PopC
97: Int 0
106: CGetL2 4
108: Gt
109: JmpZ 13 (122)
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
71: CGetL 1
73: CGetL2 3
75: Lt
76: JmpZ 55 (131)
122: IncDecL 3 PreInc
125: PopC
126: Jmp -55
function addPositive($arr, $n) {
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$elem = $arr[$i];
if ($elem > 0) {
$sum = $sum + $elem;
}
}
return $sum;
}
94: SetL 4
96: PopC
97: Int 0
106: CGetL2 4
108: Gt
109: JmpZ 13 (122)
$elem: uncount; stk: int
$i: int ; $n: int
$arr: array ; $i: int
$sum: int ; $elem: int
$i: int
$sum: dbl ; $elem: int
$elem: uncount; stk: dbl
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
$sum: dbl ; $elem: dbl
$sum: int ; $elem: dbl
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
Example
14
81: CGetM <L:0 EL:3>
94: SetL 4
96: PopC
97: Int 0
106: CGetL2 4
108: Gt
109: JmpZ 13 (122)
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
71: CGetL 1
73: CGetL2 3
75: Lt
76: JmpZ 55 (131)
122: IncDecL 3 PreInc
125: PopC
126: Jmp -55
function addPositive($arr, $n) {
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$elem = $arr[$i];
if ($elem > 0) {
$sum = $sum + $elem;
}
}
return $sum;
}
94: SetL 4
96: PopC
97: Int 0
106: CGetL2 4
108: Gt
109: JmpZ 13 (122)
$elem: uncount; stk: int
$i: int ; $n: int
$arr: array ; $i: int
$sum: int ; $elem: int
$i: int
$elem: uncount; stk: dbl
$sum: dbl ; $elem: dbl
Example
15
81: CGetM <L:0 EL:3>
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
71: CGetL 1
73: CGetL2 3
75: Lt
76: JmpZ 55 (131)
122: IncDecL 3 PreInc
125: PopC
126: Jmp -55
function addPositive($arr, $n) {
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$elem = $arr[$i];
if ($elem > 0) {
$sum = $sum + $elem;
}
}
return $sum;
}
94: SetL 4
96: PopC
97: Int 0
106: CGetL2 4
108: Gt
109: JmpZ 13 (122)
$i: int ; $n: int
$arr: array ; $i: int
$i: int
$elem: uncount; stk: dbl
$sum: dbl
Example
16
81: CGetM <L:0 EL:3>
114: CGetL 4
116: CGetL2 2
118: Add
119: SetL 2
121: PopC
71: CGetL 1
73: CGetL2 3
75: Lt
76: JmpZ 55 (131)
122: IncDecL 3 PreInc
125: PopC
126: Jmp -55
function addPositive($arr, $n) {
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$elem = $arr[$i];
if ($elem > 0) {
$sum = $sum + $elem;
}
}
return $sum;
}
94: SetL 4
96: PopC
97: Int 0
106: CGetL2 4
108: Gt
109: JmpZ 13 (122)
$i: int ; $n: int
$arr: array
Challenge #2: Huge Code Size
• HHVM dynamic (JITed) code: ~300 MB
• HHVM static code: ~130 MB
• Intel IvyBridge cache sizes:
– L1 i-cache: 32 KB / core
– LLC: 25 MB (shared)
– L1 I-TLB: 16.5 MB
• 8 x 2 MB = 16 MB
• 128 x 4 KB = 512 KB
17
Challenge #2a: JIT Speed
• Custom JIT compiler
– E.g. LLVM isn’t appropriate
• Translation Cache (TC)
– Reuse machine code across requests
• Only perform more expensive code
optimizations when there’s a big performance
impact on the generated code
18
Challenge #2b: Code Locality
1. Very selective function inlining in the JIT
2. Profile-guided JITed code layout
3. Hot/cold splitting of JITed code
4. Highly tuned runtime helpers (even hand-written in
assembly)
5. Profile-guided binary layout for the C++ written
runtime, using HFSort tool:
https://github.com/facebook/hhvm/tree/master/hphp/tools/hfsort
6. Selective use of Intel x86’s huge (2 MB) pages to
reduce I-TLB misses
19
Challenge #3: Reference Counting
• PHP uses reference counting for memory
management
– And it’s visible at the language level:
• Precise object destruction
• Copy-on-write of arrays
• Reference-counting optimization in the JIT
– Very complex and expensive optimization
– 5% performance impact
20
SetL 4
07: t4:Int = LdStack<Int,0> t3:StkPtr
09: StLoc<4> t1:FramePtr, t4:Int
10: IncRef t4:Str
...
PopC
11: DecRef t4:Str
...
count=3 object
Challenge #3: Reference Counting
• Ongoing effort to move to a tracing garbage
collector
– Currently used to collect cycles
21
More Than Just Performance:
Hack Language Support
• PHP dialect with extended type annotations,
among other language features
• Gradual typing to allow gradual migration of
large code bases
• Powerful static type checker
22
Summary
• High-load websites need high-performance software
• PHP is very popular and used to build many large-
scale websites
• Many challenges to efficiently execute PHP
• A lot of effort put into building and optimizing HHVM
• HHVM is open source
(https://github.com/facebook/hhvm)
• And it also supports the Hack language
(http://hacklang.org/)
23
Questions?
HHVM: Efficient and Scalable PHP/Hack Execution / Guilherme Ottoni (Facebook)

More Related Content

What's hot (20)

PDF
Job Queue in Golang
Bo-Yi Wu
 
PDF
Fuzzing: The New Unit Testing
Dmitry Vyukov
 
PDF
Mасштабирование микросервисов на Go, Matt Heath (Hailo)
Ontico
 
PDF
Application Logging in the 21st century - 2014.key
Tim Bunce
 
PPTX
PHP 5.6 New and Deprecated Features
Mark Niebergall
 
PDF
JRuby 9000 - Taipei Ruby User's Group 2015
Charles Nutter
 
ODP
30 Minutes To CPAN
daoswald
 
PPT
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
zznate
 
PDF
Asynchronous single page applications without a line of HTML or Javascript, o...
Robert Schadek
 
PDF
Information security programming in ruby
Hiroshi Nakamura
 
PDF
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
Vadym Kazulkin
 
ODP
Php in 2013 (Web-5 2013 conference)
julien pauli
 
PDF
Node.js Event Loop & EventEmitter
Simen Li
 
PDF
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
Ontico
 
PPT
Node js presentation
martincabrera
 
PDF
PL/Perl - New Features in PostgreSQL 9.0
Tim Bunce
 
ODP
The why and how of moving to PHP 5.5/5.6
Wim Godden
 
PDF
How to Begin Developing Ruby Core
Hiroshi SHIBATA
 
PDF
How to deploy node to production
Sean Hess
 
PPTX
All you need to know about the JavaScript event loop
Saša Tatar
 
Job Queue in Golang
Bo-Yi Wu
 
Fuzzing: The New Unit Testing
Dmitry Vyukov
 
Mасштабирование микросервисов на Go, Matt Heath (Hailo)
Ontico
 
Application Logging in the 21st century - 2014.key
Tim Bunce
 
PHP 5.6 New and Deprecated Features
Mark Niebergall
 
JRuby 9000 - Taipei Ruby User's Group 2015
Charles Nutter
 
30 Minutes To CPAN
daoswald
 
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
zznate
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Robert Schadek
 
Information security programming in ruby
Hiroshi Nakamura
 
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
Vadym Kazulkin
 
Php in 2013 (Web-5 2013 conference)
julien pauli
 
Node.js Event Loop & EventEmitter
Simen Li
 
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
Ontico
 
Node js presentation
martincabrera
 
PL/Perl - New Features in PostgreSQL 9.0
Tim Bunce
 
The why and how of moving to PHP 5.5/5.6
Wim Godden
 
How to Begin Developing Ruby Core
Hiroshi SHIBATA
 
How to deploy node to production
Sean Hess
 
All you need to know about the JavaScript event loop
Saša Tatar
 

Viewers also liked (20)

PDF
Балансировка нагрузки и отказоустойчивость в Одноклассниках
Ontico
 
PPTX
Производительность Unity3D: подводные камни / Алексей Чубарь (BIT.GAMES)
Ontico
 
PDF
Remote Highload / Андрей Смирнов (Virtustream)
Ontico
 
PDF
Красиво и не тормозит! Анимация без ущерба для производительности приложений ...
Ontico
 
PDF
Быстрое прототипирование бэкенда игры с геолокацией на OpenResty, Redis и Doc...
Ontico
 
PDF
Как мы сделали PHP 7 в два раза быстрее PHP 5 / Дмитрий Стогов (Zend Technolo...
Ontico
 
PPTX
Виртуальный ЦОД для корпоративных клиентов на базе Virtuozzo: стабильность, п...
Ontico
 
PPTX
Быстрый старт iOS приложения на примере iOS Почты Mail.Ru / Николай Морев (Ma...
Ontico
 
PDF
Cautious: IPv6 is here / Александр Азимов (Qrator Labs)
Ontico
 
PDF
Пользователь точно оценит! Повышение производительности мобильных приложений ...
Ontico
 
PDF
Борьба с DDoS в хостинге - по обе стороны баррикад / Константин Новаковский (...
Ontico
 
PPT
Как поддерживать и развивать пачку "похожих" проектов. Кластер или конгломера...
Ontico
 
PDF
Адаптивная оптимизация запросов в реляционных СУБД / Олег Иванов (Postgres Pr...
Ontico
 
PDF
Эффективная отладка репликации MySQL / Света Смирнова (Percona)
Ontico
 
PDF
Архитектура растущего проекта на примере ВКонтакте / Алексей Акулович (ВКонт...
Ontico
 
PDF
Поиск совпадений и дедупликация в потоке / Леонид Юрьев (Positive Technologies)
Ontico
 
PDF
Zabbix 3.2 - мониторинг качественно нового уровня / Алексей Владышев (Zabbix)
Ontico
 
PDF
Linux Kernel Extension for Databases / Александр Крижановский (Tempesta Techn...
Ontico
 
PDF
Как devops исчерпывает себя, и что будет дальше / Кирилл Вечера (Jetware)
Ontico
 
PDF
Highload на GPU, опыт Vinci / Олег Илларионов (ВКонтакте)
Ontico
 
Балансировка нагрузки и отказоустойчивость в Одноклассниках
Ontico
 
Производительность Unity3D: подводные камни / Алексей Чубарь (BIT.GAMES)
Ontico
 
Remote Highload / Андрей Смирнов (Virtustream)
Ontico
 
Красиво и не тормозит! Анимация без ущерба для производительности приложений ...
Ontico
 
Быстрое прототипирование бэкенда игры с геолокацией на OpenResty, Redis и Doc...
Ontico
 
Как мы сделали PHP 7 в два раза быстрее PHP 5 / Дмитрий Стогов (Zend Technolo...
Ontico
 
Виртуальный ЦОД для корпоративных клиентов на базе Virtuozzo: стабильность, п...
Ontico
 
Быстрый старт iOS приложения на примере iOS Почты Mail.Ru / Николай Морев (Ma...
Ontico
 
Cautious: IPv6 is here / Александр Азимов (Qrator Labs)
Ontico
 
Пользователь точно оценит! Повышение производительности мобильных приложений ...
Ontico
 
Борьба с DDoS в хостинге - по обе стороны баррикад / Константин Новаковский (...
Ontico
 
Как поддерживать и развивать пачку "похожих" проектов. Кластер или конгломера...
Ontico
 
Адаптивная оптимизация запросов в реляционных СУБД / Олег Иванов (Postgres Pr...
Ontico
 
Эффективная отладка репликации MySQL / Света Смирнова (Percona)
Ontico
 
Архитектура растущего проекта на примере ВКонтакте / Алексей Акулович (ВКонт...
Ontico
 
Поиск совпадений и дедупликация в потоке / Леонид Юрьев (Positive Technologies)
Ontico
 
Zabbix 3.2 - мониторинг качественно нового уровня / Алексей Владышев (Zabbix)
Ontico
 
Linux Kernel Extension for Databases / Александр Крижановский (Tempesta Techn...
Ontico
 
Как devops исчерпывает себя, и что будет дальше / Кирилл Вечера (Jetware)
Ontico
 
Highload на GPU, опыт Vinci / Олег Илларионов (ВКонтакте)
Ontico
 

Similar to HHVM: Efficient and Scalable PHP/Hack Execution / Guilherme Ottoni (Facebook) (20)

PDF
Just-In-Time Compiler in PHP 8
Nikita Popov
 
PDF
Debugging Hung Python Processes With GDB
bmbouter
 
PDF
How to build a feedback loop in software
Sandeep Joshi
 
PPTX
Php 7 hhvm and co
Pierre Joye
 
PPTX
Troubleshooting .net core on linux
Pavel Klimiankou
 
PDF
Pragmatic Optimization in Modern Programming - Ordering Optimization Approaches
Marina Kolpakova
 
PDF
Conan.io - The C/C++ package manager for Developers
Uilian Ries
 
PDF
Notes about moving from python to c++ py contw 2020
Yung-Yu Chen
 
PDF
Source Plugins
Matthew Pickering
 
PDF
Debugging Planning Issues Using Calcite's Built-in Loggers
Stamatis Zampetakis
 
PDF
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
Dong-hee Na
 
PDF
Global Interpreter Lock: Episode III - cat &lt; /dev/zero > GIL;
Tzung-Bi Shih
 
PPTX
Code optimization
veena venugopal
 
PPTX
Code optimization
veena venugopal
 
KEY
10 Catalyst Tips
Jay Shirley
 
PDF
Accelerated .NET Memory Dump Analysis training public slides
Dmitry Vostokov
 
PDF
High-Performance Python
Work-Bench
 
ODP
Linux kernel tracing superpowers in the cloud
Andrea Righi
 
PDF
Php through the eyes of a hoster
Combell NV
 
PDF
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...
Yusuke Izawa
 
Just-In-Time Compiler in PHP 8
Nikita Popov
 
Debugging Hung Python Processes With GDB
bmbouter
 
How to build a feedback loop in software
Sandeep Joshi
 
Php 7 hhvm and co
Pierre Joye
 
Troubleshooting .net core on linux
Pavel Klimiankou
 
Pragmatic Optimization in Modern Programming - Ordering Optimization Approaches
Marina Kolpakova
 
Conan.io - The C/C++ package manager for Developers
Uilian Ries
 
Notes about moving from python to c++ py contw 2020
Yung-Yu Chen
 
Source Plugins
Matthew Pickering
 
Debugging Planning Issues Using Calcite's Built-in Loggers
Stamatis Zampetakis
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
Dong-hee Na
 
Global Interpreter Lock: Episode III - cat &lt; /dev/zero > GIL;
Tzung-Bi Shih
 
Code optimization
veena venugopal
 
Code optimization
veena venugopal
 
10 Catalyst Tips
Jay Shirley
 
Accelerated .NET Memory Dump Analysis training public slides
Dmitry Vostokov
 
High-Performance Python
Work-Bench
 
Linux kernel tracing superpowers in the cloud
Andrea Righi
 
Php through the eyes of a hoster
Combell NV
 
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...
Yusuke Izawa
 

More from Ontico (20)

PDF
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
Ontico
 
PDF
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
Ontico
 
PPTX
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
Ontico
 
PDF
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
Ontico
 
PDF
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
Ontico
 
PDF
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Ontico
 
PDF
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
Ontico
 
PPTX
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
Ontico
 
PPTX
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
Ontico
 
PDF
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
Ontico
 
PPTX
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Ontico
 
PPTX
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
Ontico
 
PDF
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
Ontico
 
PPT
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
Ontico
 
PPTX
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
Ontico
 
PPTX
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
Ontico
 
PPTX
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
Ontico
 
PPTX
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
Ontico
 
PDF
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...
Ontico
 
PDF
Как мы учились чинить самолеты в воздухе / Евгений Коломеец (Virtuozzo)
Ontico
 
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
Ontico
 
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
Ontico
 
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
Ontico
 
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
Ontico
 
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
Ontico
 
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Ontico
 
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
Ontico
 
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
Ontico
 
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
Ontico
 
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
Ontico
 
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Ontico
 
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
Ontico
 
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
Ontico
 
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
Ontico
 
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
Ontico
 
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
Ontico
 
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
Ontico
 
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
Ontico
 
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...
Ontico
 
Как мы учились чинить самолеты в воздухе / Евгений Коломеец (Virtuozzo)
Ontico
 

Recently uploaded (20)

PPTX
Stability of IBR Dominated Grids - IEEE PEDG 2025 - short.pptx
ssuser307730
 
PDF
Bayesian Learning - Naive Bayes Algorithm
Sharmila Chidaravalli
 
PDF
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
PDF
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
PPTX
Comparison of Flexible and Rigid Pavements in Bangladesh
Arifur Rahman
 
PDF
How to Buy Verified CashApp Accounts IN 2025
Buy Verified CashApp Accounts
 
PDF
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
PPTX
Unit_I Functional Units, Instruction Sets.pptx
logaprakash9
 
PDF
PROGRAMMING REQUESTS/RESPONSES WITH GREATFREE IN THE CLOUD ENVIRONMENT
samueljackson3773
 
PDF
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
PPTX
Precooling and Refrigerated storage.pptx
ThongamSunita
 
PDF
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
PDF
LLC CM NCP1399 SIMPLIS MODEL MANUAL.PDF
ssuser1be9ce
 
PDF
Plant Control_EST_85520-01_en_AllChanges_20220127.pdf
DarshanaChathuranga4
 
PPTX
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
PDF
lesson4-occupationalsafetyandhealthohsstandards-240812020130-1a7246d0.pdf
arvingallosa3
 
PPTX
Functions in Python Programming Language
BeulahS2
 
PDF
June 2025 - Top 10 Read Articles in Network Security and Its Applications
IJNSA Journal
 
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
PDF
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
Stability of IBR Dominated Grids - IEEE PEDG 2025 - short.pptx
ssuser307730
 
Bayesian Learning - Naive Bayes Algorithm
Sharmila Chidaravalli
 
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
Comparison of Flexible and Rigid Pavements in Bangladesh
Arifur Rahman
 
How to Buy Verified CashApp Accounts IN 2025
Buy Verified CashApp Accounts
 
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
Unit_I Functional Units, Instruction Sets.pptx
logaprakash9
 
PROGRAMMING REQUESTS/RESPONSES WITH GREATFREE IN THE CLOUD ENVIRONMENT
samueljackson3773
 
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
Precooling and Refrigerated storage.pptx
ThongamSunita
 
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
LLC CM NCP1399 SIMPLIS MODEL MANUAL.PDF
ssuser1be9ce
 
Plant Control_EST_85520-01_en_AllChanges_20220127.pdf
DarshanaChathuranga4
 
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
lesson4-occupationalsafetyandhealthohsstandards-240812020130-1a7246d0.pdf
arvingallosa3
 
Functions in Python Programming Language
BeulahS2
 
June 2025 - Top 10 Read Articles in Network Security and Its Applications
IJNSA Journal
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 

HHVM: Efficient and Scalable PHP/Hack Execution / Guilherme Ottoni (Facebook)

  • 2. HHVM: Efficient and Scalable PHP/Hack Execution Guilherme Ottoni HHVM Team Facebook November 2016
  • 3. Speaker Intro 3 • Background in compilers, performance analysis and optimizations • 15+ years working in these areas • Spent last 5.5 years pushing the limits of PHP performance at Facebook
  • 4. Motivation: Why PHP? • Many claim it’s a poorly designed language • But it’s pretty successful and widely used, especially for server-side web development • Biggest strengths: – Integration with web servers – Rapid development cycle 4 FAST
  • 5. Motivation: Why PHP? • Top websites [http://www.alexa.com/topsites]: 1. Google 2. Youtube 3. Facebook 4. Baidu 5. Wikipedia 6. Yahoo 5 PHP
  • 6. Motivation: Why HHVM? • High load requires high performance • Standard PHP – Not very efficient – Interpreter-based – Only industry-strength implementation of PHP that existed 6 • HHVM’s goals: 1. Improve performance of PHP execution 2. Compatibility with Standard PHP
  • 8. Motivation: Why HHVM? • Top websites [http://www.alexa.com/topsites]: 1. Google 2. Youtube 3. Facebook 4. Baidu 5. Wikipedia 6. Yahoo 8 HHVM • Many other adopters, e.g. Box, Etsy, Slack, Wordpress • Wikipedia’s CPU usage dropped by 6x when it switched to HHVM [http://hhvm.com/blog/7205/wikipedia-on-hhvm]
  • 9. Overview of HHVM Pipeline 9 PHP AST Optimize Parser HHBC Bytecode Emitter Optimize, Type Inference AheadofTime HHBC HHIR Optimize x86Vasm Optimize Runtime
  • 10. Challenges for PHP Performance 1. Lack of static type information 2. Huge amounts of code a. JIT speed b. Code locality 3. Reference counting 10
  • 11. Challenge #1: Dynamic Typing • HHVM’s basic principle to achieve performance: operate on type- specialized code • Ahead-of-time type inference – AST-based – Bytecode-based 11 HHBC Optimize, Type Inference
  • 12. Challenge #1: Dynamic Typing • Runtime type specialization 1. Tracelet JIT • Inspect live types & JIT small code blocks as you go 2. Profile-driven Region JIT • Collect type information in the beginning, then later compile larger code regions 12
  • 13. $elem: uncount; stk: dbl 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC $sum: dbl ; $elem: int $sum: dbl ; $elem: dbl $sum: int ; $elem: dbl 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC Example 13 81: CGetM <L:0 EL:3> 94: SetL 4 96: PopC 97: Int 0 106: CGetL2 4 108: Gt 109: JmpZ 13 (122) 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC 71: CGetL 1 73: CGetL2 3 75: Lt 76: JmpZ 55 (131) 122: IncDecL 3 PreInc 125: PopC 126: Jmp -55 function addPositive($arr, $n) { $sum = 0; for ($i = 0; $i < $n; $i++) { $elem = $arr[$i]; if ($elem > 0) { $sum = $sum + $elem; } } return $sum; } 94: SetL 4 96: PopC 97: Int 0 106: CGetL2 4 108: Gt 109: JmpZ 13 (122) $elem: uncount; stk: int $i: int ; $n: int $arr: array ; $i: int $sum: int ; $elem: int $i: int
  • 14. $sum: dbl ; $elem: int $elem: uncount; stk: dbl 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC $sum: dbl ; $elem: dbl $sum: int ; $elem: dbl 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC Example 14 81: CGetM <L:0 EL:3> 94: SetL 4 96: PopC 97: Int 0 106: CGetL2 4 108: Gt 109: JmpZ 13 (122) 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC 71: CGetL 1 73: CGetL2 3 75: Lt 76: JmpZ 55 (131) 122: IncDecL 3 PreInc 125: PopC 126: Jmp -55 function addPositive($arr, $n) { $sum = 0; for ($i = 0; $i < $n; $i++) { $elem = $arr[$i]; if ($elem > 0) { $sum = $sum + $elem; } } return $sum; } 94: SetL 4 96: PopC 97: Int 0 106: CGetL2 4 108: Gt 109: JmpZ 13 (122) $elem: uncount; stk: int $i: int ; $n: int $arr: array ; $i: int $sum: int ; $elem: int $i: int
  • 15. $elem: uncount; stk: dbl $sum: dbl ; $elem: dbl Example 15 81: CGetM <L:0 EL:3> 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC 71: CGetL 1 73: CGetL2 3 75: Lt 76: JmpZ 55 (131) 122: IncDecL 3 PreInc 125: PopC 126: Jmp -55 function addPositive($arr, $n) { $sum = 0; for ($i = 0; $i < $n; $i++) { $elem = $arr[$i]; if ($elem > 0) { $sum = $sum + $elem; } } return $sum; } 94: SetL 4 96: PopC 97: Int 0 106: CGetL2 4 108: Gt 109: JmpZ 13 (122) $i: int ; $n: int $arr: array ; $i: int $i: int
  • 16. $elem: uncount; stk: dbl $sum: dbl Example 16 81: CGetM <L:0 EL:3> 114: CGetL 4 116: CGetL2 2 118: Add 119: SetL 2 121: PopC 71: CGetL 1 73: CGetL2 3 75: Lt 76: JmpZ 55 (131) 122: IncDecL 3 PreInc 125: PopC 126: Jmp -55 function addPositive($arr, $n) { $sum = 0; for ($i = 0; $i < $n; $i++) { $elem = $arr[$i]; if ($elem > 0) { $sum = $sum + $elem; } } return $sum; } 94: SetL 4 96: PopC 97: Int 0 106: CGetL2 4 108: Gt 109: JmpZ 13 (122) $i: int ; $n: int $arr: array
  • 17. Challenge #2: Huge Code Size • HHVM dynamic (JITed) code: ~300 MB • HHVM static code: ~130 MB • Intel IvyBridge cache sizes: – L1 i-cache: 32 KB / core – LLC: 25 MB (shared) – L1 I-TLB: 16.5 MB • 8 x 2 MB = 16 MB • 128 x 4 KB = 512 KB 17
  • 18. Challenge #2a: JIT Speed • Custom JIT compiler – E.g. LLVM isn’t appropriate • Translation Cache (TC) – Reuse machine code across requests • Only perform more expensive code optimizations when there’s a big performance impact on the generated code 18
  • 19. Challenge #2b: Code Locality 1. Very selective function inlining in the JIT 2. Profile-guided JITed code layout 3. Hot/cold splitting of JITed code 4. Highly tuned runtime helpers (even hand-written in assembly) 5. Profile-guided binary layout for the C++ written runtime, using HFSort tool: https://github.com/facebook/hhvm/tree/master/hphp/tools/hfsort 6. Selective use of Intel x86’s huge (2 MB) pages to reduce I-TLB misses 19
  • 20. Challenge #3: Reference Counting • PHP uses reference counting for memory management – And it’s visible at the language level: • Precise object destruction • Copy-on-write of arrays • Reference-counting optimization in the JIT – Very complex and expensive optimization – 5% performance impact 20 SetL 4 07: t4:Int = LdStack<Int,0> t3:StkPtr 09: StLoc<4> t1:FramePtr, t4:Int 10: IncRef t4:Str ... PopC 11: DecRef t4:Str ... count=3 object
  • 21. Challenge #3: Reference Counting • Ongoing effort to move to a tracing garbage collector – Currently used to collect cycles 21
  • 22. More Than Just Performance: Hack Language Support • PHP dialect with extended type annotations, among other language features • Gradual typing to allow gradual migration of large code bases • Powerful static type checker 22
  • 23. Summary • High-load websites need high-performance software • PHP is very popular and used to build many large- scale websites • Many challenges to efficiently execute PHP • A lot of effort put into building and optimizing HHVM • HHVM is open source (https://github.com/facebook/hhvm) • And it also supports the Hack language (http://hacklang.org/) 23

Editor's Notes

  • #12: Philosophy to obtain high performance: only operate on typed code
  • #13: Philosophy to obtain high performance: only operate on typed code
  • #14: Runs 17% faster with profile-guided trace formation compared to the baseline tracelet translator.
  • #15: Runs 17% faster with profile-guided trace formation compared to the baseline tracelet translator.
  • #16: Runs 17% faster with profile-guided trace formation compared to the baseline tracelet translator.
  • #17: Runs 17% faster with profile-guided trace formation compared to the baseline tracelet translator.
  • #26: END