forked from facebook/hhvm
/
analysis_result.cpp
5465 lines (4921 loc) · 183 KB
/
analysis_result.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <iomanip>
#include <algorithm>
#include <sstream>
#include <boost/format.hpp>
#include <boost/bind.hpp>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/alias_manager.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/depth_first_visitor.h>
#include <compiler/statement/statement_list.h>
#include <compiler/statement/if_branch_statement.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/loop_statement.h>
#include <compiler/analysis/symbol_table.h>
#include <compiler/package.h>
#include <compiler/parser/parser.h>
#include <compiler/option.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/builtin_symbols.h>
#include <compiler/analysis/constant_table.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/expression/scalar_expression.h>
#include <compiler/expression/constant_expression.h>
#include <compiler/expression/expression_list.h>
#include <compiler/expression/array_pair_expression.h>
#include <runtime/base/rtti_info.h>
#include <runtime/base/array/small_array.h>
#include <runtime/ext/ext_json.h>
#include <runtime/base/zend/zend_printf.h>
#include <util/atomic.h>
#include <util/logger.h>
#include <util/util.h>
#include <util/hash.h>
#include <util/process.h>
#include <util/job_queue.h>
#include <util/timer.h>
using namespace HPHP;
using namespace std;
using namespace boost;
///////////////////////////////////////////////////////////////////////////////
// initialization
IMPLEMENT_THREAD_LOCAL(BlockScopeRawPtr,
AnalysisResult::s_currentScopeThreadLocal);
IMPLEMENT_THREAD_LOCAL(BlockScopeRawPtrFlagsHashMap,
AnalysisResult::s_changedScopesMapThreadLocal);
AnalysisResult::AnalysisResult()
: BlockScope("Root", "", StatementPtr(), BlockScope::ProgramScope),
m_arrayLitstrKeyMaxSize(0), m_arrayIntegerKeyMaxSize(0),
m_package(NULL), m_parseOnDemand(false), m_phase(ParseAllFiles),
m_scalarArraysCounter(0), m_paramRTTICounter(0),
m_scalarArraySortedAvgLen(0), m_scalarArraySortedIndex(0),
m_scalarArraySortedSumLen(0), m_scalarArrayCompressedTextSize(0),
m_pregenerating(false), m_pregenerated(false),
m_system(false), m_sepExtension(false) {
m_classForcedVariants[0] = m_classForcedVariants[1] = false;
}
void AnalysisResult::appendExtraCode(const std::string &key,
const std::string &code) {
string &extraCode = m_extraCodes[key];
if (extraCode.empty()) {
extraCode = "<?php\n";
}
extraCode += code + "\n";
}
void AnalysisResult::appendExtraCode(const std::string &key,
const std::string &code) const {
lock()->appendExtraCode(key, code);
}
void AnalysisResult::parseExtraCode(const string &key) {
Lock lock(getMutex());
map<string, string>::iterator iter = m_extraCodes.find(key);
if (iter != m_extraCodes.end()) {
string code = iter->second;
string sfilename = iter->first + "." + Option::LambdaPrefix + "lambda";
m_extraCodes.erase(key);
const char *filename = m_extraCodeFileNames.add(sfilename.c_str());
Compiler::Parser::ParseString(code, shared_from_this(), filename, true);
}
}
///////////////////////////////////////////////////////////////////////////////
// general functions
void AnalysisResult::addFileScope(FileScopePtr fileScope) {
ASSERT(fileScope);
FileScopePtr &res = m_files[fileScope->getName()];
ASSERT(!res);
res = fileScope;
vertex_descriptor vertex = add_vertex(m_depGraph);
fileScope->setVertex(vertex);
m_fileVertMap[vertex] = fileScope;
m_fileScopes.push_back(fileScope);
}
bool AnalysisResult::inParseOnDemandDirs(const string &filename) const {
for (size_t i = 0; i < m_parseOnDemandDirs.size(); i++) {
if (filename.find(m_parseOnDemandDirs[i]) == 0) return true;
}
return false;
}
void AnalysisResult::parseOnDemand(const std::string &name) const {
if (m_package) {
const std::string &root = m_package->getRoot();
string rname = name;
if (name.find(root) == 0) {
rname = name.substr(root.length());
}
if (m_files.find(rname) == m_files.end() &&
(m_parseOnDemand || inParseOnDemandDirs(rname)) &&
Option::PackageExcludeFiles.find(rname) ==
Option::PackageExcludeFiles.end() &&
!Option::IsFileExcluded(rname, Option::PackageExcludePatterns)) {
m_package->addSourceFile(rname.c_str());
}
}
}
FileScopePtr AnalysisResult::findFileScope(const std::string &name) const {
StringToFileScopePtrMap::const_iterator iter = m_files.find(name);
if (iter != m_files.end()) {
return iter->second;
}
return FileScopePtr();
}
FunctionScopePtr AnalysisResult::findFunction(
const std::string &funcName) const {
StringToFunctionScopePtrMap::const_iterator bit =
m_functions.find(funcName);
if (bit != m_functions.end()) {
return bit->second;
}
StringToFunctionScopePtrMap::const_iterator iter =
m_functionDecs.find(funcName);
if (iter != m_functionDecs.end()) {
return iter->second;
}
return FunctionScopePtr();
}
BlockScopePtr AnalysisResult::findConstantDeclarer(
const std::string &name) {
if (getConstants()->isPresent(name)) return shared_from_this();
StringToFileScopePtrMap::const_iterator iter = m_constDecs.find(name);
if (iter != m_constDecs.end()) return iter->second;
return BlockScopePtr();
}
ClassScopePtr AnalysisResult::findClass(const std::string &name) const {
AnalysisResultConstPtr ar = shared_from_this();
string lname = Util::toLower(name);
StringToClassScopePtrMap::const_iterator sysIter =
m_systemClasses.find(lname);
if (sysIter != m_systemClasses.end()) return sysIter->second;
StringToClassScopePtrVecMap::const_iterator iter = m_classDecs.find(lname);
if (iter != m_classDecs.end() && iter->second.size()) {
return iter->second.back();
}
return ClassScopePtr();
}
ClassScopePtr AnalysisResult::findClass(const std::string &name,
FindClassBy by) {
AnalysisResultPtr ar = shared_from_this();
if (by == PropertyName) return ClassScopePtr();
string lname = Util::toLower(name);
if (by == MethodName) {
StringToClassScopePtrVecMap::iterator iter =
m_methodToClassDecs.find(lname);
if (iter != m_methodToClassDecs.end()) {
if (iter->second.size() == 1) {
iter->second[0]->findFunction(ar, lname, true)->setDynamic();
return ClassScopePtr();
} else {
// The call to findClass by method name means all these
// same-named methods should be dynamic since there will
// be an invoke to call one of them.
BOOST_FOREACH(ClassScopePtr cls, iter->second) {
FunctionScopePtr func = cls->findFunction(ar, lname, true);
// Something fishy here
if (func) {
func->setDynamic();
}
}
iter->second.clear();
}
}
} else {
return findClass(name);
}
return ClassScopePtr();
}
const ClassScopePtrVec &AnalysisResult::findRedeclaredClasses
(const std::string &name) const {
StringToClassScopePtrVecMap::const_iterator iter = m_classDecs.find(name);
if (iter == m_classDecs.end()) {
static ClassScopePtrVec empty;
empty.clear();
return empty;
}
return iter->second;
}
ClassScopePtrVec AnalysisResult::findClasses(const std::string &name) const {
StringToClassScopePtrMap::const_iterator sysIter =
m_systemClasses.find(name);
if (sysIter != m_systemClasses.end()) {
return ClassScopePtrVec(1, sysIter->second);
}
return findRedeclaredClasses(name);
}
bool AnalysisResult::classMemberExists(const std::string &name,
FindClassBy by) const {
if (by == MethodName) {
return m_methodToClassDecs.find(name) != m_methodToClassDecs.end();
}
return m_classDecs.find(name) != m_classDecs.end();
}
ClassScopePtr AnalysisResult::findExactClass(ConstructPtr cs,
const std::string &name) const {
ClassScopePtr cls = findClass(name);
if (!cls || !cls->isRedeclaring()) return cls;
std::string lowerName = Util::toLower(name);
if (ClassScopePtr currentCls = cs->getClassScope()) {
if (lowerName == currentCls->getName()) {
return currentCls;
}
}
if (FileScopePtr currentFile = cs->getFileScope()) {
StatementList &stmts = *currentFile->getStmt();
for (int i = stmts.getCount(); i--; ) {
StatementPtr s = stmts[i];
if (s && s->is(Statement::KindOfClassStatement)) {
ClassScopeRawPtr scope =
static_pointer_cast<ClassStatement>(s)->getClassScope();
if (lowerName == scope->getName()) {
return scope;
}
}
}
}
return ClassScopePtr();
}
bool AnalysisResult::checkClassPresent(ConstructPtr cs,
const std::string &name) const {
if (name == "self" || name == "parent") return true;
std::string lowerName = Util::toLower(name);
if (ClassScopePtr currentCls = cs->getClassScope()) {
if (lowerName == currentCls->getName() ||
currentCls->derivesFrom(shared_from_this(), lowerName,
true, false)) {
return true;
}
}
if (FileScopePtr currentFile = cs->getFileScope()) {
StatementList &stmts = *currentFile->getStmt();
for (int i = stmts.getCount(); i--; ) {
StatementPtr s = stmts[i];
if (s && s->is(Statement::KindOfClassStatement)) {
ClassScopePtr scope =
static_pointer_cast<ClassStatement>(s)->getClassScope();
if (lowerName == scope->getName()) {
return true;
}
if (scope->derivesFrom(shared_from_this(), lowerName,
true, false)) {
return true;
}
}
}
}
return false;
}
int AnalysisResult::getFunctionCount() const {
int total = 0;
for (StringToFileScopePtrMap::const_iterator iter = m_files.begin();
iter != m_files.end(); ++iter) {
total += iter->second->getFunctionCount();
}
return total;
}
int AnalysisResult::getClassCount() const {
int total = 0;
for (StringToFileScopePtrMap::const_iterator iter = m_files.begin();
iter != m_files.end(); ++iter) {
total += iter->second->getClassCount();
}
return total;
}
void AnalysisResult::countReturnTypes(std::map<std::string, int> &counts) {
for (StringToFileScopePtrMap::const_iterator iter = m_files.begin();
iter != m_files.end(); ++iter) {
iter->second->countReturnTypes(counts);
}
}
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
bool AnalysisResult::declareFunction(FunctionScopePtr funcScope) const {
ASSERT(m_phase <= AnalyzeInclude);
string fname = funcScope->getName();
// System functions override
if (m_functions.find(fname) != m_functions.end()) {
// we need someone to hold on to a reference to it
// even though we're not going to do anything with it
this->lock()->m_ignoredScopes.push_back(funcScope);
return false;
}
return true;
}
bool AnalysisResult::declareClass(ClassScopePtr classScope) const {
ASSERT(m_phase <= AnalyzeInclude);
string cname = classScope->getName();
// System classes override
if (m_systemClasses.find(cname) != m_systemClasses.end()) {
// we need someone to hold on to a reference to it
// even though we're not going to do anything with it
this->lock()->m_ignoredScopes.push_back(classScope);
return false;
}
int mask =
(m_classForcedVariants[0] ? VariableTable::NonPrivateNonStaticVars : 0) |
(m_classForcedVariants[1] ? VariableTable::NonPrivateStaticVars : 0);
if (mask) {
AnalysisResultConstPtr ar = shared_from_this();
classScope->getVariables()->forceVariants(ar, mask);
}
return true;
}
void AnalysisResult::declareUnknownClass(const std::string &name) {
m_classDecs.operator[](name);
}
bool AnalysisResult::declareConst(FileScopePtr fs, const string &name) {
if (getConstants()->isPresent(name) ||
m_constDecs.find(name) != m_constDecs.end()) {
m_constRedeclared.insert(name);
return false;
} else {
m_constDecs[name] = fs;
return true;
}
}
static bool by_source(const BlockScopePtr &b1, const BlockScopePtr &b2) {
return b1->getStmt()->getLocation()->
compare(b2->getStmt()->getLocation().get()) < 0;
}
void AnalysisResult::canonicalizeSymbolOrder() {
getConstants()->canonicalizeSymbolOrder();
getVariables()->canonicalizeSymbolOrder();
AnalysisResultPtr ar = shared_from_this();
for (StringToClassScopePtrVecMap::iterator iter = m_classDecs.begin();
iter != m_classDecs.end(); ++iter) {
ClassScopePtrVec &classes = iter->second;
if (classes.size() > 1) {
sort(classes.begin(), classes.end(), by_source);
for (unsigned int i = 0; i < classes.size(); i++) {
classes[i]->setRedeclaring(ar, i);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Dependencies
void AnalysisResult::link(FileScopePtr user, FileScopePtr provider) {
if (user != provider) {
bool needsLock = getPhase() != AnalyzeAll &&
getPhase() != AnalyzeFinal;
ConditionalLock lock(m_depGraphMutex, needsLock);
add_edge(user->vertex(), provider->vertex(), m_depGraph);
}
}
bool AnalysisResult::addClassDependency(FileScopePtr usingFile,
const std::string &className) {
if (BuiltinSymbols::s_classes.find(className) !=
BuiltinSymbols::s_classes.end())
return true;
StringToClassScopePtrVecMap::const_iterator iter =
m_classDecs.find(className);
if (iter == m_classDecs.end() || iter->second.size() != 1) return false;
ClassScopePtr classScope = iter->second[0];
FileScopePtr fileScope = classScope->getContainingFile();
link(usingFile, fileScope);
return true;
}
bool AnalysisResult::addFunctionDependency(FileScopePtr usingFile,
const std::string &functionName) {
if (BuiltinSymbols::s_functions.find(functionName) !=
BuiltinSymbols::s_functions.end())
return true;
StringToFunctionScopePtrMap::const_iterator iter =
m_functionDecs.find(functionName);
if (iter == m_functionDecs.end() || iter->second->isRedeclaring()) {
return false;
}
FunctionScopePtr functionScope = iter->second;
FileScopePtr fileScope = functionScope->getContainingFile();
link(usingFile, fileScope);
return true;
}
bool AnalysisResult::addIncludeDependency(FileScopePtr usingFile,
const std::string &includeFilename) {
ASSERT(!includeFilename.empty());
FileScopePtr fileScope = findFileScope(includeFilename);
if (fileScope) {
link(usingFile, fileScope);
return true;
} else {
return false;
}
}
bool AnalysisResult::addConstantDependency(FileScopePtr usingFile,
const std::string &constantName) {
if (m_constants->isPresent(constantName))
return true;
StringToFileScopePtrMap::const_iterator iter =
m_constDecs.find(constantName);
if (iter == m_constDecs.end()) return false;
FileScopePtr fileScope = iter->second;
link(usingFile, fileScope);
return true;
}
bool AnalysisResult::isConstantDeclared(const std::string &constName) const {
if (m_constants->isPresent(constName)) return true;
StringToFileScopePtrMap::const_iterator iter = m_constDecs.find(constName);
if (iter == m_constDecs.end()) return false;
FileScopePtr fileScope = iter->second;
ConstantTablePtr constants = fileScope->getConstants();
ConstructPtr decl = constants->getValue(constName);
if (decl) return true;
return false;
}
bool AnalysisResult::isConstantRedeclared(const std::string &constName) const {
return m_constRedeclared.find(constName) != m_constRedeclared.end();
}
bool AnalysisResult::isSystemConstant(const std::string &constName) const {
return m_constants->isSystem(constName);
}
///////////////////////////////////////////////////////////////////////////////
// Program
void AnalysisResult::loadBuiltinFunctions() {
AnalysisResultPtr ar = shared_from_this();
BuiltinSymbols::LoadFunctions(ar, m_functions);
}
void AnalysisResult::loadBuiltins() {
AnalysisResultPtr ar = shared_from_this();
BuiltinSymbols::LoadFunctions(ar, m_functions);
BuiltinSymbols::LoadClasses(ar, m_systemClasses);
BuiltinSymbols::LoadVariables(ar, m_variables);
BuiltinSymbols::LoadConstants(ar, m_constants);
}
void AnalysisResult::checkClassDerivations() {
AnalysisResultPtr ar = shared_from_this();
ClassScopePtr cls;
for (StringToClassScopePtrVecMap::const_iterator iter = m_classDecs.begin();
iter != m_classDecs.end(); ++iter) {
BOOST_FOREACH(cls, iter->second) {
hphp_string_iset seen;
cls->checkDerivation(ar, seen);
}
}
}
void AnalysisResult::collectFunctionsAndClasses(FileScopePtr fs) {
const StringToFunctionScopePtrMap &funcs = fs->getFunctions();
for (StringToFunctionScopePtrMap::const_iterator iter = funcs.begin();
iter != funcs.end(); ++iter) {
FunctionScopePtr func = iter->second;
if (!func->inPseudoMain()) {
FunctionScopePtr &funcDec = m_functionDecs[iter->first];
if (funcDec) {
FunctionScopePtrVec &funcVec = m_functionReDecs[iter->first];
int sz = funcVec.size();
if (!sz) {
funcDec->setRedeclaring(sz++);
funcVec.push_back(funcDec);
}
func->setRedeclaring(sz++);
funcVec.push_back(func);
} else {
funcDec = func;
}
}
}
if (const StringToFunctionScopePtrVecMap *redec = fs->getRedecFunctions()) {
for (StringToFunctionScopePtrVecMap::const_iterator iter = redec->begin();
iter != redec->end(); ++iter) {
FunctionScopePtrVec::const_iterator i = iter->second.begin();
FunctionScopePtrVec::const_iterator e = iter->second.end();
FunctionScopePtr &funcDec = m_functionDecs[iter->first];
ASSERT(funcDec); // because the first one was in funcs above
FunctionScopePtrVec &funcVec = m_functionReDecs[iter->first];
int sz = funcVec.size();
if (!sz) {
funcDec->setRedeclaring(sz++);
funcVec.push_back(funcDec);
}
while (++i != e) { // we already added the first one
(*i)->setRedeclaring(sz++);
funcVec.push_back(*i);
}
}
}
const StringToClassScopePtrVecMap &classes = fs->getClasses();
for (StringToClassScopePtrVecMap::const_iterator iter = classes.begin();
iter != classes.end(); ++iter) {
ClassScopePtrVec &clsVec = m_classDecs[iter->first];
clsVec.insert(clsVec.end(), iter->second.begin(), iter->second.end());
}
}
static bool by_filename(const FileScopePtr &f1, const FileScopePtr &f2) {
return f1->getName() < f2->getName();
}
void AnalysisResult::analyzeProgram(bool system /* = false */) {
AnalysisResultPtr ar = shared_from_this();
if (system) m_system = true;
getVariables()->forceVariants(ar, VariableTable::AnyVars);
getVariables()->setAttribute(VariableTable::ContainsLDynamicVariable);
getVariables()->setAttribute(VariableTable::ContainsExtract);
getVariables()->setAttribute(VariableTable::ForceGlobal);
// Analyze Includes
Logger::Verbose("Analyzing Includes");
setPhase(AnalysisResult::AnalyzeInclude);
sort(m_fileScopes.begin(), m_fileScopes.end(), by_filename); // fixed order
unsigned int i = 0;
for (i = 0; i < m_fileScopes.size(); i++) {
collectFunctionsAndClasses(m_fileScopes[i]);
}
// Keep generated code identical without randomness
canonicalizeSymbolOrder();
// Analyze some special cases
for (set<string>::const_iterator it = Option::VolatileClasses.begin();
it != Option::VolatileClasses.end(); ++it) {
ClassScopePtr cls = findClass(Util::toLower(*it));
if (cls && cls->isUserClass()) {
cls->setVolatile();
}
}
// I think we need one more round of checking, as new includes may bring in
// more classes.
checkClassDerivations();
// Analyze All
Logger::Verbose("Analyzing All");
setPhase(AnalysisResult::AnalyzeAll);
for (i = 0; i < m_fileScopes.size(); i++) {
m_fileScopes[i]->analyzeProgram(ar);
}
/*
Note that cls->collectMethods() can add entries to m_classDecs,
which can invalidate iterators. So we have to create an array
and then iterate over that.
The new entries added to m_classDecs are always empty, so it
doesnt matter that we dont include them in the iteration
*/
ClassScopePtr cls;
std::vector<ClassScopePtr> classes;
classes.reserve(m_classDecs.size());
for (StringToClassScopePtrVecMap::const_iterator iter = m_classDecs.begin();
iter != m_classDecs.end(); ++iter) {
BOOST_FOREACH(cls, iter->second) {
classes.push_back(cls);
}
}
// Collect methods
BOOST_FOREACH(cls, classes) {
if (cls->isRedeclaring()) {
cls->setStaticDynamic(ar);
}
StringToFunctionScopePtrMap methods;
cls->collectMethods(ar, methods);
bool needAbstractMethodImpl =
(!cls->isAbstract() && !cls->isInterface() &&
!cls->derivesFromRedeclaring());
for (StringToFunctionScopePtrMap::const_iterator iterMethod =
methods.begin(); iterMethod != methods.end(); ++iterMethod) {
FunctionScopePtr func = iterMethod->second;
if (!func->hasImpl() && needAbstractMethodImpl) {
FunctionScopePtr tmpFunc =
cls->findFunction(ar, func->getName(), true, true);
assert(!tmpFunc || !tmpFunc->hasImpl());
Compiler::Error(Compiler::MissingAbstractMethodImpl,
func->getStmt(), cls->getStmt());
}
m_methodToClassDecs[iterMethod->first].push_back(cls);
}
}
string cname;
BOOST_FOREACH(tie(cname, cls), m_systemClasses) {
StringToFunctionScopePtrMap methods;
cls->collectMethods(ar, methods);
for (StringToFunctionScopePtrMap::const_iterator iterMethod =
methods.begin(); iterMethod != methods.end(); ++iterMethod) {
m_methodToClassDecs[iterMethod->first].push_back(cls);
}
}
// Analyze perfect virtuals
if (Option::AnalyzePerfectVirtuals && !system) {
analyzePerfectVirtuals();
}
}
static void addClassRootMethods(AnalysisResultPtr ar, ClassScopePtr cls,
hphp_string_set &methods) {
const StringToFunctionScopePtrMap &funcs = cls->getFunctions();
for (StringToFunctionScopePtrMap::const_iterator iter =
funcs.begin(); iter != funcs.end(); ++iter) {
ClassScopePtrVec roots;
cls->getRootParents(ar, iter->first, roots, cls);
for (unsigned int i = 0; i < roots.size(); i++) {
methods.insert(roots[i]->getName() + "::" + iter->first);
}
}
}
static void addClassRootMethods(AnalysisResultPtr ar, ClassScopePtr cls,
StringToFunctionScopePtrVecMap &methods) {
const StringToFunctionScopePtrMap &funcs = cls->getFunctions();
for (StringToFunctionScopePtrMap::const_iterator iter =
funcs.begin(); iter != funcs.end(); ++iter) {
ClassScopePtr root = cls->getRootParent(ar, iter->first);
string cluster = root->getName() + "::" + iter->first;
FunctionScopePtrVec &fs = methods[cluster];
fs.push_back(iter->second);
}
}
void AnalysisResult::analyzePerfectVirtuals() {
AnalysisResultPtr ar = shared_from_this();
StringToFunctionScopePtrVecMap methods;
hphp_string_set redeclaringMethods;
for (StringToClassScopePtrVecMap::const_iterator iter = m_classDecs.begin();
iter != m_classDecs.end(); ++iter) {
for (unsigned int i = 0; i < iter->second.size(); i++) {
ClassScopePtr cls = iter->second[i];
// being conservative, not to do redeclaring classes at all
if (cls->derivesFromRedeclaring()) {
addClassRootMethods(ar, cls, redeclaringMethods);
continue;
}
// classes derived from system or extension classes can be complicated
ClassScopePtr root = cls->getRootParent(ar);
if (!root->isUserClass() || root->isExtensionClass()) continue;
// cluster virtual methods by a root parent that also defined the method
addClassRootMethods(ar, cls, methods);
}
}
// if ANY class in the hierarchy is a reclaring one, ignore
for (hphp_string_set::const_iterator iter = redeclaringMethods.begin();
iter != redeclaringMethods.end(); ++iter) {
methods.erase(*iter);
}
for (StringToFunctionScopePtrVecMap::const_iterator iter = methods.begin();
iter != methods.end(); ++iter) {
// if it's unique, ignore
const FunctionScopePtrVec &funcs = iter->second;
if (funcs.size() < 2) {
continue;
}
bool perfect = true;
for (unsigned int i = 1; i < funcs.size(); i++) {
if (!funcs[0]->matchParams(funcs[i])) {
perfect = false;
break;
}
}
if (perfect) {
for (unsigned int i = 0; i < funcs.size(); i++) {
funcs[i]->setPerfectVirtual();
}
}
}
}
void AnalysisResult::analyzeProgramFinal() {
AnalysisResultPtr ar = shared_from_this();
setPhase(AnalysisResult::AnalyzeFinal);
for (uint i = 0; i < m_fileScopes.size(); i++) {
m_fileScopes[i]->analyzeProgram(ar);
}
for (StringToClassScopePtrVecMap::iterator iter = m_classDecs.begin(),
end = m_classDecs.end(); iter != end; ++iter) {
for (ClassScopePtrVec::iterator it = iter->second.begin(),
e = iter->second.end(); it != e; ++it) {
ClassScopePtr cls = *it;
if (cls->isUserClass()) {
ClassStatementPtr clsStmt =
dynamic_pointer_cast<ClassStatement>(cls->getStmt());
bool needsCppCtor = false;
bool needsInit = false;
if (clsStmt) clsStmt->getCtorAndInitInfo(needsCppCtor, needsInit);
cls->setNeedsCppCtor(needsCppCtor);
cls->setNeedsInitMethod(needsInit);
}
}
}
// Keep generated code identical without randomness
canonicalizeSymbolOrder();
setPhase(AnalysisResult::CodeGen);
}
static void dumpVisitor(AnalysisResultPtr ar, StatementPtr s, void *data) {
s->dump(0, ar);
}
void AnalysisResult::dump() {
visitFiles(dumpVisitor, 0);
fflush(0);
}
void AnalysisResult::docJson(const string &filename) {
ofstream f(filename.c_str());
if (f.fail()) {
Logger::Error("Could not open file for writing doc JSON: %s",
filename.c_str());
return;
}
JSON::DocTarget::OutputStream out(f, shared_from_this());
JSON::DocTarget::MapStream ms(out);
ms.add("userland", m_fileScopes);
ClassScopePtrVec systemClasses;
systemClasses.reserve(m_systemClasses.size());
for (StringToClassScopePtrMap::iterator it = m_systemClasses.begin();
it != m_systemClasses.end(); ++it) {
systemClasses.push_back(it->second);
}
// just generate system classes for now
ms.add("system", systemClasses);
ms.done();
f.close();
}
void AnalysisResult::visitFiles(void (*cb)(AnalysisResultPtr,
StatementPtr, void*), void *data) {
AnalysisResultPtr ar = shared_from_this();
for (StringToFileScopePtrMap::const_iterator iter = m_files.begin();
iter != m_files.end(); ++iter) {
FileScopePtr file = iter->second;
file->visit(ar, cb, data);
}
}
void AnalysisResult::getScopesSet(BlockScopeRawPtrQueue &v) {
for (StringToFileScopePtrMap::const_iterator iter = m_files.begin();
iter != m_files.end(); ++iter) {
FileScopePtr file = iter->second;
file->getScopesSet(v);
}
}
///////////////////////////////////////////////////////////////////////////////
// optimization functions
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
template <typename When>
struct OptWorker;
template <typename When>
struct OptVisitor {
typedef OptVisitor<When> Visitor;
OptVisitor(AnalysisResultPtr ar, unsigned nscope) :
m_ar(ar), m_nscope(nscope), m_dispatcher(0) {
}
OptVisitor(const Visitor &po) : m_ar(po.m_ar),
m_nscope(po.m_nscope),
m_dispatcher(po.m_dispatcher) {
const_cast<Visitor&>(po).m_dispatcher = 0;
}
~OptVisitor() {
delete m_dispatcher;
}
void start() {
m_dispatcher->start();
}
void wait() {
m_dispatcher->waitEmpty(false);
}
void stop() {
m_dispatcher->waitEmpty();
}
int getQueuedJobs() {
return m_dispatcher->getQueuedJobs();
}
int getActiveWorker() {
return m_dispatcher->getActiveWorker();
}
AnalysisResultPtr m_ar;
unsigned m_nscope;
JobQueueDispatcher<BlockScope *, OptWorker<When> > *m_dispatcher;
};
template <typename When>
class OptWorker : public JobQueueWorker<BlockScope *, true, true> {
public:
OptWorker() {}
virtual void doJob(BlockScope *scope) {
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumDoJobCalls);
ConcurrentBlockScopeRawPtrIntHashMap::accessor acc;
AnalysisResult::s_DoJobUniqueScopes.insert(acc,
BlockScopeRawPtr(scope));
acc->second += 1;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
try {
DepthFirstVisitor<When, OptVisitor > *visitor =
(DepthFirstVisitor<When, OptVisitor >*)m_opaque;
{
Lock ldep(BlockScope::s_depsMutex);
Lock lstate(BlockScope::s_jobStateMutex);
assert(scope->getMark() == BlockScope::MarkReady);
if (scope->getNumDepsToWaitFor()) {
scope->setMark(BlockScope::MarkWaiting);
return;
}
scope->setMark(BlockScope::MarkProcessing);
}
scope->setForceRerun(false);
scope->setNeedsReschedule(false);
// creates on demand
AnalysisResult::s_changedScopesMapThreadLocal->clear();
int useKinds = visitor->visitScope(BlockScopeRawPtr(scope));
ASSERT(useKinds >= 0);
{
Lock l2(BlockScope::s_depsMutex);
Lock l1(BlockScope::s_jobStateMutex);
ASSERT(scope->getMark() == BlockScope::MarkProcessing);
ASSERT(scope->getNumDepsToWaitFor() == 0);
scope->assertNumDepsSanity();
// re-enqueue changed scopes, regardless of rescheduling exception.
// this is because we might have made changes to other scopes which we
// do not undo, so we need to announce their updates
BlockScopeRawPtrFlagsHashMap::const_iterator localIt =
AnalysisResult::s_changedScopesMapThreadLocal->begin();
BlockScopeRawPtrFlagsHashMap::const_iterator localEnd =
AnalysisResult::s_changedScopesMapThreadLocal->end();
for (; localIt != localEnd; ++localIt) {
const BlockScopeRawPtrFlagsVec &ordered =
localIt->first->getOrderedUsers();
for (BlockScopeRawPtrFlagsVec::const_iterator userIt =
ordered.begin(), userEnd = ordered.end();
userIt != userEnd; ++userIt) {
BlockScopeRawPtrFlagsVec::value_type pf = *userIt;
if ((pf->second & GetPhaseInterestMask<When>()) &&
(pf->second & localIt->second)) {
int m = pf->first->getMark();
switch (m) {
case BlockScope::MarkWaiting:
case BlockScope::MarkReady:
; // no-op
break;
case BlockScope::MarkProcessing:
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumForceRerunGlobal);
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
pf->first->setForceRerun(true);
break;
case BlockScope::MarkProcessed:
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumReactivateGlobal);
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
if (visitor->activateScope(pf->first)) {
visitor->enqueue(pf->first);
}
break;
default: ASSERT(false);
}
}
}
}
AnalysisResult::s_changedScopesMapThreadLocal.destroy();
if (scope->needsReschedule()) {
// This signals an error in visitScope() which the scope can possibly
// recover from if run again. an example is a lock contention error
// (where the scope had to bail out). thus, we simply want to
// re-enqueue it (w/o activating dependents, since this scope hasn't
// actually finished running)
scope->setRescheduleFlags(
scope->rescheduleFlags() | useKinds);
if (visitor->activateScope(BlockScopeRawPtr(scope))) {
visitor->enqueue(BlockScopeRawPtr(scope));
}
} else {
useKinds |= scope->rescheduleFlags();
scope->setRescheduleFlags(0);
const BlockScopeRawPtrFlagsVec &ordered = scope->getOrderedUsers();
for (BlockScopeRawPtrFlagsVec::const_iterator it = ordered.begin(),
end = ordered.end(); it != end; ++it) {
BlockScopeRawPtrFlagsVec::value_type pf = *it;
if (pf->second & GetPhaseInterestMask<When>()) {
int m = pf->first->getMark();
if (pf->second & useKinds && m == BlockScope::MarkProcessed) {
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumReactivateUseKinds);
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
bool ready = visitor->activateScope(pf->first);
assert(!ready);