Repository navigation
Expand file tree
/
Copy pathContext.cpp
More file actions
1195 lines (1025 loc) · 38.1 KB
/
Copy pathContext.cpp
File metadata and controls
1195 lines (1025 loc) · 38.1 KB
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
/*
* Copyright 2021-2023 Hewlett Packard Enterprise Development LP
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "chpl/framework/Context.h"
#include "chpl/framework/query-impl.h"
#include "chpl/framework/global-strings.h"
#include "chpl/parsing/parsing-queries.h"
#include "chpl/framework/stringify-functions.h"
#include "chpl/framework/ErrorWriter.h"
#include "chpl/framework/ErrorBase.h"
#include "chpl/framework/compiler-configuration.h"
#include "chpl/util/filesystem.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/FileSystem.h"
#include <chrono>
#include <fstream>
#include <iomanip>
#include <utility>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include "../util/my_aligned_alloc.h" // assumes size_t defined
namespace chpl {
namespace detail {
GlobalStrings globalStrings;
Context rootContext;
static void initGlobalStrings() {
#define X(field, str) globalStrings.field = UniqueString::get(&rootContext, str);
#include "chpl/framework/all-global-strings.h"
#undef X
}
} // namespace detail
using namespace chpl::querydetail;
void Context::Configuration::swap(Context::Configuration& other) {
std::swap(chplHome, other.chplHome);
std::swap(chplEnvOverrides, other.chplEnvOverrides);
std::swap(tmpDir, other.tmpDir);
std::swap(keepTmpDir, other.keepTmpDir);
std::swap(toolName, other.toolName);
}
void Context::setupGlobalStrings() {
if (this == &detail::rootContext) {
detail::initGlobalStrings();
for (auto& v : uniqueStringsTable) {
doNotCollectUniqueCString(v.str);
}
} else {
for (const auto& v : detail::rootContext.uniqueStringsTable) {
uniqueStringsTable.insert(v);
}
}
}
void Context::swap(Context& other) {
config_.swap(other.config_);
std::swap(handler_, other.handler_);
std::swap(computedChplEnv, other.computedChplEnv);
std::swap(chplEnv, other.chplEnv);
std::swap(detailedErrors, other.detailedErrors);
std::swap(uniqueStringsTable, other.uniqueStringsTable);
std::swap(queryDB, other.queryDB);
std::swap(modNameToFilepath, other.modNameToFilepath);
std::swap(queryStack, other.queryStack);
std::swap(ptrsMarkedThisRevision, other.ptrsMarkedThisRevision);
std::swap(ownedPtrsForThisRevision, other.ownedPtrsForThisRevision);
std::swap(currentRevisionNumber, other.currentRevisionNumber);
std::swap(checkStringsAlreadyMarked, other.checkStringsAlreadyMarked);
std::swap(enableDebugTrace, other.enableDebugTrace);
std::swap(enableQueryTiming, other.enableQueryTiming);
std::swap(enableQueryTimingTrace, other.enableQueryTimingTrace);
std::swap(currentTerminalSupportsColor_, other.currentTerminalSupportsColor_);
std::swap(breakSet, other.breakSet);
std::swap(breakOnHash, other.breakOnHash);
std::swap(numQueriesRunThisRevision_, other.numQueriesRunThisRevision_);
std::swap(queryTraceDepth, other.queryTraceDepth);
std::swap(queryTraceIgnoreQueries, other.queryTraceIgnoreQueries);
std::swap(queryDepthColor, other.queryDepthColor);
std::swap(queryTimingTraceOutput, other.queryTimingTraceOutput);
std::swap(lastPrepareToGCRevisionNumber, other.lastPrepareToGCRevisionNumber);
std::swap(gcCounter, other.gcCounter);
}
Context::Context() {
setupGlobalStrings();
}
Context::Context(Configuration config) {
// swap the configuration settings in to place
config_.swap(config);
setupGlobalStrings();
}
Context::Context(Context& consumeContext, Configuration newConfig) {
// swap all fields in to place from consumeContext
this->swap(consumeContext);
// set consumeContext not to delete the temp dir when it is deleted
// since this context will do so if that is needed.
consumeContext.config_.keepTmpDir = true;
// now set the new configuration information
config_.swap(newConfig);
}
Context::RunResultBase::RunResultBase() = default;
Context::RunResultBase::~RunResultBase() = default;
Context::RunResultBase::RunResultBase(const Context::RunResultBase& other) {
for (auto& err : other.errors()) {
errors_.push_back(err->clone());
}
}
bool Context::RunResultBase::ranWithoutErrors() const {
for (auto& error : errors_) {
auto kind = error->kind();
if (kind == ErrorBase::ERROR || kind == ErrorBase::SYNTAX) {
return false;
}
}
return true;
}
Context::ErrorCollectionEntry
Context::ErrorCollectionEntry::createForTrackingQuery(
std::vector<owned<ErrorBase>>* storeInto,
const QueryMapResultBase* trackingQuery) {
return Context::ErrorCollectionEntry(storeInto, trackingQuery);
}
Context::ErrorCollectionEntry
Context::ErrorCollectionEntry::createForRecomputing(
const querydetail::QueryMapResultBase* trackingQuery) {
return Context::ErrorCollectionEntry(nullptr, trackingQuery);
}
void Context::ErrorCollectionEntry::storeError(owned<ErrorBase> toStore) const {
if (storeInto_) {
storeInto_->push_back(std::move(toStore));
}
}
void Context::reportError(Context* context, const ErrorBase* err) {
handler_->report(context, err);
}
const std::string& Context::chplHome() const {
return config_.chplHome;
}
const std::string& Context::tmpDir() {
if (tmpDir_.empty()) {
if (!config_.tmpDir.empty()) {
// if a temp dir was configured, use that
tmpDir_ = config_.tmpDir;
} else {
// otherwise, generate a temp directory
std::string dir;
auto err = makeTempDir(config_.toolName + "-", dir);
if (err) {
this->error(Location(), "Could not create temp directory");
} else {
tmpDir_ = dir;
tmpDirExists_ = true;
}
}
}
if (!tmpDirExists_) {
auto err = llvm::sys::fs::create_directories(tmpDir_);
if (err) {
this->error(Location(), "Could not create temp directory %s",
tmpDir_.c_str());
} else {
tmpDirExists_ = true;
}
}
return tmpDir_;
}
bool Context::shouldSaveTmpDirFiles() const {
return config_.keepTmpDir;
}
std::string Context::tmpDirAnchorFile() {
std::string path = tmpDir();
if (!path.empty() && !tmpDirAnchorCreated_) {
path += "/anchor";
std::string data = "anchor\n";
std::error_code err = writeFile(path.c_str(), data);
if (err) {
this->error(Location(), "Could not update anchor file %s: %s",
path.c_str(), err.message().c_str());
} else {
tmpDirAnchorCreated_ = true;
}
}
return path;
}
void Context::cleanupTmpDirIfNeeded() {
if (!tmpDir_.empty() && fileExists(tmpDir_.c_str()) && !config_.keepTmpDir) {
// delete the tmp dir
deleteDir(tmpDir_);
}
}
void Context::setDetailedErrorOutput(bool detailedErrors) {
this->detailedErrors = detailedErrors;
}
UniqueString Context::adjustPathForErrorMsg(UniqueString path) {
const std::string& chpl_home = this->chplHome();
size_t chpl_home_len = chpl_home.length();
if (chpl_home_len > 0 && path.startsWith(chpl_home)) {
// replace a prefix of the value of CHPL_HOME with $CHPL_HOME
return UniqueString::getConcat(this, "$CHPL_HOME",
path.c_str()+chpl_home_len);
}
return path;
}
llvm::ErrorOr<const ChplEnvMap&> Context::getChplEnv() {
if (config_.chplHome.empty() || computedChplEnv) return chplEnv;
auto chplEnvResult = ::chpl::getChplEnv(config_.chplEnvOverrides,
config_.chplHome.c_str());
if (auto err = chplEnvResult.getError()) {
// forward error to caller
return err;
}
chplEnv = std::move(chplEnvResult.get());
computedChplEnv = true;
return chplEnv;
}
void Context::defaultReportError(Context* context, const ErrorBase* err) {
ErrorWriter ew(context, std::cerr,
context->detailedErrors ?
ErrorWriter::DETAILED :
ErrorWriter::BRIEF,
context->currentTerminalSupportsColor_);
err->write(ew);
if (context->detailedErrors) {
// Print an extra error separator
std::cerr << std::endl;
}
}
// unique'd strings are preceded by 4 bytes of length, gcMark and doNotCollectMark
// this number must be even
#define UNIQUED_STRING_METADATA_BYTES 6
#define UNIQUED_STRING_METADATA_LEN 4
Context::~Context() {
// free all the unique'd strings
for (auto& item: uniqueStringsTable) {
char* buf = (char*) item.str;
buf -= UNIQUED_STRING_METADATA_BYTES;
char doNotCollect = buf[UNIQUED_STRING_METADATA_LEN + 1];
// Root context : Free all strings
// Other contexts: Free all that aren't doNotCollect
if (this == &detail::rootContext || !doNotCollect) {
free(buf);
}
}
// delete the tmp dir
cleanupTmpDirIfNeeded();
}
#define ALIGN_DN(i, size) ((i) & ~((size) - 1))
#define ALIGN_UP(i, size) ALIGN_DN((i) + (size) - 1, size)
static char* allocateEvenAligned(size_t amt) {
char* buf = (char*) malloc(amt);
// UNIQUED_STRING_METADATA_BYTES must be even
static_assert((UNIQUED_STRING_METADATA_BYTES & 1) == 0, "UniquedString metadata bytes not even");
// Normally, malloc returns something that is aligned to 16 bytes,
// but it's technically possible that a platform library
// could not do so. So, here we check.
// We only need even alignment here.
if ((((uintptr_t)buf) & 1) != 0) {
free(buf);
// try again with an aligned allocation
size_t alignment = sizeof(void *);
size_t align_up_len = ALIGN_UP(amt, sizeof(void*));
buf = (char*) my_aligned_alloc(alignment, align_up_len);
}
CHPL_ASSERT(buf);
CHPL_ASSERT((((uintptr_t)buf) & 1) == 0);
return buf;
}
// Assumes buf starts with UNIQUED_STRING_METADATA_BYTES of metadata and has
// room for len and then a null terminator.
// Assumes that buf is allocated with even alignment
// Returns the pointer to where to copy the string and null terminator.
char* Context::setupStringMetadata(char* buf, size_t len) {
char gcMark = this->gcCounter & 0xff;
CHPL_ASSERT(len <= INT32_MAX);
int32_t len32 = len;
// these assert should fail if the below code needs to change
static_assert(sizeof(len32) + 2 == UNIQUED_STRING_METADATA_BYTES, "Size mismatch");
static_assert(sizeof(len32) == UNIQUED_STRING_METADATA_LEN, "Size mismatch");
// copy the length
memcpy(buf, &len32, sizeof(len32));
buf += sizeof(len32);
// set the GC mark
*buf = gcMark;
buf++;
// set the doNotCollectMark
*buf = 0;
buf++;
return buf;
}
// allocates new storage for the string if it was not found
const char* Context::getOrCreateUniqueString(const char* str, size_t len) {
chpl::detail::StringAndLength key = {str, len};
auto search = this->uniqueStringsTable.find(key);
if (search != this->uniqueStringsTable.end()) {
const char* ret = search->str;
// update the GC mark
this->markUniqueCString(ret);
return ret;
}
size_t allocLen = UNIQUED_STRING_METADATA_BYTES+len+1; // metadata, len, null
char* buf = allocateEvenAligned(allocLen);
// setup metadata
char* s = setupStringMetadata(buf, len);
// copy string data and null terminator
memcpy(s, str, len);
// null terminate
s[len] = 0x0;
// Add it to the table
chpl::detail::StringAndLength ret = {s, len};
this->uniqueStringsTable.insert(search, ret);
return s;
}
const char* Context::uniqueCString(const char* str, size_t len) {
if (len == 0 || str == nullptr) str = "";
return this->getOrCreateUniqueString(str, len);
}
const char* Context::uniqueCString(const char* str) {
if (str == nullptr) str = "";
return this->getOrCreateUniqueString(str, strlen(str));
}
const char* Context::uniqueCStringConcatLen(const char* s1, size_t len1,
const char* s2, size_t len2,
const char* s3, size_t len3,
const char* s4, size_t len4,
const char* s5, size_t len5,
const char* s6, size_t len6,
const char* s7, size_t len7,
const char* s8, size_t len8,
const char* s9, size_t len9) {
size_t len = len1 + len2 + len3 + len4 + len5 + len6 + len7 + len8 + len9;
size_t allocLen = UNIQUED_STRING_METADATA_BYTES+len+1; // metadata, len, null
char* buf = allocateEvenAligned(allocLen);
// setup metadata
char* s = setupStringMetadata(buf, len);
len = 0;
// copy each non-empty string
if (len1 > 0) {
memcpy(&s[len], s1, len1);
len += len1;
}
if (len2 > 0) {
memcpy(&s[len], s2, len2);
len += len2;
}
if (len3 > 0) {
memcpy(&s[len], s3, len3);
len += len3;
}
if (len4 > 0) {
memcpy(&s[len], s4, len4);
len += len4;
}
if (len5 > 0) {
memcpy(&s[len], s5, len5);
len += len5;
}
if (len6 > 0) {
memcpy(&s[len], s6, len6);
len += len6;
}
if (len7 > 0) {
memcpy(&s[len], s7, len7);
len += len7;
}
if (len8 > 0) {
memcpy(&s[len], s8, len8);
len += len8;
}
if (len9 > 0) {
memcpy(&s[len], s9, len9);
len += len9;
}
// null terminate
s[len] = '\0';
// Check for it in the table
chpl::detail::StringAndLength key = {s, len};
auto search = this->uniqueStringsTable.find(key);
if (search != this->uniqueStringsTable.end()) {
const char* ret = search->str;
// update the GC mark
this->markUniqueCString(ret);
free(buf);
return ret;
}
// Add it to the table
chpl::detail::StringAndLength ret = {s, len};
this->uniqueStringsTable.insert(search, ret);
return s;
}
const char* Context::uniqueCStringConcat(const char* s1,
const char* s2,
const char* s3,
const char* s4,
const char* s5,
const char* s6,
const char* s7,
const char* s8,
const char* s9) {
size_t len1 = 0;
size_t len2 = 0;
size_t len3 = 0;
size_t len4 = 0;
size_t len5 = 0;
size_t len6 = 0;
size_t len7 = 0;
size_t len8 = 0;
size_t len9 = 0;
if (s1 != nullptr) len1 = strlen(s1);
if (s2 != nullptr) len2 = strlen(s2);
if (s3 != nullptr) len3 = strlen(s3);
if (s4 != nullptr) len4 = strlen(s4);
if (s5 != nullptr) len5 = strlen(s5);
if (s6 != nullptr) len6 = strlen(s6);
if (s7 != nullptr) len7 = strlen(s7);
if (s8 != nullptr) len8 = strlen(s8);
if (s9 != nullptr) len9 = strlen(s9);
return uniqueCStringConcatLen(s1, len1, s2, len2,
s3, len3, s4, len4, s5, len5, s6, len6,
s7, len7, s8, len8, s9, len9);
}
void Context::markUniqueCString(const char* s) {
if (s == nullptr) {
return; // nothing to do
}
bool checkMarked = false;
bool doMark = (currentRevisionNumber == lastPrepareToGCRevisionNumber);
char gcMark = this->gcCounter & 0xff;
char* buf = (char*) s;
buf -= UNIQUED_STRING_METADATA_BYTES; // find start of metadata
buf += UNIQUED_STRING_METADATA_LEN; // pass the length
#ifndef NDEBUG
// assertions are enabled, so consider logic about
// whether or not current values should already be marked
checkMarked = checkStringsAlreadyMarked;
#endif
if (checkMarked) {
CHPL_ASSERT(buf[0] == gcMark && "string should already be marked");
}
// write the mark if needed
if (doMark) {
buf[0] = gcMark;
}
CHPL_ASSERT(0 <= buf[1] && buf[1] <= 1); // doNotCollectMark bit is 0 or 1
}
void Context::doNotCollectUniqueCString(const char* s) {
char* buf = (char*)s;
buf -= UNIQUED_STRING_METADATA_BYTES; // find start of metadata
buf += UNIQUED_STRING_METADATA_LEN; // pass the length
buf += 1; // pass the gc mark
*buf = 1; // set doNotCollectMark
}
size_t Context::lengthForUniqueString(const char* s) {
const char* buf = (char*) s;
buf -= UNIQUED_STRING_METADATA_BYTES; // find start of metadata
int32_t len32 = 0;
memcpy(&len32, buf, sizeof(len32));
CHPL_ASSERT(len32 >= 0);
return len32;
}
bool Context::shouldMarkUnownedPointer(const void* ptr) {
// don't bother for nullptr
if (ptr == nullptr)
return false;
// shouldn't run any mark code if the revision is not doing GC
CHPL_ASSERT(this->currentRevisionNumber == this->lastPrepareToGCRevisionNumber);
// check that the unowned pointer refers to an owned
// pointer that we have already marked
CHPL_ASSERT(ownedPtrsForThisRevision.count(ptr) != 0);
// add the pointer to the map
auto pair = ptrsMarkedThisRevision.insert(ptr);
// pair.second is 'true' if the insertion took place
// or 'false' if there already was an element
return pair.second;
}
bool Context::shouldMarkOwnedPointer(const void* ptr) {
// don't bother for nullptr
if (ptr == nullptr)
return false;
#ifndef NDEBUG
// note the pointer value for checking with markUnownedPointer
ownedPtrsForThisRevision.insert(ptr);
#endif
return true;
}
static
const UniqueString& filePathForModuleIdSymbolPathQuery(Context* context,
UniqueString modIdSymP) {
QUERY_BEGIN(filePathForModuleIdSymbolPathQuery, context, modIdSymP);
// return the empty string if it wasn't already set
// in setFilePathForModuleID.
UniqueString result;
return QUERY_END(result);
}
static bool symbolAndFilePathForID(Context* context, const ID& id,
UniqueString& symbolPathOut,
UniqueString& pathOut) {
UniqueString symbolPath = id.symbolPath();
while (!symbolPath.isEmpty()) {
auto tupleOfArgs = std::make_tuple(symbolPath);
bool got = context->hasCurrentResultForQuery(
filePathForModuleIdSymbolPathQuery, tupleOfArgs);
if (got) {
symbolPathOut = symbolPath;
pathOut = filePathForModuleIdSymbolPathQuery(context, symbolPath);
return true;
}
// remove the last path component, e.g. M.N -> M
symbolPath = ID::parentSymbolPath(context, symbolPath);
}
pathOut = UniqueString::get(context, "<unknown file path>");
return false;
}
bool Context::filePathForId(ID id, UniqueString& pathOut) {
UniqueString symbolPath;
return symbolAndFilePathForID(this, id, symbolPath, pathOut);
}
bool Context::filePathForId(ID id,
UniqueString& pathOut,
UniqueString& parentSymbolPathOut) {
UniqueString symbolPath;
bool got = symbolAndFilePathForID(this, id, symbolPath, pathOut);
if (got)
parentSymbolPathOut = ID::parentSymbolPath(this, symbolPath);
return got;
}
void Context::setFilePathForModuleId(ID moduleID, UniqueString path) {
UniqueString moduleIdSymbolPath = moduleID.symbolPath();
auto tupleOfArgs = std::make_tuple(moduleIdSymbolPath);
updateResultForQuery(filePathForModuleIdSymbolPathQuery,
tupleOfArgs, path,
"filePathForModuleIdSymbolPathQuery",
/* isInputQuery */ false,
/* forSetter */ true);
if (enableDebugTrace) {
printf("%i SETTING FILE PATH FOR MODULE %s -> %s\n", queryTraceDepth,
moduleIdSymbolPath.c_str(), path.c_str());
}
#ifndef NDEBUG
// check that querying the module ID works...
UniqueString gotPath;
bool ok = filePathForId(moduleID, gotPath);
CHPL_ASSERT(ok);
// ... and gives the same path
// Note: if this check causes problems in the future, it could
// be removed, or we could wire up setFileText used in tests
// to work with the LLVM VirtualFilesystem
#if LLVM_VERSION_MAJOR <= 11
llvm::SmallVector<char, 64> realPath, realGotPath;
#else
llvm::SmallVector<char> realPath, realGotPath;
#endif
std::error_code errPath;
std::error_code errGotPath;
errPath = llvm::sys::fs::real_path(path.str(), realPath);
errGotPath = llvm::sys::fs::real_path(gotPath.str(), realGotPath);
if (errPath || errGotPath) {
// ignore the check if there were errors
} else {
CHPL_ASSERT(realPath == realGotPath);
}
#endif
}
static
const UniqueString& pathHasLibraryQuery(Context* context,
UniqueString filePath) {
QUERY_BEGIN(pathHasLibraryQuery, context, filePath);
UniqueString result;
return QUERY_END(result);
}
bool Context::pathHasLibrary(const UniqueString& filePath,
UniqueString& pathOut) {
auto tupleOfArgs = std::make_tuple(filePath);
bool got = hasCurrentResultForQuery(pathHasLibraryQuery,
tupleOfArgs);
if (got) {
pathOut = pathHasLibraryQuery(this, filePath);
return true;
}
pathOut = UniqueString::get(this, "<unknown library path>");
return false;
}
void Context::setLibraryForFilePath(const UniqueString& filePath, const UniqueString& libPath) {
auto tupleOfArgs = std::make_tuple(filePath);
updateResultForQuery(pathHasLibraryQuery,
tupleOfArgs, libPath,
"pathHasLibraryQuery",
/* isInputQuery */ false,
/* forSetter */ true);
}
void Context::advanceToNextRevision(bool prepareToGC) {
this->currentRevisionNumber++;
this->numQueriesRunThisRevision_ = 0;
ptrsMarkedThisRevision.clear();
ownedPtrsForThisRevision.clear();
if (prepareToGC) {
this->lastPrepareToGCRevisionNumber = this->currentRevisionNumber;
gcCounter++;
}
if (enableDebugTrace) {
printf("%i CURRENT REVISION NUMBER IS NOW %i %s\n", queryTraceDepth,
(int) this->currentRevisionNumber,
prepareToGC?"PREPARING GC":"");
}
}
void Context::setDebugTraceFlag(bool enable) {
enableDebugTrace = enable;
}
void Context::setBreakOnHash(size_t hashVal) {
breakSet = true;
breakOnHash = hashVal;
}
void Context::collectGarbage() {
// if there are no parent queries, collect some garbage
CHPL_ASSERT(queryStack.size() == 0);
if (enableDebugTrace) {
printf("%i COLLECTING GARBAGE\n", queryTraceDepth);
}
// clear out the saved old results
// warning: this loop proceeds in a nondeterministic order
for (auto& dbEntry: queryDB) {
QueryMapBase* queryMapBase = dbEntry.second.get();
queryMapBase->clearOldResults(this->currentRevisionNumber);
}
if (this->lastPrepareToGCRevisionNumber == this->currentRevisionNumber) {
// remove UniqueStrings that have not been marked
size_t nUniqueStringsBefore = uniqueStringsTable.size();
// Performance: Would it be better to modify the table in-place
// rather than creating a new table as is done here?
char gcMark = this->gcCounter & 0xff;
UniqueStringsTableType newTable;
std::vector<char*> toFree;
// warning: this loop proceeds in a nondeterministic order
for (auto& e: uniqueStringsTable) {
const char* key = e.str;
char* buf = (char*)key;
buf -= UNIQUED_STRING_METADATA_BYTES; // find start of allocation
char* allocation = buf;
buf += UNIQUED_STRING_METADATA_LEN; // pass the length
// buf[1] is the doNotCollectMark
if (buf[1] || buf[0] == gcMark) {
newTable.insert(e);
if (enableDebugTrace) {
printf("%i COPYING OVER UNIQUESTRING %s\n", queryTraceDepth, key);
}
} else {
toFree.push_back(allocation);
if (enableDebugTrace) {
printf("%i WILL FREE UNIQUESTRING %s\n", queryTraceDepth, key);
}
}
}
for (char* allocation: toFree) {
free(allocation);
}
uniqueStringsTable.swap(newTable);
if (enableDebugTrace) {
size_t nUniqueStringsAfter = uniqueStringsTable.size();
printf("%i COLLECTED %i UniqueStrings\n", queryTraceDepth,
(int)(nUniqueStringsBefore-nUniqueStringsAfter));
}
}
}
void Context::report(owned<ErrorBase> error) {
gdbShouldBreakHere();
// If errorCollectionStack is not empty, errors are being collected, and
// thus not reported to the handler. Stash the error in the top (back) of the
// stack, but do not call `reportError`. Still store it into query
// results (errors will be re-emitted if the cached query is invoked without
// error collection).
if (queryStack.size() > 0 && errorCollectionStack.size() > 0) {
bool isSilencing =
errorCollectionStack.back().collectingQuery() == queryStack.back();
errorCollectionStack.back().storeError(error->clone());
queryStack.back()->errors.push_back(std::make_pair(std::move(error), isSilencing));
} else if (queryStack.size() > 0) {
bool isSilencing = false;
queryStack.back()->errors.push_back(std::make_pair(std::move(error), isSilencing));
reportError(this, queryStack.back()->errors.back().first.get());
} else if (errorCollectionStack.size() > 0) {
errorCollectionStack.back().storeError(std::move(error));
} else {
reportError(this, error.get());
}
}
static void logErrorInContext(Context* context,
ErrorBase::Kind kind,
Location loc,
const char* fmt,
va_list vl) {
auto err = GeneralError::vbuild(kind, loc, fmt, vl);
context->report(std::move(err));
}
static void logErrorInContext(Context* context,
ErrorBase::Kind kind,
ID id,
const char* fmt,
va_list vl) {
auto err = GeneralError::vbuild(kind, id, fmt, vl);
context->report(std::move(err));
}
static void logErrorInContext(Context* context,
ErrorBase::Kind kind,
const uast::AstNode* ast,
const char* fmt,
va_list vl) {
auto err = GeneralError::vbuild(kind, ast->id(), fmt, vl);
context->report(std::move(err));
}
#define CHPL_CONTEXT_LOG_ERROR_HELPER(context__, kind__, pin__, fmt__) \
do { \
va_list vl; \
va_start(vl, fmt__); \
logErrorInContext(context__, kind__, pin__, fmt__, vl); \
va_end(vl); \
} while (0)
// TODO: Similar overloads for NOTE, WARN, etc.
void Context::error(Location loc, const char* fmt, ...) {
CHPL_CONTEXT_LOG_ERROR_HELPER(this, ErrorBase::ERROR, loc, fmt);
}
void Context::error(ID id, const char* fmt, ...) {
CHPL_CONTEXT_LOG_ERROR_HELPER(this, ErrorBase::ERROR, id, fmt);
}
void Context::error(const uast::AstNode* ast, const char* fmt, ...) {
CHPL_CONTEXT_LOG_ERROR_HELPER(this, ErrorBase::ERROR, ast, fmt);
}
void Context::error(const resolution::TypedFnSignature* inFn,
const uast::AstNode* ast,
const char* fmt, ...) {
CHPL_CONTEXT_LOG_ERROR_HELPER(this, ErrorBase::ERROR, ast, fmt);
// TODO: add note about instantiation & POI stack
}
#undef CHPL_CONTEXT_LOG_ERROR_HELPER
void Context::recomputeIfNeeded(const QueryMapResultBase* resultEntry) {
//if (enableDebugTrace) {
// printf("RECOMPUTING IF NEEDED FOR %p %s\n", resultEntry,
// resultEntry->parentQueryMap->queryName);
//}
if (this->currentRevisionNumber == resultEntry->lastChecked) {
// No need to check the dependencies again.
// We already know that we can reuse the result.
return;
}
if (resultEntry->parentQueryMap->isInputQuery) {
// For an input query, compute it once per revision, ignoring
// dependencies (e.g. if it is reading a file, we need to check that the
// file has not changed.)
auto marker = markRecomputing(true);
resultEntry->recompute(this);
CHPL_ASSERT(resultEntry->lastChecked == this->currentRevisionNumber);
return;
}
// Otherwise, check the dependencies. Have any of them
// changed since the last revision in which we computed this?
// If so, compute it again.
bool useSaved = true;
for (auto& dependency : resultEntry->dependencies) {
const QueryMapResultBase* dependencyQuery = dependency.query;
if (dependencyQuery->lastChanged > resultEntry->lastChanged) {
useSaved = false;
break;
} else if (this->currentRevisionNumber == dependencyQuery->lastChecked) {
// No need to check the dependency again; already did, and it was OK
} else {
if (dependency.errorCollectionRoot) {
errorCollectionStack.push_back(
ErrorCollectionEntry::createForRecomputing(resultEntry));
}
recomputeIfNeeded(dependencyQuery);
if (dependency.errorCollectionRoot) {
errorCollectionStack.pop_back();
}
// we might have recomputed the dependency, so check its lastChanged
if (dependencyQuery->lastChanged > resultEntry->lastChanged) {
useSaved = false;
break;
}
}
}
if (useSaved == false) {
auto marker = markRecomputing(true);
resultEntry->recompute(this);
CHPL_ASSERT(resultEntry->lastChecked == this->currentRevisionNumber);
if (enableDebugTrace) {
printf("%i DONE RECOMPUTING IF NEEDED -- RECOMPUTED FOR %s\n",
queryTraceDepth,
resultEntry->parentQueryMap->queryName);
}
return;
} else {
updateForReuse(resultEntry);
if (enableDebugTrace) {
printf("%i DONE RECOMPUTING IF NEEDED -- REUSED FOR %s\n",
queryTraceDepth,
resultEntry->parentQueryMap->queryName);
}
}
}
// this should be called once each revision the first time
// the result is reused. It sets lastChecked = currentRevisionNumber
// and takes some steps to support garbage collection.
void Context::updateForReuse(const QueryMapResultBase* resultEntry) {
// if we are GC'ing, mark unique strings
if (this->currentRevisionNumber == this->lastPrepareToGCRevisionNumber) {
resultEntry->markUniqueStringsInResult(this);
// and also mark unique strings in the errors
}
resultEntry->lastChecked = this->currentRevisionNumber;
resultEntry->emittedErrors = errorCollectionStack.empty();
// Update error locations if needed and re-report the error
// Only re-report errors if they are not being silenced.
if (errorCollectionStack.empty()) {
for (auto& err: resultEntry->errors) {
if (!err.second) {
// Only report an error if it wasn't silenced in the original run
reportError(this, err.first.get());
}
}
}
}
bool Context::queryCanUseSavedResult(
const void* queryFunction,
const QueryMapResultBase* resultEntry) {
bool useSaved = false;
CHPL_ASSERT(resultEntry != nullptr);
if (resultEntry->lastChanged == -1) {
// If it is a new entry, we can't reuse it
useSaved = false;
} else if (this->currentRevisionNumber == resultEntry->lastChecked) {
// the query was already checked/run in this revision
useSaved = true;
} else if (resultEntry->parentQueryMap->isInputQuery) {
// be sure to re-run input queries
useSaved = false;
} else {
useSaved = true;
for (auto& dependency: resultEntry->dependencies) {
const QueryMapResultBase* dependencyQuery = dependency.query;
if (dependency.errorCollectionRoot) {
errorCollectionStack.push_back(
ErrorCollectionEntry::createForRecomputing(resultEntry));
}
recomputeIfNeeded(dependencyQuery);
if (dependency.errorCollectionRoot) {
errorCollectionStack.pop_back();
}