1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
18 #define ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
19
20 #include <array>
21 #include <list>
22 #include <set>
23 #include <string_view>
24 #include <vector>
25
26 #include "base/arena_containers.h"
27 #include "base/arena_object.h"
28 #include "base/array_ref.h"
29 #include "base/atomic.h"
30 #include "base/bit_memory_region.h"
31 #include "base/hash_map.h"
32 #include "base/hash_set.h"
33 #include "base/malloc_arena_pool.h"
34 #include "base/mem_map.h"
35 #include "base/safe_map.h"
36 #include "dex/dex_file.h"
37 #include "dex/dex_file_types.h"
38 #include "dex/method_reference.h"
39 #include "dex/type_reference.h"
40
41 namespace art {
42
43 /**
44 * Convenient class to pass around profile information (including inline caches)
45 * without the need to hold GC-able objects.
46 */
47 struct ProfileMethodInfo {
48 struct ProfileInlineCache {
49 ProfileInlineCache(uint32_t pc,
50 bool missing_types,
51 const std::vector<TypeReference>& profile_classes,
52 // Only used by profman for creating profiles from text
53 bool megamorphic = false)
dex_pcProfileMethodInfo::ProfileInlineCache54 : dex_pc(pc),
55 is_missing_types(missing_types),
56 classes(profile_classes),
57 is_megamorphic(megamorphic) {}
58
59 const uint32_t dex_pc;
60 const bool is_missing_types;
61 // TODO: Replace `TypeReference` with `dex::TypeIndex` and allow artificial
62 // type indexes for types without a `dex::TypeId` in any dex file processed
63 // by the profman. See `ProfileCompilationInfo::FindOrCreateTypeIndex()`.
64 const std::vector<TypeReference> classes;
65 const bool is_megamorphic;
66 };
67
ProfileMethodInfoProfileMethodInfo68 explicit ProfileMethodInfo(MethodReference reference) : ref(reference) {}
69
ProfileMethodInfoProfileMethodInfo70 ProfileMethodInfo(MethodReference reference, const std::vector<ProfileInlineCache>& caches)
71 : ref(reference),
72 inline_caches(caches) {}
73
74 MethodReference ref;
75 std::vector<ProfileInlineCache> inline_caches;
76 };
77
78 class FlattenProfileData;
79
80 /**
81 * Profile information in a format suitable to be queried by the compiler and
82 * performing profile guided compilation.
83 * It is a serialize-friendly format based on information collected by the
84 * interpreter (ProfileInfo).
85 * Currently it stores only the hot compiled methods.
86 */
87 class ProfileCompilationInfo {
88 public:
89 static const uint8_t kProfileMagic[];
90 static const uint8_t kProfileVersion[];
91 static const uint8_t kProfileVersionForBootImage[];
92 static const char kDexMetadataProfileEntry[];
93
94 static constexpr size_t kProfileVersionSize = 4;
95 static constexpr uint8_t kIndividualInlineCacheSize = 5;
96
97 // Data structures for encoding the offline representation of inline caches.
98 // This is exposed as public in order to make it available to dex2oat compilations
99 // (see compiler/optimizing/inliner.cc).
100
101 // The type used to manipulate the profile index of dex files.
102 // It sets an upper limit to how many dex files a given profile can record.
103 using ProfileIndexType = uint16_t;
104
105 // Encodes a class reference in the profile.
106 // The owning dex file is encoded as the index (dex_profile_index) it has in the
107 // profile rather than as a full reference (location, checksum).
108 // This avoids excessive string copying when managing the profile data.
109 // The dex_profile_index is an index in the `DexFileData::profile_index` (internal use)
110 // and a matching dex file can found with `FindDexFileForProfileIndex()`.
111 // Note that the dex_profile_index is not necessary the multidex index.
112 // We cannot rely on the actual multidex index because a single profile may store
113 // data from multiple splits. This means that a profile may contain a classes2.dex from split-A
114 // and one from split-B.
115 struct ClassReference : public ValueObject {
ClassReferenceClassReference116 ClassReference(ProfileIndexType dex_profile_idx, const dex::TypeIndex type_idx) :
117 dex_profile_index(dex_profile_idx), type_index(type_idx) {}
118
119 bool operator==(const ClassReference& other) const {
120 return dex_profile_index == other.dex_profile_index && type_index == other.type_index;
121 }
122 bool operator<(const ClassReference& other) const {
123 return dex_profile_index == other.dex_profile_index
124 ? type_index < other.type_index
125 : dex_profile_index < other.dex_profile_index;
126 }
127
128 ProfileIndexType dex_profile_index; // the index of the owning dex in the profile info
129 dex::TypeIndex type_index; // the type index of the class
130 };
131
132 // Encodes the actual inline cache for a given dex pc (whether or not the receiver is
133 // megamorphic and its possible types).
134 // If the receiver is megamorphic or is missing types the set of classes will be empty.
135 struct DexPcData : public ArenaObject<kArenaAllocProfile> {
DexPcDataDexPcData136 explicit DexPcData(ArenaAllocator* allocator)
137 : DexPcData(allocator->Adapter(kArenaAllocProfile)) {}
DexPcDataDexPcData138 explicit DexPcData(const ArenaAllocatorAdapter<void>& allocator)
139 : is_missing_types(false),
140 is_megamorphic(false),
141 classes(std::less<dex::TypeIndex>(), allocator) {}
142 void AddClass(const dex::TypeIndex& type_idx);
SetIsMegamorphicDexPcData143 void SetIsMegamorphic() {
144 if (is_missing_types) return;
145 is_megamorphic = true;
146 classes.clear();
147 }
SetIsMissingTypesDexPcData148 void SetIsMissingTypes() {
149 is_megamorphic = false;
150 is_missing_types = true;
151 classes.clear();
152 }
153 bool operator==(const DexPcData& other) const {
154 return is_megamorphic == other.is_megamorphic &&
155 is_missing_types == other.is_missing_types &&
156 classes == other.classes;
157 }
158
159 // Not all runtime types can be encoded in the profile. For example if the receiver
160 // type is in a dex file which is not tracked for profiling its type cannot be
161 // encoded. When types are missing this field will be set to true.
162 bool is_missing_types;
163 bool is_megamorphic;
164 ArenaSet<dex::TypeIndex> classes;
165 };
166
167 // The inline cache map: DexPc -> DexPcData.
168 using InlineCacheMap = ArenaSafeMap<uint16_t, DexPcData>;
169
170 // Maps a method dex index to its inline cache.
171 using MethodMap = ArenaSafeMap<uint16_t, InlineCacheMap>;
172
173 // Profile method hotness information for a single method. Also includes a pointer to the inline
174 // cache map.
175 class MethodHotness {
176 public:
177 enum Flag {
178 // Marker flag used to simplify iterations.
179 kFlagFirst = 1 << 0,
180 // The method is profile-hot (this is implementation specific, e.g. equivalent to JIT-warm)
181 kFlagHot = 1 << 0,
182 // Executed during the app startup as determined by the runtime.
183 kFlagStartup = 1 << 1,
184 // Executed after app startup as determined by the runtime.
185 kFlagPostStartup = 1 << 2,
186 // Marker flag used to simplify iterations.
187 kFlagLastRegular = 1 << 2,
188 // Executed by a 32bit process.
189 kFlag32bit = 1 << 3,
190 // Executed by a 64bit process.
191 kFlag64bit = 1 << 4,
192 // Executed on sensitive thread (e.g. UI).
193 kFlagSensitiveThread = 1 << 5,
194 // Executed during the app startup as determined by the framework (equivalent to am start).
195 kFlagAmStartup = 1 << 6,
196 // Executed after the app startup as determined by the framework (equivalent to am start).
197 kFlagAmPostStartup = 1 << 7,
198 // Executed during system boot.
199 kFlagBoot = 1 << 8,
200 // Executed after the system has booted.
201 kFlagPostBoot = 1 << 9,
202
203 // The startup bins captured the relative order of when a method become hot. There are 6
204 // total bins supported and each hot method will have at least one bit set. If the profile was
205 // merged multiple times more than one bit may be set as a given method may become hot at
206 // various times during subsequent executions.
207 // The granularity of the bins is unspecified (i.e. the runtime is free to change the
208 // values it uses - this may be 100ms, 200ms etc...).
209 kFlagStartupBin = 1 << 10,
210 kFlagStartupMaxBin = 1 << 15,
211 // Marker flag used to simplify iterations.
212 kFlagLastBoot = 1 << 15,
213 };
214
IsHot()215 bool IsHot() const {
216 return (flags_ & kFlagHot) != 0;
217 }
218
IsStartup()219 bool IsStartup() const {
220 return (flags_ & kFlagStartup) != 0;
221 }
222
IsPostStartup()223 bool IsPostStartup() const {
224 return (flags_ & kFlagPostStartup) != 0;
225 }
226
AddFlag(Flag flag)227 void AddFlag(Flag flag) {
228 flags_ |= flag;
229 }
230
GetFlags()231 uint32_t GetFlags() const {
232 return flags_;
233 }
234
HasFlagSet(MethodHotness::Flag flag)235 bool HasFlagSet(MethodHotness::Flag flag) {
236 return (flags_ & flag ) != 0;
237 }
238
IsInProfile()239 bool IsInProfile() const {
240 return flags_ != 0;
241 }
242
GetInlineCacheMap()243 const InlineCacheMap* GetInlineCacheMap() const {
244 return inline_cache_map_;
245 }
246
247 private:
248 const InlineCacheMap* inline_cache_map_ = nullptr;
249 uint32_t flags_ = 0;
250
SetInlineCacheMap(const InlineCacheMap * info)251 void SetInlineCacheMap(const InlineCacheMap* info) {
252 inline_cache_map_ = info;
253 }
254
255 friend class ProfileCompilationInfo;
256 };
257
258 // Encapsulates metadata that can be associated with the methods and classes added to the profile.
259 // The additional metadata is serialized in the profile and becomes part of the profile key
260 // representation. It can be used to differentiate the samples that are added to the profile
261 // based on the supported criteria (e.g. keep track of which app generated what sample when
262 // constructing a boot profile.).
263 class ProfileSampleAnnotation {
264 public:
ProfileSampleAnnotation(const std::string & package_name)265 explicit ProfileSampleAnnotation(const std::string& package_name) :
266 origin_package_name_(package_name) {}
267
GetOriginPackageName()268 const std::string& GetOriginPackageName() const { return origin_package_name_; }
269
270 bool operator==(const ProfileSampleAnnotation& other) const {
271 return origin_package_name_ == other.origin_package_name_;
272 }
273
274 bool operator<(const ProfileSampleAnnotation& other) const {
275 return origin_package_name_ < other.origin_package_name_;
276 }
277
278 // A convenient empty annotation object that can be used to denote that no annotation should
279 // be associated with the profile samples.
280 static const ProfileSampleAnnotation kNone;
281
282 private:
283 // The name of the package that generated the samples.
284 const std::string origin_package_name_;
285 };
286
287 // Helper class for printing referenced dex file information to a stream.
288 struct DexReferenceDumper;
289
290 // Public methods to create, extend or query the profile.
291 ProfileCompilationInfo();
292 explicit ProfileCompilationInfo(bool for_boot_image);
293 explicit ProfileCompilationInfo(ArenaPool* arena_pool);
294 ProfileCompilationInfo(ArenaPool* arena_pool, bool for_boot_image);
295
296 ~ProfileCompilationInfo();
297
298 // Returns the maximum value for the profile index.
MaxProfileIndex()299 static constexpr ProfileIndexType MaxProfileIndex() {
300 return std::numeric_limits<ProfileIndexType>::max();
301 }
302
303 // Find a tracked dex file. Returns `MaxProfileIndex()` on failure, whether due to no records
304 // for the dex location or profile key, or checksum/num_type_ids/num_method_ids mismatch.
305 ProfileIndexType FindDexFile(
306 const DexFile& dex_file,
307 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const {
308 const DexFileData* data = FindDexDataUsingAnnotations(&dex_file, annotation);
309 return (data != nullptr) ? data->profile_index : MaxProfileIndex();
310 }
311
312 // Find or add a tracked dex file. Returns `MaxProfileIndex()` on failure, whether due to
313 // checksum/num_type_ids/num_method_ids mismatch or reaching the maximum number of dex files.
314 ProfileIndexType FindOrAddDexFile(
315 const DexFile& dex_file,
316 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
317 DexFileData* data = GetOrAddDexFileData(&dex_file, annotation);
318 return (data != nullptr) ? data->profile_index : MaxProfileIndex();
319 }
320
321 // Add the given methods to the current profile object.
322 //
323 // Note: if an annotation is provided, the methods/classes will be associated with the group
324 // (dex_file, sample_annotation). Each group keeps its unique set of methods/classes.
325 bool AddMethods(const std::vector<ProfileMethodInfo>& methods,
326 MethodHotness::Flag flags,
327 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
328
329 // Find a type index in the `dex_file` if there is a `TypeId` for it. Otherwise,
330 // find or insert the descriptor in "extra descriptors" and return an artificial
331 // type index beyond `dex_file.NumTypeIds()`. This fails if the artificial index
332 // would be kDexNoIndex16 (0xffffu) or higher, returning an invalid type index.
333 // The returned type index can be used, if valid, for `AddClass()` or (TODO) as
334 // a type index for inline caches.
335 dex::TypeIndex FindOrCreateTypeIndex(const DexFile& dex_file, TypeReference class_ref);
336 dex::TypeIndex FindOrCreateTypeIndex(const DexFile& dex_file, const char* descriptor);
337
338 // Add a class with the specified `type_index` to the profile. The `type_index`
339 // can be either a normal index for a `TypeId` in the dex file, or an artificial
340 // type index created by `FindOrCreateTypeIndex()`.
AddClass(ProfileIndexType profile_index,dex::TypeIndex type_index)341 void AddClass(ProfileIndexType profile_index, dex::TypeIndex type_index) {
342 DCHECK_LT(profile_index, info_.size());
343 DexFileData* const data = info_[profile_index].get();
344 DCHECK(type_index.IsValid());
345 DCHECK(type_index.index_ <= data->num_type_ids ||
346 type_index.index_ - data->num_type_ids < extra_descriptors_.size());
347 data->class_set.insert(type_index);
348 }
349
350 // Add a class with the specified `type_index` to the profile. The `type_index`
351 // can be either a normal index for a `TypeId` in the dex file, or an artificial
352 // type index created by `FindOrCreateTypeIndex()`.
353 // Returns `true` on success, `false` on failure.
354 bool AddClass(const DexFile& dex_file,
355 dex::TypeIndex type_index,
356 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
357 DCHECK(type_index.IsValid());
358 DCHECK(type_index.index_ <= dex_file.NumTypeIds() ||
359 type_index.index_ - dex_file.NumTypeIds() < extra_descriptors_.size());
360 DexFileData* const data = GetOrAddDexFileData(&dex_file, annotation);
361 if (data == nullptr) { // Checksum/num_type_ids/num_method_ids mismatch or too many dex files.
362 return false;
363 }
364 data->class_set.insert(type_index);
365 return true;
366 }
367
368 // Add a class with the specified `descriptor` to the profile.
369 // Returns `true` on success, `false` on failure.
370 bool AddClass(const DexFile& dex_file,
371 const char* descriptor,
372 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
373 bool AddClass(const DexFile& dex_file,
374 const std::string& descriptor,
375 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
376 return AddClass(dex_file, descriptor.c_str(), annotation);
377 }
378 bool AddClass(const DexFile& dex_file,
379 std::string_view descriptor,
380 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
381 return AddClass(dex_file, std::string(descriptor).c_str(), annotation);
382 }
383
384 // Add multiple type ids for classes in a single dex file. Iterator is for type_ids not
385 // class_defs.
386 //
387 // Note: see AddMethods docs for the handling of annotations.
388 template <class Iterator>
389 bool AddClassesForDex(
390 const DexFile* dex_file,
391 Iterator index_begin,
392 Iterator index_end,
393 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
394 DexFileData* data = GetOrAddDexFileData(dex_file, annotation);
395 if (data == nullptr) {
396 return false;
397 }
398 data->class_set.insert(index_begin, index_end);
399 return true;
400 }
401
AddMethod(ProfileIndexType profile_index,uint32_t method_index,MethodHotness::Flag flags)402 void AddMethod(ProfileIndexType profile_index, uint32_t method_index, MethodHotness::Flag flags) {
403 DCHECK_LT(profile_index, info_.size());
404 DexFileData* const data = info_[profile_index].get();
405 DCHECK_LT(method_index, data->num_method_ids);
406 data->AddMethod(flags, method_index);
407 }
408
409 // Add a method to the profile using its online representation (containing runtime structures).
410 //
411 // Note: see AddMethods docs for the handling of annotations.
412 bool AddMethod(const ProfileMethodInfo& pmi,
413 MethodHotness::Flag flags,
414 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
415
416 // Bulk add sampled methods and/or hot methods for a single dex, fast since it only has one
417 // GetOrAddDexFileData call.
418 //
419 // Note: see AddMethods docs for the handling of annotations.
420 template <class Iterator>
421 bool AddMethodsForDex(
422 MethodHotness::Flag flags,
423 const DexFile* dex_file,
424 Iterator index_begin,
425 Iterator index_end,
426 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
427 DexFileData* data = GetOrAddDexFileData(dex_file, annotation);
428 if (data == nullptr) {
429 return false;
430 }
431 for (Iterator it = index_begin; it != index_end; ++it) {
432 DCHECK_LT(*it, data->num_method_ids);
433 if (!data->AddMethod(flags, *it)) {
434 return false;
435 }
436 }
437 return true;
438 }
439
440 // Load or Merge profile information from the given file descriptor.
441 // If the current profile is non-empty the load will fail.
442 // If merge_classes is set to false, classes will not be merged/loaded.
443 // If filter_fn is present, it will be used to filter out profile data belonging
444 // to dex file which do not comply with the filter
445 // (i.e. for which filter_fn(dex_location, dex_checksum) is false).
446 using ProfileLoadFilterFn = std::function<bool(const std::string&, uint32_t)>;
447 // Profile filter method which accepts all dex locations.
448 // This is convenient to use when we need to accept all locations without repeating the same
449 // lambda.
450 static bool ProfileFilterFnAcceptAll(const std::string& dex_location, uint32_t checksum);
451
452 bool Load(
453 int fd,
454 bool merge_classes = true,
455 const ProfileLoadFilterFn& filter_fn = ProfileFilterFnAcceptAll);
456
457 // Verify integrity of the profile file with the provided dex files.
458 // If there exists a DexData object which maps to a dex_file, then it verifies that:
459 // - The checksums of the DexData and dex_file are equals.
460 // - No method id exceeds NumMethodIds corresponding to the dex_file.
461 // - No class id exceeds NumTypeIds corresponding to the dex_file.
462 // - For every inline_caches, class_ids does not exceed NumTypeIds corresponding to
463 // the dex_file they are in.
464 bool VerifyProfileData(const std::vector<const DexFile*>& dex_files);
465
466 // Loads profile information from the given file.
467 // Returns true on success, false otherwise.
468 // If the current profile is non-empty the load will fail.
469 // If clear_if_invalid is true:
470 // - If the file is invalid, the method clears the file and returns true.
471 // - If the file doesn't exist, the method returns true.
472 bool Load(const std::string& filename, bool clear_if_invalid);
473
474 // Merge the data from another ProfileCompilationInfo into the current object. Only merges
475 // classes if merge_classes is true. This is used for creating the boot profile since
476 // we don't want all of the classes to be image classes.
477 bool MergeWith(const ProfileCompilationInfo& info, bool merge_classes = true);
478
479 // Merge profile information from the given file descriptor.
480 bool MergeWith(const std::string& filename);
481
482 // Save the profile data to the given file descriptor.
483 bool Save(int fd);
484
485 // Save the current profile into the given file. Overwrites any existing data.
486 bool Save(const std::string& filename, uint64_t* bytes_written);
487
488 // A fallback implementation of `Save` that uses a flock.
489 bool SaveFallback(const std::string& filename, uint64_t* bytes_written);
490
491 // Return the number of dex files referenced in the profile.
GetNumberOfDexFiles()492 size_t GetNumberOfDexFiles() const {
493 return info_.size();
494 }
495
496 // Return the number of methods that were profiled.
497 uint32_t GetNumberOfMethods() const;
498
499 // Return the number of resolved classes that were profiled.
500 uint32_t GetNumberOfResolvedClasses() const;
501
502 // Returns whether the referenced method is a startup method.
IsStartupMethod(ProfileIndexType profile_index,uint32_t method_index)503 bool IsStartupMethod(ProfileIndexType profile_index, uint32_t method_index) const {
504 return info_[profile_index]->IsStartupMethod(method_index);
505 }
506
507 // Returns whether the referenced method is a post-startup method.
IsPostStartupMethod(ProfileIndexType profile_index,uint32_t method_index)508 bool IsPostStartupMethod(ProfileIndexType profile_index, uint32_t method_index) const {
509 return info_[profile_index]->IsPostStartupMethod(method_index);
510 }
511
512 // Returns whether the referenced method is hot.
IsHotMethod(ProfileIndexType profile_index,uint32_t method_index)513 bool IsHotMethod(ProfileIndexType profile_index, uint32_t method_index) const {
514 return info_[profile_index]->IsHotMethod(method_index);
515 }
516
517 // Returns whether the referenced method is in the profile (with any hotness flag).
IsMethodInProfile(ProfileIndexType profile_index,uint32_t method_index)518 bool IsMethodInProfile(ProfileIndexType profile_index, uint32_t method_index) const {
519 DCHECK_LT(profile_index, info_.size());
520 const DexFileData* const data = info_[profile_index].get();
521 return data->IsMethodInProfile(method_index);
522 }
523
524 // Returns the profile method info for a given method reference.
525 //
526 // Note that if the profile was built with annotations, the same dex file may be
527 // represented multiple times in the profile (due to different annotation associated with it).
528 // If so, and if no annotation is passed to this method, then only the first dex file is searched.
529 //
530 // Implementation details: It is suitable to pass kNone for regular profile guided compilation
531 // because during compilation we generally don't care about annotations. The metadata is
532 // useful for boot profiles which need the extra information.
533 MethodHotness GetMethodHotness(
534 const MethodReference& method_ref,
535 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
536
537 // Return true if the class's type is present in the profiling info.
ContainsClass(ProfileIndexType profile_index,dex::TypeIndex type_index)538 bool ContainsClass(ProfileIndexType profile_index, dex::TypeIndex type_index) const {
539 DCHECK_LT(profile_index, info_.size());
540 const DexFileData* const data = info_[profile_index].get();
541 DCHECK(type_index.IsValid());
542 DCHECK(type_index.index_ <= data->num_type_ids ||
543 type_index.index_ - data->num_type_ids < extra_descriptors_.size());
544 return data->class_set.find(type_index) != data->class_set.end();
545 }
546
547 // Return true if the class's type is present in the profiling info.
548 //
549 // Note: see GetMethodHotness docs for the handling of annotations.
550 bool ContainsClass(
551 const DexFile& dex_file,
552 dex::TypeIndex type_idx,
553 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
554
555 // Return the dex file for the given `profile_index`, or null if none of the provided
556 // dex files has a matching checksum and a location with the same base key.
557 template <typename Container>
FindDexFileForProfileIndex(ProfileIndexType profile_index,const Container & dex_files)558 const DexFile* FindDexFileForProfileIndex(ProfileIndexType profile_index,
559 const Container& dex_files) const {
560 static_assert(std::is_same_v<typename Container::value_type, const DexFile*> ||
561 std::is_same_v<typename Container::value_type, std::unique_ptr<const DexFile>>);
562 DCHECK_LE(profile_index, info_.size());
563 const DexFileData* dex_file_data = info_[profile_index].get();
564 DCHECK(dex_file_data != nullptr);
565 uint32_t dex_checksum = dex_file_data->checksum;
566 std::string_view base_key = GetBaseKeyViewFromAugmentedKey(dex_file_data->profile_key);
567 for (const auto& dex_file : dex_files) {
568 if (dex_checksum == dex_file->GetLocationChecksum() &&
569 base_key == GetProfileDexFileBaseKeyView(dex_file->GetLocation())) {
570 return std::addressof(*dex_file);
571 }
572 }
573 return nullptr;
574 }
575
576 DexReferenceDumper DumpDexReference(ProfileIndexType profile_index) const;
577
578 // Dump all the loaded profile info into a string and returns it.
579 // If dex_files is not empty then the method indices will be resolved to their
580 // names.
581 // This is intended for testing and debugging.
582 std::string DumpInfo(const std::vector<const DexFile*>& dex_files,
583 bool print_full_dex_location = true) const;
584
585 // Return the classes and methods for a given dex file through out args. The out args are the set
586 // of class as well as the methods and their associated inline caches. Returns true if the dex
587 // file is register and has a matching checksum, false otherwise.
588 //
589 // Note: see GetMethodHotness docs for the handling of annotations.
590 bool GetClassesAndMethods(
591 const DexFile& dex_file,
592 /*out*/std::set<dex::TypeIndex>* class_set,
593 /*out*/std::set<uint16_t>* hot_method_set,
594 /*out*/std::set<uint16_t>* startup_method_set,
595 /*out*/std::set<uint16_t>* post_startup_method_method_set,
596 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
597
598 const ArenaSet<dex::TypeIndex>* GetClasses(
599 const DexFile& dex_file,
600 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
601
602 // Returns true iff both profiles have the same version.
603 bool SameVersion(const ProfileCompilationInfo& other) const;
604
605 // Perform an equality test with the `other` profile information.
606 bool Equals(const ProfileCompilationInfo& other);
607
608 // Return the base profile key associated with the given dex location. The base profile key
609 // is solely constructed based on the dex location (as opposed to the one produced by
610 // GetProfileDexFileAugmentedKey which may include additional metadata like the origin
611 // package name)
612 static std::string GetProfileDexFileBaseKey(const std::string& dex_location);
613
614 // Returns a base key without the annotation information.
615 static std::string GetBaseKeyFromAugmentedKey(const std::string& profile_key);
616
617 // Returns the annotations from an augmented key.
618 // If the key is a base key it return ProfileSampleAnnotation::kNone.
619 static ProfileSampleAnnotation GetAnnotationFromKey(const std::string& augmented_key);
620
621 // Generate a test profile which will contain a percentage of the total maximum
622 // number of methods and classes (method_ratio and class_ratio).
623 static bool GenerateTestProfile(int fd,
624 uint16_t number_of_dex_files,
625 uint16_t method_ratio,
626 uint16_t class_ratio,
627 uint32_t random_seed);
628
629 // Generate a test profile which will randomly contain classes and methods from
630 // the provided list of dex files.
631 static bool GenerateTestProfile(int fd,
632 std::vector<std::unique_ptr<const DexFile>>& dex_files,
633 uint16_t method_percentage,
634 uint16_t class_percentage,
635 uint32_t random_seed);
636
GetAllocator()637 ArenaAllocator* GetAllocator() { return &allocator_; }
638
639 // Return all of the class descriptors in the profile for a set of dex files.
640 // Note: see GetMethodHotness docs for the handling of annotations..
641 HashSet<std::string> GetClassDescriptors(
642 const std::vector<const DexFile*>& dex_files,
643 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
644
645 // Return true if the fd points to a profile file.
646 bool IsProfileFile(int fd);
647
648 // Update the profile keys corresponding to the given dex files based on their current paths.
649 // This method allows fix-ups in the profile for dex files that might have been renamed.
650 // The new profile key will be constructed based on the current dex location.
651 //
652 // The matching [profile key <-> dex_file] is done based on the dex checksum and the number of
653 // methods ids. If neither is a match then the profile key is not updated.
654 //
655 // If the new profile key would collide with an existing key (for a different dex)
656 // the method returns false. Otherwise it returns true.
657 //
658 // `matched` is set to true if any profile has matched any input dex file.
659 bool UpdateProfileKeys(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
660 /*out*/ bool* matched);
661
662 // Checks if the profile is empty.
663 bool IsEmpty() const;
664
665 // Clears all the data from the profile.
666 void ClearData();
667
668 // Clears all the data from the profile and adjust the object version.
669 void ClearDataAndAdjustVersion(bool for_boot_image);
670
671 // Prepare the profile to store aggregation counters.
672 // This will change the profile version and allocate extra storage for the counters.
673 // It allocates 2 bytes for every possible method and class, so do not use in performance
674 // critical code which needs to be memory efficient.
675 void PrepareForAggregationCounters();
676
677 // Returns true if the profile is configured to store aggregation counters.
678 bool IsForBootImage() const;
679
680 // Get type descriptor for a valid type index, whether a normal type index
681 // referencing a `dex::TypeId` in the dex file, or an artificial type index
682 // referencing an "extra descriptor".
GetTypeDescriptor(const DexFile * dex_file,dex::TypeIndex type_index)683 const char* GetTypeDescriptor(const DexFile* dex_file, dex::TypeIndex type_index) const {
684 DCHECK(type_index.IsValid());
685 uint32_t num_type_ids = dex_file->NumTypeIds();
686 if (type_index.index_ < num_type_ids) {
687 return dex_file->StringByTypeIdx(type_index);
688 } else {
689 return extra_descriptors_[type_index.index_ - num_type_ids].c_str();
690 }
691 }
692
693 // Return the version of this profile.
694 const uint8_t* GetVersion() const;
695
696 // Extracts the data that the profile has on the given dex files:
697 // - for each method and class, a list of the corresponding annotations and flags
698 // - the maximum number of aggregations for classes and classes across dex files with different
699 // annotations (essentially this sums up how many different packages used the corresponding
700 // method). This information is reconstructible from the other two pieces of info, but it's
701 // convenient to have it precomputed.
702 std::unique_ptr<FlattenProfileData> ExtractProfileData(
703 const std::vector<std::unique_ptr<const DexFile>>& dex_files) const;
704
705 private:
706 // Helper classes.
707 class FileHeader;
708 class FileSectionInfo;
709 enum class FileSectionType : uint32_t;
710 enum class ProfileLoadStatus : uint32_t;
711 class ProfileSource;
712 class SafeBuffer;
713
714 // Extra descriptors are used to reference classes with `TypeIndex` between the dex
715 // file's `NumTypeIds()` and the `DexFile::kDexNoIndex16`. The range of usable
716 // extra descriptor indexes is therefore also limited by `DexFile::kDexNoIndex16`.
717 using ExtraDescriptorIndex = uint16_t;
718 static constexpr ExtraDescriptorIndex kMaxExtraDescriptors = DexFile::kDexNoIndex16;
719
720 class ExtraDescriptorIndexEmpty {
721 public:
MakeEmpty(ExtraDescriptorIndex & index)722 void MakeEmpty(ExtraDescriptorIndex& index) const {
723 index = kMaxExtraDescriptors;
724 }
IsEmpty(const ExtraDescriptorIndex & index)725 bool IsEmpty(const ExtraDescriptorIndex& index) const {
726 return index == kMaxExtraDescriptors;
727 }
728 };
729
730 class ExtraDescriptorHash {
731 public:
ExtraDescriptorHash(const dchecked_vector<std::string> * extra_descriptors)732 explicit ExtraDescriptorHash(const dchecked_vector<std::string>* extra_descriptors)
733 : extra_descriptors_(extra_descriptors) {}
734
operator()735 size_t operator()(const ExtraDescriptorIndex& index) const {
736 std::string_view str = (*extra_descriptors_)[index];
737 return (*this)(str);
738 }
739
operator()740 size_t operator()(std::string_view str) const {
741 return DataHash()(str);
742 }
743
744 private:
745 const dchecked_vector<std::string>* extra_descriptors_;
746 };
747
748 class ExtraDescriptorEquals {
749 public:
ExtraDescriptorEquals(const dchecked_vector<std::string> * extra_descriptors)750 explicit ExtraDescriptorEquals(const dchecked_vector<std::string>* extra_descriptors)
751 : extra_descriptors_(extra_descriptors) {}
752
operator()753 size_t operator()(const ExtraDescriptorIndex& lhs, const ExtraDescriptorIndex& rhs) const {
754 DCHECK_EQ(lhs == rhs, (*this)(lhs, (*extra_descriptors_)[rhs]));
755 return lhs == rhs;
756 }
757
operator()758 size_t operator()(const ExtraDescriptorIndex& lhs, std::string_view rhs_str) const {
759 std::string_view lhs_str = (*extra_descriptors_)[lhs];
760 return lhs_str == rhs_str;
761 }
762
763 private:
764 const dchecked_vector<std::string>* extra_descriptors_;
765 };
766
767 using ExtraDescriptorHashSet = HashSet<ExtraDescriptorIndex,
768 ExtraDescriptorIndexEmpty,
769 ExtraDescriptorHash,
770 ExtraDescriptorEquals>;
771
772 // Internal representation of the profile information belonging to a dex file.
773 // Note that we could do without the profile_index (the index of the dex file
774 // in the profile) field in this struct because we can infer it from
775 // `profile_key_map_` and `info_`. However, it makes the profiles logic much
776 // simpler if we have the profile index here as well.
777 struct DexFileData : public DeletableArenaObject<kArenaAllocProfile> {
DexFileDataDexFileData778 DexFileData(ArenaAllocator* allocator,
779 const std::string& key,
780 uint32_t location_checksum,
781 uint16_t index,
782 uint32_t num_types,
783 uint32_t num_methods,
784 bool for_boot_image)
785 : allocator_(allocator),
786 profile_key(key),
787 profile_index(index),
788 checksum(location_checksum),
789 method_map(std::less<uint16_t>(), allocator->Adapter(kArenaAllocProfile)),
790 class_set(std::less<dex::TypeIndex>(), allocator->Adapter(kArenaAllocProfile)),
791 num_type_ids(num_types),
792 num_method_ids(num_methods),
793 bitmap_storage(allocator->Adapter(kArenaAllocProfile)),
794 is_for_boot_image(for_boot_image) {
795 bitmap_storage.resize(ComputeBitmapStorage(is_for_boot_image, num_method_ids));
796 if (!bitmap_storage.empty()) {
797 method_bitmap =
798 BitMemoryRegion(MemoryRegion(
799 &bitmap_storage[0],
800 bitmap_storage.size()),
801 0,
802 ComputeBitmapBits(is_for_boot_image, num_method_ids));
803 }
804 }
805
ComputeBitmapBitsDexFileData806 static size_t ComputeBitmapBits(bool is_for_boot_image, uint32_t num_method_ids) {
807 size_t flag_bitmap_index = FlagBitmapIndex(is_for_boot_image
808 ? MethodHotness::kFlagLastBoot
809 : MethodHotness::kFlagLastRegular);
810 return num_method_ids * (flag_bitmap_index + 1);
811 }
ComputeBitmapStorageDexFileData812 static size_t ComputeBitmapStorage(bool is_for_boot_image, uint32_t num_method_ids) {
813 return RoundUp(ComputeBitmapBits(is_for_boot_image, num_method_ids), kBitsPerByte) /
814 kBitsPerByte;
815 }
816
817 bool operator==(const DexFileData& other) const {
818 return checksum == other.checksum &&
819 num_method_ids == other.num_method_ids &&
820 method_map == other.method_map &&
821 class_set == other.class_set &&
822 BitMemoryRegion::Equals(method_bitmap, other.method_bitmap);
823 }
824
825 // Mark a method as executed at least once.
826 bool AddMethod(MethodHotness::Flag flags, size_t index);
827
MergeBitmapDexFileData828 void MergeBitmap(const DexFileData& other) {
829 DCHECK_EQ(bitmap_storage.size(), other.bitmap_storage.size());
830 for (size_t i = 0; i < bitmap_storage.size(); ++i) {
831 bitmap_storage[i] |= other.bitmap_storage[i];
832 }
833 }
834
835 void SetMethodHotness(size_t index, MethodHotness::Flag flags);
836 MethodHotness GetHotnessInfo(uint32_t dex_method_index) const;
837
IsStartupMethodDexFileData838 bool IsStartupMethod(uint32_t method_index) const {
839 DCHECK_LT(method_index, num_method_ids);
840 return method_bitmap.LoadBit(
841 MethodFlagBitmapIndex(MethodHotness::Flag::kFlagStartup, method_index));
842 }
843
IsPostStartupMethodDexFileData844 bool IsPostStartupMethod(uint32_t method_index) const {
845 DCHECK_LT(method_index, num_method_ids);
846 return method_bitmap.LoadBit(
847 MethodFlagBitmapIndex(MethodHotness::Flag::kFlagPostStartup, method_index));
848 }
849
IsHotMethodDexFileData850 bool IsHotMethod(uint32_t method_index) const {
851 DCHECK_LT(method_index, num_method_ids);
852 return method_map.find(method_index) != method_map.end();
853 }
854
IsMethodInProfileDexFileData855 bool IsMethodInProfile(uint32_t method_index) const {
856 DCHECK_LT(method_index, num_method_ids);
857 bool has_flag = false;
858 ForMethodBitmapHotnessFlags([&](MethodHotness::Flag flag) {
859 if (method_bitmap.LoadBit(MethodFlagBitmapIndex(
860 static_cast<MethodHotness::Flag>(flag), method_index))) {
861 has_flag = true;
862 return false;
863 }
864 return true;
865 });
866 return has_flag || IsHotMethod(method_index);
867 }
868
869 bool ContainsClass(dex::TypeIndex type_index) const;
870
871 uint32_t ClassesDataSize() const;
872 void WriteClasses(SafeBuffer& buffer) const;
873 ProfileLoadStatus ReadClasses(
874 SafeBuffer& buffer,
875 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
876 std::string* error);
877 static ProfileLoadStatus SkipClasses(SafeBuffer& buffer, std::string* error);
878
879 uint32_t MethodsDataSize(/*out*/ uint16_t* method_flags = nullptr,
880 /*out*/ size_t* saved_bitmap_bit_size = nullptr) const;
881 void WriteMethods(SafeBuffer& buffer) const;
882 ProfileLoadStatus ReadMethods(
883 SafeBuffer& buffer,
884 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
885 std::string* error);
886 static ProfileLoadStatus SkipMethods(SafeBuffer& buffer, std::string* error);
887
888 // The allocator used to allocate new inline cache maps.
889 ArenaAllocator* const allocator_;
890 // The profile key this data belongs to.
891 std::string profile_key;
892 // The profile index of this dex file (matches ClassReference#dex_profile_index).
893 ProfileIndexType profile_index;
894 // The dex checksum.
895 uint32_t checksum;
896 // The methods' profile information.
897 MethodMap method_map;
898 // The classes which have been profiled. Note that these don't necessarily include
899 // all the classes that can be found in the inline caches reference.
900 ArenaSet<dex::TypeIndex> class_set;
901 // Find the inline caches of the the given method index. Add an empty entry if
902 // no previous data is found.
903 InlineCacheMap* FindOrAddHotMethod(uint16_t method_index);
904 // Num type ids.
905 uint32_t num_type_ids;
906 // Num method ids.
907 uint32_t num_method_ids;
908 ArenaVector<uint8_t> bitmap_storage;
909 BitMemoryRegion method_bitmap;
910 bool is_for_boot_image;
911
912 private:
913 template <typename Fn>
ForMethodBitmapHotnessFlagsDexFileData914 void ForMethodBitmapHotnessFlags(Fn fn) const {
915 uint32_t lastFlag = is_for_boot_image
916 ? MethodHotness::kFlagLastBoot
917 : MethodHotness::kFlagLastRegular;
918 for (uint32_t flag = MethodHotness::kFlagFirst; flag <= lastFlag; flag = flag << 1) {
919 if (flag == MethodHotness::kFlagHot) {
920 // There's no bit for hotness in the bitmap.
921 // We store the hotness by recording the method in the method list.
922 continue;
923 }
924 bool cont = fn(enum_cast<MethodHotness::Flag>(flag));
925 if (!cont) {
926 break;
927 }
928 }
929 }
930
MethodFlagBitmapIndexDexFileData931 size_t MethodFlagBitmapIndex(MethodHotness::Flag flag, size_t method_index) const {
932 DCHECK_LT(method_index, num_method_ids);
933 // The format is [startup bitmap][post startup bitmap][AmStartup][...]
934 // This compresses better than ([startup bit][post startup bit])*
935 return method_index + FlagBitmapIndex(flag) * num_method_ids;
936 }
937
FlagBitmapIndexDexFileData938 static size_t FlagBitmapIndex(MethodHotness::Flag flag) {
939 DCHECK(flag != MethodHotness::kFlagHot);
940 DCHECK(IsPowerOfTwo(static_cast<uint32_t>(flag)));
941 // We arrange the method flags in order, starting with the startup flag.
942 // The kFlagHot is not encoded in the bitmap and thus not expected as an
943 // argument here. Since all the other flags start at 1 we have to subtract
944 // one from the power of 2.
945 return WhichPowerOf2(static_cast<uint32_t>(flag)) - 1;
946 }
947
948 static void WriteClassSet(SafeBuffer& buffer, const ArenaSet<dex::TypeIndex>& class_set);
949
950 uint16_t GetUsedBitmapFlags() const;
951 };
952
953 // Return the profile data for the given profile key or null if the dex location
954 // already exists but has a different checksum
955 DexFileData* GetOrAddDexFileData(const std::string& profile_key,
956 uint32_t checksum,
957 uint32_t num_type_ids,
958 uint32_t num_method_ids);
959
GetOrAddDexFileData(const DexFile * dex_file,const ProfileSampleAnnotation & annotation)960 DexFileData* GetOrAddDexFileData(const DexFile* dex_file,
961 const ProfileSampleAnnotation& annotation) {
962 return GetOrAddDexFileData(GetProfileDexFileAugmentedKey(dex_file->GetLocation(), annotation),
963 dex_file->GetLocationChecksum(),
964 dex_file->NumTypeIds(),
965 dex_file->NumMethodIds());
966 }
967
968 // Return the dex data associated with the given profile key or null if the profile
969 // doesn't contain the key.
970 const DexFileData* FindDexData(const std::string& profile_key,
971 uint32_t checksum,
972 bool verify_checksum = true) const;
973 // Same as FindDexData but performs the searching using the given annotation:
974 // - If the annotation is kNone then the search ignores it and only looks at the base keys.
975 // In this case only the first matching dex is searched.
976 // - If the annotation is not kNone, the augmented key is constructed and used to invoke
977 // the regular FindDexData.
978 const DexFileData* FindDexDataUsingAnnotations(
979 const DexFile* dex_file,
980 const ProfileSampleAnnotation& annotation) const;
981
982 // Same as FindDexDataUsingAnnotations but extracts the data for all annotations.
983 void FindAllDexData(
984 const DexFile* dex_file,
985 /*out*/ std::vector<const ProfileCompilationInfo::DexFileData*>* result) const;
986
987 // Add a new extra descriptor. Returns kMaxExtraDescriptors on failure.
988 ExtraDescriptorIndex AddExtraDescriptor(std::string_view extra_descriptor);
989
990 // Parsing functionality.
991
992 ProfileLoadStatus OpenSource(int32_t fd,
993 /*out*/ std::unique_ptr<ProfileSource>* source,
994 /*out*/ std::string* error);
995
996 ProfileLoadStatus ReadSectionData(ProfileSource& source,
997 const FileSectionInfo& section_info,
998 /*out*/ SafeBuffer* buffer,
999 /*out*/ std::string* error);
1000
1001 ProfileLoadStatus ReadDexFilesSection(
1002 ProfileSource& source,
1003 const FileSectionInfo& section_info,
1004 const ProfileLoadFilterFn& filter_fn,
1005 /*out*/ dchecked_vector<ProfileIndexType>* dex_profile_index_remap,
1006 /*out*/ std::string* error);
1007
1008 ProfileLoadStatus ReadExtraDescriptorsSection(
1009 ProfileSource& source,
1010 const FileSectionInfo& section_info,
1011 /*out*/ dchecked_vector<ExtraDescriptorIndex>* extra_descriptors_remap,
1012 /*out*/ std::string* error);
1013
1014 ProfileLoadStatus ReadClassesSection(
1015 ProfileSource& source,
1016 const FileSectionInfo& section_info,
1017 const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1018 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1019 /*out*/ std::string* error);
1020
1021 ProfileLoadStatus ReadMethodsSection(
1022 ProfileSource& source,
1023 const FileSectionInfo& section_info,
1024 const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1025 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1026 /*out*/ std::string* error);
1027
1028 // Entry point for profile loading functionality.
1029 ProfileLoadStatus LoadInternal(
1030 int32_t fd,
1031 std::string* error,
1032 bool merge_classes = true,
1033 const ProfileLoadFilterFn& filter_fn = ProfileFilterFnAcceptAll);
1034
1035 // Find the data for the dex_pc in the inline cache. Adds an empty entry
1036 // if no previous data exists.
1037 static DexPcData* FindOrAddDexPc(InlineCacheMap* inline_cache, uint32_t dex_pc);
1038
1039 // Initializes the profile version to the desired one.
1040 void InitProfileVersionInternal(const uint8_t version[]);
1041
1042 // Returns the threshold size (in bytes) which will trigger save/load warnings.
1043 size_t GetSizeWarningThresholdBytes() const;
1044 // Returns the threshold size (in bytes) which will cause save/load failures.
1045 size_t GetSizeErrorThresholdBytes() const;
1046
1047 // Implementation of `GetProfileDexFileBaseKey()` but returning a subview
1048 // referencing the same underlying data to avoid excessive heap allocations.
1049 static std::string_view GetProfileDexFileBaseKeyView(std::string_view dex_location);
1050
1051 // Implementation of `GetBaseKeyFromAugmentedKey()` but returning a subview
1052 // referencing the same underlying data to avoid excessive heap allocations.
1053 static std::string_view GetBaseKeyViewFromAugmentedKey(std::string_view dex_location);
1054
1055 // Returns the augmented profile key associated with the given dex location.
1056 // The return key will contain a serialized form of the information from the provided
1057 // annotation. If the annotation is ProfileSampleAnnotation::kNone then no extra info is
1058 // added to the key and this method is equivalent to GetProfileDexFileBaseKey.
1059 static std::string GetProfileDexFileAugmentedKey(const std::string& dex_location,
1060 const ProfileSampleAnnotation& annotation);
1061
1062 // Migrates the annotation from an augmented key to a base key.
1063 static std::string MigrateAnnotationInfo(const std::string& base_key,
1064 const std::string& augmented_key);
1065
1066 friend class ProfileCompilationInfoTest;
1067 friend class CompilerDriverProfileTest;
1068 friend class ProfileAssistantTest;
1069 friend class Dex2oatLayoutTest;
1070
1071 MallocArenaPool default_arena_pool_;
1072 ArenaAllocator allocator_;
1073
1074 // Vector containing the actual profile info.
1075 // The vector index is the profile index of the dex data and
1076 // matched DexFileData::profile_index.
1077 ArenaVector<std::unique_ptr<DexFileData>> info_;
1078
1079 // Cache mapping profile keys to profile index.
1080 // This is used to speed up searches since it avoids iterating
1081 // over the info_ vector when searching by profile key.
1082 // The backing storage for the `string_view` is the associated `DexFileData`.
1083 ArenaSafeMap<const std::string_view, ProfileIndexType> profile_key_map_;
1084
1085 // Additional descriptors for referencing types not present in a dex files's `TypeId`s.
1086 dchecked_vector<std::string> extra_descriptors_;
1087 ExtraDescriptorHashSet extra_descriptors_indexes_;
1088
1089 // The version of the profile.
1090 uint8_t version_[kProfileVersionSize];
1091 };
1092
1093 /**
1094 * Flatten profile data that list all methods and type references together
1095 * with their metadata (such as flags or annotation list).
1096 */
1097 class FlattenProfileData {
1098 public:
1099 class ItemMetadata {
1100 public:
1101 ItemMetadata();
1102 ItemMetadata(const ItemMetadata& other);
1103
GetFlags()1104 uint16_t GetFlags() const {
1105 return flags_;
1106 }
1107
GetAnnotations()1108 const std::list<ProfileCompilationInfo::ProfileSampleAnnotation>& GetAnnotations() const {
1109 return annotations_;
1110 }
1111
AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag)1112 void AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag) {
1113 flags_ |= flag;
1114 }
1115
HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag)1116 bool HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag) const {
1117 return (flags_ & flag) != 0;
1118 }
1119
1120 private:
1121 // will be 0 for classes and MethodHotness::Flags for methods.
1122 uint16_t flags_;
1123 // This is a list that may contain duplicates after a merge operation.
1124 // It represents that a method was used multiple times across different devices.
1125 std::list<ProfileCompilationInfo::ProfileSampleAnnotation> annotations_;
1126
1127 friend class ProfileCompilationInfo;
1128 friend class FlattenProfileData;
1129 };
1130
1131 FlattenProfileData();
1132
GetMethodData()1133 const SafeMap<MethodReference, ItemMetadata>& GetMethodData() const {
1134 return method_metadata_;
1135 }
1136
GetClassData()1137 const SafeMap<TypeReference, ItemMetadata>& GetClassData() const {
1138 return class_metadata_;
1139 }
1140
GetMaxAggregationForMethods()1141 uint32_t GetMaxAggregationForMethods() const {
1142 return max_aggregation_for_methods_;
1143 }
1144
GetMaxAggregationForClasses()1145 uint32_t GetMaxAggregationForClasses() const {
1146 return max_aggregation_for_classes_;
1147 }
1148
1149 void MergeData(const FlattenProfileData& other);
1150
1151 private:
1152 // Method data.
1153 SafeMap<MethodReference, ItemMetadata> method_metadata_;
1154 // Class data.
1155 SafeMap<TypeReference, ItemMetadata> class_metadata_;
1156 // Maximum aggregation counter for all methods.
1157 // This is essentially a cache equal to the max size of any method's annotation set.
1158 // It avoids the traversal of all the methods which can be quite expensive.
1159 uint32_t max_aggregation_for_methods_;
1160 // Maximum aggregation counter for all classes.
1161 // Simillar to max_aggregation_for_methods_.
1162 uint32_t max_aggregation_for_classes_;
1163
1164 friend class ProfileCompilationInfo;
1165 };
1166
1167 struct ProfileCompilationInfo::DexReferenceDumper {
GetProfileKeyDexReferenceDumper1168 const std::string& GetProfileKey() {
1169 return dex_file_data->profile_key;
1170 }
1171
GetDexChecksumDexReferenceDumper1172 uint32_t GetDexChecksum() const {
1173 return dex_file_data->checksum;
1174 }
1175
GetNumTypeIdsDexReferenceDumper1176 uint32_t GetNumTypeIds() const {
1177 return dex_file_data->num_type_ids;
1178 }
1179
GetNumMethodIdsDexReferenceDumper1180 uint32_t GetNumMethodIds() const {
1181 return dex_file_data->num_method_ids;
1182 }
1183
1184 const DexFileData* dex_file_data;
1185 };
1186
DumpDexReference(ProfileIndexType profile_index)1187 inline ProfileCompilationInfo::DexReferenceDumper ProfileCompilationInfo::DumpDexReference(
1188 ProfileIndexType profile_index) const {
1189 return DexReferenceDumper{info_[profile_index].get()};
1190 }
1191
1192 std::ostream& operator<<(std::ostream& stream, ProfileCompilationInfo::DexReferenceDumper dumper);
1193
1194 } // namespace art
1195
1196 #endif // ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
1197