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   // `is_test` should be set to true for unit tests which create artificial dex
326   // files.
327   bool AddMethods(const std::vector<ProfileMethodInfo>& methods,
328                   MethodHotness::Flag flags,
329                   const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone,
330                   bool is_test = false);
331 
332   // Find a type index in the `dex_file` if there is a `TypeId` for it. Otherwise,
333   // find or insert the descriptor in "extra descriptors" and return an artificial
334   // type index beyond `dex_file.NumTypeIds()`. This fails if the artificial index
335   // would be kDexNoIndex16 (0xffffu) or higher, returning an invalid type index.
336   // The returned type index can be used, if valid, for `AddClass()` or (TODO) as
337   // a type index for inline caches.
338   dex::TypeIndex FindOrCreateTypeIndex(const DexFile& dex_file, TypeReference class_ref);
339   dex::TypeIndex FindOrCreateTypeIndex(const DexFile& dex_file, std::string_view descriptor);
340 
341   // Add a class with the specified `type_index` to the profile. The `type_index`
342   // can be either a normal index for a `TypeId` in the dex file, or an artificial
343   // type index created by `FindOrCreateTypeIndex()`.
AddClass(ProfileIndexType profile_index,dex::TypeIndex type_index)344   void AddClass(ProfileIndexType profile_index, dex::TypeIndex type_index) {
345     DCHECK_LT(profile_index, info_.size());
346     DexFileData* const data = info_[profile_index].get();
347     DCHECK(type_index.IsValid());
348     DCHECK(type_index.index_ <= data->num_type_ids ||
349            type_index.index_ - data->num_type_ids < extra_descriptors_.size());
350     data->class_set.insert(type_index);
351   }
352 
353   // Add a class with the specified `type_index` to the profile. The `type_index`
354   // can be either a normal index for a `TypeId` in the dex file, or an artificial
355   // type index created by `FindOrCreateTypeIndex()`.
356   // Returns `true` on success, `false` on failure.
357   bool AddClass(const DexFile& dex_file,
358                 dex::TypeIndex type_index,
359                 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
360     DCHECK(type_index.IsValid());
361     DCHECK(type_index.index_ <= dex_file.NumTypeIds() ||
362            type_index.index_ - dex_file.NumTypeIds() < extra_descriptors_.size());
363     DexFileData* const data = GetOrAddDexFileData(&dex_file, annotation);
364     if (data == nullptr) {  // Checksum/num_type_ids/num_method_ids mismatch or too many dex files.
365       return false;
366     }
367     data->class_set.insert(type_index);
368     return true;
369   }
370 
371   // Add a class with the specified `descriptor` to the profile.
372   // Returns `true` on success, `false` on failure.
373   bool AddClass(const DexFile& dex_file,
374                 std::string_view descriptor,
375                 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
376 
377   // Add multiple type ids for classes in a single dex file. Iterator is for type_ids not
378   // class_defs.
379   //
380   // Note: see AddMethods docs for the handling of annotations.
381   template <class Iterator>
382   bool AddClassesForDex(
383       const DexFile* dex_file,
384       Iterator index_begin,
385       Iterator index_end,
386       const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
387     DexFileData* data = GetOrAddDexFileData(dex_file, annotation);
388     if (data == nullptr) {
389       return false;
390     }
391     data->class_set.insert(index_begin, index_end);
392     return true;
393   }
394 
AddMethod(ProfileIndexType profile_index,uint32_t method_index,MethodHotness::Flag flags)395   void AddMethod(ProfileIndexType profile_index, uint32_t method_index, MethodHotness::Flag flags) {
396     DCHECK_LT(profile_index, info_.size());
397     DexFileData* const data = info_[profile_index].get();
398     DCHECK_LT(method_index, data->num_method_ids);
399     data->AddMethod(flags, method_index);
400   }
401 
402   // Add a method to the profile using its online representation (containing runtime structures).
403   //
404   // Note: see AddMethods docs for the handling of annotations.
405   bool AddMethod(const ProfileMethodInfo& pmi,
406                  MethodHotness::Flag flags,
407                  const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone,
408                  bool is_test = false);
409 
410   // Bulk add sampled methods and/or hot methods for a single dex, fast since it only has one
411   // GetOrAddDexFileData call.
412   //
413   // Note: see AddMethods docs for the handling of annotations.
414   template <class Iterator>
415   bool AddMethodsForDex(
416       MethodHotness::Flag flags,
417       const DexFile* dex_file,
418       Iterator index_begin,
419       Iterator index_end,
420       const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
421     DexFileData* data = GetOrAddDexFileData(dex_file, annotation);
422     if (data == nullptr) {
423       return false;
424     }
425     for (Iterator it = index_begin; it != index_end; ++it) {
426       DCHECK_LT(*it, data->num_method_ids);
427       if (!data->AddMethod(flags, *it)) {
428         return false;
429       }
430     }
431     return true;
432   }
433 
434   // Load or Merge profile information from the given file descriptor.
435   // If the current profile is non-empty the load will fail.
436   // If merge_classes is set to false, classes will not be merged/loaded.
437   // If filter_fn is present, it will be used to filter out profile data belonging
438   // to dex file which do not comply with the filter
439   // (i.e. for which filter_fn(dex_location, dex_checksum) is false).
440   using ProfileLoadFilterFn = std::function<bool(const std::string&, uint32_t)>;
441   // Profile filter method which accepts all dex locations.
442   // This is convenient to use when we need to accept all locations without repeating the same
443   // lambda.
444   static bool ProfileFilterFnAcceptAll(const std::string& dex_location, uint32_t checksum);
445 
446   bool Load(
447       int fd,
448       bool merge_classes = true,
449       const ProfileLoadFilterFn& filter_fn = ProfileFilterFnAcceptAll);
450 
451   // Verify integrity of the profile file with the provided dex files.
452   // If there exists a DexData object which maps to a dex_file, then it verifies that:
453   // - The checksums of the DexData and dex_file are equals.
454   // - No method id exceeds NumMethodIds corresponding to the dex_file.
455   // - No class id exceeds NumTypeIds corresponding to the dex_file.
456   // - For every inline_caches, class_ids does not exceed NumTypeIds corresponding to
457   //   the dex_file they are in.
458   bool VerifyProfileData(const std::vector<const DexFile*>& dex_files);
459 
460   // Loads profile information from the given file.
461   // Returns true on success, false otherwise.
462   // If the current profile is non-empty the load will fail.
463   // If clear_if_invalid is true:
464   // - If the file is invalid, the method clears the file and returns true.
465   // - If the file doesn't exist, the method returns true.
466   bool Load(const std::string& filename, bool clear_if_invalid);
467 
468   // Merge the data from another ProfileCompilationInfo into the current object. Only merges
469   // classes if merge_classes is true. This is used for creating the boot profile since
470   // we don't want all of the classes to be image classes.
471   bool MergeWith(const ProfileCompilationInfo& info, bool merge_classes = true);
472 
473   // Merge profile information from the given file descriptor.
474   bool MergeWith(const std::string& filename);
475 
476   // Save the profile data to the given file descriptor.
477   bool Save(int fd);
478 
479   // Save the current profile into the given file. Overwrites any existing data.
480   bool Save(const std::string& filename, uint64_t* bytes_written);
481 
482   // A fallback implementation of `Save` that uses a flock.
483   bool SaveFallback(const std::string& filename, uint64_t* bytes_written);
484 
485   // Return the number of dex files referenced in the profile.
GetNumberOfDexFiles()486   size_t GetNumberOfDexFiles() const {
487     return info_.size();
488   }
489 
490   // Return the number of methods that were profiled.
491   uint32_t GetNumberOfMethods() const;
492 
493   // Return the number of resolved classes that were profiled.
494   uint32_t GetNumberOfResolvedClasses() const;
495 
496   // Returns whether the referenced method is a startup method.
IsStartupMethod(ProfileIndexType profile_index,uint32_t method_index)497   bool IsStartupMethod(ProfileIndexType profile_index, uint32_t method_index) const {
498     return info_[profile_index]->IsStartupMethod(method_index);
499   }
500 
501   // Returns whether the referenced method is a post-startup method.
IsPostStartupMethod(ProfileIndexType profile_index,uint32_t method_index)502   bool IsPostStartupMethod(ProfileIndexType profile_index, uint32_t method_index) const {
503     return info_[profile_index]->IsPostStartupMethod(method_index);
504   }
505 
506   // Returns whether the referenced method is hot.
IsHotMethod(ProfileIndexType profile_index,uint32_t method_index)507   bool IsHotMethod(ProfileIndexType profile_index, uint32_t method_index) const {
508     return info_[profile_index]->IsHotMethod(method_index);
509   }
510 
511   // Returns whether the referenced method is in the profile (with any hotness flag).
IsMethodInProfile(ProfileIndexType profile_index,uint32_t method_index)512   bool IsMethodInProfile(ProfileIndexType profile_index, uint32_t method_index) const {
513     DCHECK_LT(profile_index, info_.size());
514     const DexFileData* const data = info_[profile_index].get();
515     return data->IsMethodInProfile(method_index);
516   }
517 
518   // Returns the profile method info for a given method reference.
519   //
520   // Note that if the profile was built with annotations, the same dex file may be
521   // represented multiple times in the profile (due to different annotation associated with it).
522   // If so, and if no annotation is passed to this method, then only the first dex file is searched.
523   //
524   // Implementation details: It is suitable to pass kNone for regular profile guided compilation
525   // because during compilation we generally don't care about annotations. The metadata is
526   // useful for boot profiles which need the extra information.
527   MethodHotness GetMethodHotness(
528       const MethodReference& method_ref,
529       const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
530 
531   // Return true if the class's type is present in the profiling info.
ContainsClass(ProfileIndexType profile_index,dex::TypeIndex type_index)532   bool ContainsClass(ProfileIndexType profile_index, dex::TypeIndex type_index) const {
533     DCHECK_LT(profile_index, info_.size());
534     const DexFileData* const data = info_[profile_index].get();
535     DCHECK(type_index.IsValid());
536     DCHECK(type_index.index_ <= data->num_type_ids ||
537            type_index.index_ - data->num_type_ids < extra_descriptors_.size());
538     return data->class_set.find(type_index) != data->class_set.end();
539   }
540 
541   // Return true if the class's type is present in the profiling info.
542   //
543   // Note: see GetMethodHotness docs for the handling of annotations.
544   bool ContainsClass(
545       const DexFile& dex_file,
546       dex::TypeIndex type_idx,
547       const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
548 
549   // Return the dex file for the given `profile_index`, or null if none of the provided
550   // dex files has a matching checksum and a location with the same base key.
551   template <typename Container>
FindDexFileForProfileIndex(ProfileIndexType profile_index,const Container & dex_files)552   const DexFile* FindDexFileForProfileIndex(ProfileIndexType profile_index,
553                                             const Container& dex_files) const {
554     static_assert(std::is_same_v<typename Container::value_type, const DexFile*> ||
555                   std::is_same_v<typename Container::value_type, std::unique_ptr<const DexFile>>);
556     DCHECK_LE(profile_index, info_.size());
557     const DexFileData* dex_file_data = info_[profile_index].get();
558     DCHECK(dex_file_data != nullptr);
559     uint32_t dex_checksum = dex_file_data->checksum;
560     std::string_view base_key = GetBaseKeyViewFromAugmentedKey(dex_file_data->profile_key);
561     for (const auto& dex_file : dex_files) {
562       if (dex_checksum == dex_file->GetLocationChecksum() &&
563           base_key == GetProfileDexFileBaseKeyView(dex_file->GetLocation())) {
564         return std::addressof(*dex_file);
565       }
566     }
567     return nullptr;
568   }
569 
570   DexReferenceDumper DumpDexReference(ProfileIndexType profile_index) const;
571 
572   // Dump all the loaded profile info into a string and returns it.
573   // If dex_files is not empty then the method indices will be resolved to their
574   // names.
575   // This is intended for testing and debugging.
576   std::string DumpInfo(const std::vector<const DexFile*>& dex_files,
577                        bool print_full_dex_location = true) const;
578 
579   // Return the classes and methods for a given dex file through out args. The out args are the set
580   // of class as well as the methods and their associated inline caches. Returns true if the dex
581   // file is register and has a matching checksum, false otherwise.
582   //
583   // Note: see GetMethodHotness docs for the handling of annotations.
584   bool GetClassesAndMethods(
585       const DexFile& dex_file,
586       /*out*/std::set<dex::TypeIndex>* class_set,
587       /*out*/std::set<uint16_t>* hot_method_set,
588       /*out*/std::set<uint16_t>* startup_method_set,
589       /*out*/std::set<uint16_t>* post_startup_method_method_set,
590       const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
591 
592   const ArenaSet<dex::TypeIndex>* GetClasses(
593       const DexFile& dex_file,
594       const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
595 
596   // Returns true iff both profiles have the same version.
597   bool SameVersion(const ProfileCompilationInfo& other) const;
598 
599   // Perform an equality test with the `other` profile information.
600   bool Equals(const ProfileCompilationInfo& other);
601 
602   // Return the base profile key associated with the given dex location. The base profile key
603   // is solely constructed based on the dex location (as opposed to the one produced by
604   // GetProfileDexFileAugmentedKey which may include additional metadata like the origin
605   // package name)
606   static std::string GetProfileDexFileBaseKey(const std::string& dex_location);
607 
608   // Returns a base key without the annotation information.
609   static std::string GetBaseKeyFromAugmentedKey(const std::string& profile_key);
610 
611   // Returns the annotations from an augmented key.
612   // If the key is a base key it return ProfileSampleAnnotation::kNone.
613   static ProfileSampleAnnotation GetAnnotationFromKey(const std::string& augmented_key);
614 
615   // Generate a test profile which will contain a percentage of the total maximum
616   // number of methods and classes (method_ratio and class_ratio).
617   static bool GenerateTestProfile(int fd,
618                                   uint16_t number_of_dex_files,
619                                   uint16_t method_ratio,
620                                   uint16_t class_ratio,
621                                   uint32_t random_seed);
622 
623   // Generate a test profile which will randomly contain classes and methods from
624   // the provided list of dex files.
625   static bool GenerateTestProfile(int fd,
626                                   std::vector<std::unique_ptr<const DexFile>>& dex_files,
627                                   uint16_t method_percentage,
628                                   uint16_t class_percentage,
629                                   uint32_t random_seed);
630 
GetAllocator()631   ArenaAllocator* GetAllocator() { return &allocator_; }
632 
633   // Return all of the class descriptors in the profile for a set of dex files.
634   // Note: see GetMethodHotness docs for the handling of annotations..
635   HashSet<std::string> GetClassDescriptors(
636       const std::vector<const DexFile*>& dex_files,
637       const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
638 
639   // Return true if the fd points to a profile file.
640   bool IsProfileFile(int fd);
641 
642   // Update the profile keys corresponding to the given dex files based on their current paths.
643   // This method allows fix-ups in the profile for dex files that might have been renamed.
644   // The new profile key will be constructed based on the current dex location.
645   //
646   // The matching [profile key <-> dex_file] is done based on the dex checksum and the number of
647   // methods ids. If neither is a match then the profile key is not updated.
648   //
649   // If the new profile key would collide with an existing key (for a different dex)
650   // the method returns false. Otherwise it returns true.
651   //
652   // `matched` is set to true if all profiles have matched input dex files.
653   bool UpdateProfileKeys(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
654                          /*out*/ bool* matched);
655 
656   // Checks if the profile is empty.
657   bool IsEmpty() const;
658 
659   // Clears all the data from the profile.
660   void ClearData();
661 
662   // Clears all the data from the profile and adjust the object version.
663   void ClearDataAndAdjustVersion(bool for_boot_image);
664 
665   // Prepare the profile to store aggregation counters.
666   // This will change the profile version and allocate extra storage for the counters.
667   // It allocates 2 bytes for every possible method and class, so do not use in performance
668   // critical code which needs to be memory efficient.
669   void PrepareForAggregationCounters();
670 
671   // Returns true if the profile is configured to store aggregation counters.
672   bool IsForBootImage() const;
673 
674   // Get type descriptor for a valid type index, whether a normal type index
675   // referencing a `dex::TypeId` in the dex file, or an artificial type index
676   // referencing an "extra descriptor".
GetTypeDescriptor(const DexFile * dex_file,dex::TypeIndex type_index)677   const char* GetTypeDescriptor(const DexFile* dex_file, dex::TypeIndex type_index) const {
678     DCHECK(type_index.IsValid());
679     uint32_t num_type_ids = dex_file->NumTypeIds();
680     if (type_index.index_ < num_type_ids) {
681       return dex_file->GetTypeDescriptor(type_index);
682     } else {
683       return extra_descriptors_[type_index.index_ - num_type_ids].c_str();
684     }
685   }
686 
687   // Return the version of this profile.
688   const uint8_t* GetVersion() const;
689 
690   // Extracts the data that the profile has on the given dex files:
691   //  - for each method and class, a list of the corresponding annotations and flags
692   //  - the maximum number of aggregations for classes and classes across dex files with different
693   //    annotations (essentially this sums up how many different packages used the corresponding
694   //    method). This information is reconstructible from the other two pieces of info, but it's
695   //    convenient to have it precomputed.
696   std::unique_ptr<FlattenProfileData> ExtractProfileData(
697       const std::vector<std::unique_ptr<const DexFile>>& dex_files) const;
698 
699  private:
700   // Helper classes.
701   class FileHeader;
702   class FileSectionInfo;
703   enum class FileSectionType : uint32_t;
704   enum class ProfileLoadStatus : uint32_t;
705   class ProfileSource;
706   class SafeBuffer;
707 
708   // Extra descriptors are used to reference classes with `TypeIndex` between the dex
709   // file's `NumTypeIds()` and the `DexFile::kDexNoIndex16`. The range of usable
710   // extra descriptor indexes is therefore also limited by `DexFile::kDexNoIndex16`.
711   using ExtraDescriptorIndex = uint16_t;
712   static constexpr ExtraDescriptorIndex kMaxExtraDescriptors = DexFile::kDexNoIndex16;
713 
714   class ExtraDescriptorIndexEmpty {
715    public:
MakeEmpty(ExtraDescriptorIndex & index)716     void MakeEmpty(ExtraDescriptorIndex& index) const {
717       index = kMaxExtraDescriptors;
718     }
IsEmpty(const ExtraDescriptorIndex & index)719     bool IsEmpty(const ExtraDescriptorIndex& index) const {
720       return index == kMaxExtraDescriptors;
721     }
722   };
723 
724   class ExtraDescriptorHash {
725    public:
ExtraDescriptorHash(const dchecked_vector<std::string> * extra_descriptors)726     explicit ExtraDescriptorHash(const dchecked_vector<std::string>* extra_descriptors)
727         : extra_descriptors_(extra_descriptors) {}
728 
operator()729     size_t operator()(const ExtraDescriptorIndex& index) const {
730       std::string_view str = (*extra_descriptors_)[index];
731       return (*this)(str);
732     }
733 
operator()734     size_t operator()(std::string_view str) const {
735       return DataHash()(str);
736     }
737 
738    private:
739     const dchecked_vector<std::string>* extra_descriptors_;
740   };
741 
742   class ExtraDescriptorEquals {
743    public:
ExtraDescriptorEquals(const dchecked_vector<std::string> * extra_descriptors)744     explicit ExtraDescriptorEquals(const dchecked_vector<std::string>* extra_descriptors)
745         : extra_descriptors_(extra_descriptors) {}
746 
operator()747     size_t operator()(const ExtraDescriptorIndex& lhs, const ExtraDescriptorIndex& rhs) const {
748       DCHECK_EQ(lhs == rhs, (*this)(lhs, (*extra_descriptors_)[rhs]));
749       return lhs == rhs;
750     }
751 
operator()752     size_t operator()(const ExtraDescriptorIndex& lhs, std::string_view rhs_str) const {
753       std::string_view lhs_str = (*extra_descriptors_)[lhs];
754       return lhs_str == rhs_str;
755     }
756 
757    private:
758     const dchecked_vector<std::string>* extra_descriptors_;
759   };
760 
761   using ExtraDescriptorHashSet = HashSet<ExtraDescriptorIndex,
762                                          ExtraDescriptorIndexEmpty,
763                                          ExtraDescriptorHash,
764                                          ExtraDescriptorEquals>;
765 
766   // Internal representation of the profile information belonging to a dex file.
767   // Note that we could do without the profile_index (the index of the dex file
768   // in the profile) field in this struct because we can infer it from
769   // `profile_key_map_` and `info_`. However, it makes the profiles logic much
770   // simpler if we have the profile index here as well.
771   struct DexFileData : public DeletableArenaObject<kArenaAllocProfile> {
DexFileDataDexFileData772     DexFileData(ArenaAllocator* allocator,
773                 const std::string& key,
774                 uint32_t location_checksum,
775                 uint16_t index,
776                 uint32_t num_types,
777                 uint32_t num_methods,
778                 bool for_boot_image)
779         : allocator_(allocator),
780           profile_key(key),
781           profile_index(index),
782           checksum(location_checksum),
783           method_map(std::less<uint16_t>(), allocator->Adapter(kArenaAllocProfile)),
784           class_set(std::less<dex::TypeIndex>(), allocator->Adapter(kArenaAllocProfile)),
785           num_type_ids(num_types),
786           num_method_ids(num_methods),
787           bitmap_storage(allocator->Adapter(kArenaAllocProfile)),
788           is_for_boot_image(for_boot_image) {
789       bitmap_storage.resize(ComputeBitmapStorage(is_for_boot_image, num_method_ids));
790       if (!bitmap_storage.empty()) {
791         method_bitmap =
792             BitMemoryRegion(MemoryRegion(
793                 &bitmap_storage[0],
794                 bitmap_storage.size()),
795                 0,
796                 ComputeBitmapBits(is_for_boot_image, num_method_ids));
797       }
798     }
799 
ComputeBitmapBitsDexFileData800     static size_t ComputeBitmapBits(bool is_for_boot_image, uint32_t num_method_ids) {
801       size_t flag_bitmap_index = FlagBitmapIndex(is_for_boot_image
802           ? MethodHotness::kFlagLastBoot
803           : MethodHotness::kFlagLastRegular);
804       return num_method_ids * (flag_bitmap_index + 1);
805     }
ComputeBitmapStorageDexFileData806     static size_t ComputeBitmapStorage(bool is_for_boot_image, uint32_t num_method_ids) {
807       return RoundUp(ComputeBitmapBits(is_for_boot_image, num_method_ids), kBitsPerByte) /
808           kBitsPerByte;
809     }
810 
811     bool operator==(const DexFileData& other) const {
812       return checksum == other.checksum &&
813           num_method_ids == other.num_method_ids &&
814           method_map == other.method_map &&
815           class_set == other.class_set &&
816           BitMemoryRegion::Equals(method_bitmap, other.method_bitmap);
817     }
818 
819     // Mark a method as executed at least once.
820     bool AddMethod(MethodHotness::Flag flags, size_t index);
821 
MergeBitmapDexFileData822     void MergeBitmap(const DexFileData& other) {
823       DCHECK_EQ(bitmap_storage.size(), other.bitmap_storage.size());
824       for (size_t i = 0; i < bitmap_storage.size(); ++i) {
825         bitmap_storage[i] |= other.bitmap_storage[i];
826       }
827     }
828 
829     void SetMethodHotness(size_t index, MethodHotness::Flag flags);
830     MethodHotness GetHotnessInfo(uint32_t dex_method_index) const;
831 
IsStartupMethodDexFileData832     bool IsStartupMethod(uint32_t method_index) const {
833       DCHECK_LT(method_index, num_method_ids);
834       return method_bitmap.LoadBit(
835           MethodFlagBitmapIndex(MethodHotness::Flag::kFlagStartup, method_index));
836     }
837 
IsPostStartupMethodDexFileData838     bool IsPostStartupMethod(uint32_t method_index) const {
839       DCHECK_LT(method_index, num_method_ids);
840       return method_bitmap.LoadBit(
841           MethodFlagBitmapIndex(MethodHotness::Flag::kFlagPostStartup, method_index));
842     }
843 
IsHotMethodDexFileData844     bool IsHotMethod(uint32_t method_index) const {
845       DCHECK_LT(method_index, num_method_ids);
846       return method_map.find(method_index) != method_map.end();
847     }
848 
IsMethodInProfileDexFileData849     bool IsMethodInProfile(uint32_t method_index) const {
850       DCHECK_LT(method_index, num_method_ids);
851       bool has_flag = false;
852       ForMethodBitmapHotnessFlags([&](MethodHotness::Flag flag) {
853         if (method_bitmap.LoadBit(MethodFlagBitmapIndex(
854                 static_cast<MethodHotness::Flag>(flag), method_index))) {
855           has_flag = true;
856           return false;
857         }
858         return true;
859       });
860       return has_flag || IsHotMethod(method_index);
861     }
862 
863     bool ContainsClass(dex::TypeIndex type_index) const;
864 
865     uint32_t ClassesDataSize() const;
866     void WriteClasses(SafeBuffer& buffer) const;
867     ProfileLoadStatus ReadClasses(
868         SafeBuffer& buffer,
869         const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
870         std::string* error);
871     static ProfileLoadStatus SkipClasses(SafeBuffer& buffer, std::string* error);
872 
873     uint32_t MethodsDataSize(/*out*/ uint16_t* method_flags = nullptr,
874                              /*out*/ size_t* saved_bitmap_bit_size = nullptr) const;
875     void WriteMethods(SafeBuffer& buffer) const;
876     ProfileLoadStatus ReadMethods(
877         SafeBuffer& buffer,
878         const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
879         std::string* error);
880     static ProfileLoadStatus SkipMethods(SafeBuffer& buffer, std::string* error);
881 
882     // The allocator used to allocate new inline cache maps.
883     ArenaAllocator* const allocator_;
884     // The profile key this data belongs to.
885     std::string profile_key;
886     // The profile index of this dex file (matches ClassReference#dex_profile_index).
887     ProfileIndexType profile_index;
888     // The dex checksum.
889     uint32_t checksum;
890     // The methods' profile information.
891     MethodMap method_map;
892     // The classes which have been profiled. Note that these don't necessarily include
893     // all the classes that can be found in the inline caches reference.
894     ArenaSet<dex::TypeIndex> class_set;
895     // Find the inline caches of the the given method index. Add an empty entry if
896     // no previous data is found.
897     InlineCacheMap* FindOrAddHotMethod(uint16_t method_index);
898     // Num type ids.
899     uint32_t num_type_ids;
900     // Num method ids.
901     uint32_t num_method_ids;
902     ArenaVector<uint8_t> bitmap_storage;
903     BitMemoryRegion method_bitmap;
904     bool is_for_boot_image;
905 
906    private:
907     template <typename Fn>
ForMethodBitmapHotnessFlagsDexFileData908     void ForMethodBitmapHotnessFlags(Fn fn) const {
909       uint32_t lastFlag = is_for_boot_image
910           ? MethodHotness::kFlagLastBoot
911           : MethodHotness::kFlagLastRegular;
912       for (uint32_t flag = MethodHotness::kFlagFirst; flag <= lastFlag; flag = flag << 1) {
913         if (flag == MethodHotness::kFlagHot) {
914           // There's no bit for hotness in the bitmap.
915           // We store the hotness by recording the method in the method list.
916           continue;
917         }
918         bool cont = fn(enum_cast<MethodHotness::Flag>(flag));
919         if (!cont) {
920           break;
921         }
922       }
923     }
924 
MethodFlagBitmapIndexDexFileData925     size_t MethodFlagBitmapIndex(MethodHotness::Flag flag, size_t method_index) const {
926       DCHECK_LT(method_index, num_method_ids);
927       // The format is [startup bitmap][post startup bitmap][AmStartup][...]
928       // This compresses better than ([startup bit][post startup bit])*
929       return method_index + FlagBitmapIndex(flag) * num_method_ids;
930     }
931 
FlagBitmapIndexDexFileData932     static size_t FlagBitmapIndex(MethodHotness::Flag flag) {
933       DCHECK(flag != MethodHotness::kFlagHot);
934       DCHECK(IsPowerOfTwo(static_cast<uint32_t>(flag)));
935       // We arrange the method flags in order, starting with the startup flag.
936       // The kFlagHot is not encoded in the bitmap and thus not expected as an
937       // argument here. Since all the other flags start at 1 we have to subtract
938       // one from the power of 2.
939       return WhichPowerOf2(static_cast<uint32_t>(flag)) - 1;
940     }
941 
942     static void WriteClassSet(SafeBuffer& buffer, const ArenaSet<dex::TypeIndex>& class_set);
943 
944     uint16_t GetUsedBitmapFlags() const;
945   };
946 
947   // Return the profile data for the given profile key or null if the dex location
948   // already exists but has a different checksum
949   DexFileData* GetOrAddDexFileData(const std::string& profile_key,
950                                    uint32_t checksum,
951                                    uint32_t num_type_ids,
952                                    uint32_t num_method_ids);
953 
GetOrAddDexFileData(const DexFile * dex_file,const ProfileSampleAnnotation & annotation)954   DexFileData* GetOrAddDexFileData(const DexFile* dex_file,
955                                    const ProfileSampleAnnotation& annotation) {
956     return GetOrAddDexFileData(GetProfileDexFileAugmentedKey(dex_file->GetLocation(), annotation),
957                                dex_file->GetLocationChecksum(),
958                                dex_file->NumTypeIds(),
959                                dex_file->NumMethodIds());
960   }
961 
962   // Return the dex data associated with the given profile key or null if the profile
963   // doesn't contain the key.
964   const DexFileData* FindDexData(const std::string& profile_key,
965                                  uint32_t checksum,
966                                  bool verify_checksum = true) const;
967   // Same as FindDexData but performs the searching using the given annotation:
968   //   - If the annotation is kNone then the search ignores it and only looks at the base keys.
969   //     In this case only the first matching dex is searched.
970   //   - If the annotation is not kNone, the augmented key is constructed and used to invoke
971   //     the regular FindDexData.
972   const DexFileData* FindDexDataUsingAnnotations(
973       const DexFile* dex_file,
974       const ProfileSampleAnnotation& annotation) const;
975 
976   // Same as FindDexDataUsingAnnotations but extracts the data for all annotations.
977   void FindAllDexData(
978       const DexFile* dex_file,
979       /*out*/ std::vector<const ProfileCompilationInfo::DexFileData*>* result) const;
980 
981   // Add a new extra descriptor. Returns kMaxExtraDescriptors on failure.
982   ExtraDescriptorIndex AddExtraDescriptor(std::string_view extra_descriptor);
983 
984   // Parsing functionality.
985 
986   ProfileLoadStatus OpenSource(int32_t fd,
987                                /*out*/ std::unique_ptr<ProfileSource>* source,
988                                /*out*/ std::string* error);
989 
990   ProfileLoadStatus ReadSectionData(ProfileSource& source,
991                                     const FileSectionInfo& section_info,
992                                     /*out*/ SafeBuffer* buffer,
993                                     /*out*/ std::string* error);
994 
995   ProfileLoadStatus ReadDexFilesSection(
996       ProfileSource& source,
997       const FileSectionInfo& section_info,
998       const ProfileLoadFilterFn& filter_fn,
999       /*out*/ dchecked_vector<ProfileIndexType>* dex_profile_index_remap,
1000       /*out*/ std::string* error);
1001 
1002   ProfileLoadStatus ReadExtraDescriptorsSection(
1003       ProfileSource& source,
1004       const FileSectionInfo& section_info,
1005       /*out*/ dchecked_vector<ExtraDescriptorIndex>* extra_descriptors_remap,
1006       /*out*/ std::string* error);
1007 
1008   ProfileLoadStatus ReadClassesSection(
1009       ProfileSource& source,
1010       const FileSectionInfo& section_info,
1011       const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1012       const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1013       /*out*/ std::string* error);
1014 
1015   ProfileLoadStatus ReadMethodsSection(
1016       ProfileSource& source,
1017       const FileSectionInfo& section_info,
1018       const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1019       const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1020       /*out*/ std::string* error);
1021 
1022   // Entry point for profile loading functionality.
1023   ProfileLoadStatus LoadInternal(
1024       int32_t fd,
1025       std::string* error,
1026       bool merge_classes = true,
1027       const ProfileLoadFilterFn& filter_fn = ProfileFilterFnAcceptAll);
1028 
1029   // Find the data for the dex_pc in the inline cache. Adds an empty entry
1030   // if no previous data exists.
1031   static DexPcData* FindOrAddDexPc(InlineCacheMap* inline_cache, uint32_t dex_pc);
1032 
1033   // Initializes the profile version to the desired one.
1034   void InitProfileVersionInternal(const uint8_t version[]);
1035 
1036   // Returns the threshold size (in bytes) which will trigger save/load warnings.
1037   size_t GetSizeWarningThresholdBytes() const;
1038   // Returns the threshold size (in bytes) which will cause save/load failures.
1039   size_t GetSizeErrorThresholdBytes() const;
1040 
1041   // Implementation of `GetProfileDexFileBaseKey()` but returning a subview
1042   // referencing the same underlying data to avoid excessive heap allocations.
1043   static std::string_view GetProfileDexFileBaseKeyView(std::string_view dex_location);
1044 
1045   // Implementation of `GetBaseKeyFromAugmentedKey()` but returning a subview
1046   // referencing the same underlying data to avoid excessive heap allocations.
1047   static std::string_view GetBaseKeyViewFromAugmentedKey(std::string_view dex_location);
1048 
1049   // Returns the augmented profile key associated with the given dex location.
1050   // The return key will contain a serialized form of the information from the provided
1051   // annotation. If the annotation is ProfileSampleAnnotation::kNone then no extra info is
1052   // added to the key and this method is equivalent to GetProfileDexFileBaseKey.
1053   static std::string GetProfileDexFileAugmentedKey(const std::string& dex_location,
1054                                                    const ProfileSampleAnnotation& annotation);
1055 
1056   // Migrates the annotation from an augmented key to a base key.
1057   static std::string MigrateAnnotationInfo(const std::string& base_key,
1058                                            const std::string& augmented_key);
1059 
1060   friend class ProfileCompilationInfoTest;
1061   friend class CompilerDriverProfileTest;
1062   friend class ProfileAssistantTest;
1063   friend class Dex2oatLayoutTest;
1064 
1065   MallocArenaPool default_arena_pool_;
1066   ArenaAllocator allocator_;
1067 
1068   // Vector containing the actual profile info.
1069   // The vector index is the profile index of the dex data and
1070   // matched DexFileData::profile_index.
1071   ArenaVector<std::unique_ptr<DexFileData>> info_;
1072 
1073   // Cache mapping profile keys to profile index.
1074   // This is used to speed up searches since it avoids iterating
1075   // over the info_ vector when searching by profile key.
1076   // The backing storage for the `string_view` is the associated `DexFileData`.
1077   ArenaSafeMap<const std::string_view, ProfileIndexType> profile_key_map_;
1078 
1079   // Additional descriptors for referencing types not present in a dex files's `TypeId`s.
1080   dchecked_vector<std::string> extra_descriptors_;
1081   ExtraDescriptorHashSet extra_descriptors_indexes_;
1082 
1083   // The version of the profile.
1084   uint8_t version_[kProfileVersionSize];
1085 };
1086 
1087 /**
1088  * Flatten profile data that list all methods and type references together
1089  * with their metadata (such as flags or annotation list).
1090  */
1091 class FlattenProfileData {
1092  public:
1093   class ItemMetadata {
1094    public:
1095     ItemMetadata();
1096     ItemMetadata(const ItemMetadata& other);
1097 
GetFlags()1098     uint16_t GetFlags() const {
1099       return flags_;
1100     }
1101 
GetAnnotations()1102     const std::list<ProfileCompilationInfo::ProfileSampleAnnotation>& GetAnnotations() const {
1103       return annotations_;
1104     }
1105 
AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag)1106     void AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag) {
1107       flags_ |= flag;
1108     }
1109 
HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag)1110     bool HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag) const {
1111       return (flags_ & flag) != 0;
1112     }
1113 
1114    private:
1115     // will be 0 for classes and MethodHotness::Flags for methods.
1116     uint16_t flags_;
1117     // This is a list that may contain duplicates after a merge operation.
1118     // It represents that a method was used multiple times across different devices.
1119     std::list<ProfileCompilationInfo::ProfileSampleAnnotation> annotations_;
1120 
1121     friend class ProfileCompilationInfo;
1122     friend class FlattenProfileData;
1123   };
1124 
1125   FlattenProfileData();
1126 
GetMethodData()1127   const SafeMap<MethodReference, ItemMetadata>& GetMethodData() const {
1128     return method_metadata_;
1129   }
1130 
GetClassData()1131   const SafeMap<TypeReference, ItemMetadata>& GetClassData() const {
1132     return class_metadata_;
1133   }
1134 
GetMaxAggregationForMethods()1135   uint32_t GetMaxAggregationForMethods() const {
1136     return max_aggregation_for_methods_;
1137   }
1138 
GetMaxAggregationForClasses()1139   uint32_t GetMaxAggregationForClasses() const {
1140     return max_aggregation_for_classes_;
1141   }
1142 
1143   void MergeData(const FlattenProfileData& other);
1144 
1145  private:
1146   // Method data.
1147   SafeMap<MethodReference, ItemMetadata> method_metadata_;
1148   // Class data.
1149   SafeMap<TypeReference, ItemMetadata> class_metadata_;
1150   // Maximum aggregation counter for all methods.
1151   // This is essentially a cache equal to the max size of any method's annotation set.
1152   // It avoids the traversal of all the methods which can be quite expensive.
1153   uint32_t max_aggregation_for_methods_;
1154   // Maximum aggregation counter for all classes.
1155   // Simillar to max_aggregation_for_methods_.
1156   uint32_t max_aggregation_for_classes_;
1157 
1158   friend class ProfileCompilationInfo;
1159 };
1160 
1161 struct ProfileCompilationInfo::DexReferenceDumper {
GetProfileKeyDexReferenceDumper1162   const std::string& GetProfileKey() {
1163     return dex_file_data->profile_key;
1164   }
1165 
GetDexChecksumDexReferenceDumper1166   uint32_t GetDexChecksum() const {
1167     return dex_file_data->checksum;
1168   }
1169 
GetNumTypeIdsDexReferenceDumper1170   uint32_t GetNumTypeIds() const {
1171     return dex_file_data->num_type_ids;
1172   }
1173 
GetNumMethodIdsDexReferenceDumper1174   uint32_t GetNumMethodIds() const {
1175     return dex_file_data->num_method_ids;
1176   }
1177 
1178   const DexFileData* dex_file_data;
1179 };
1180 
DumpDexReference(ProfileIndexType profile_index)1181 inline ProfileCompilationInfo::DexReferenceDumper ProfileCompilationInfo::DumpDexReference(
1182     ProfileIndexType profile_index) const {
1183   return DexReferenceDumper{info_[profile_index].get()};
1184 }
1185 
1186 std::ostream& operator<<(std::ostream& stream, ProfileCompilationInfo::DexReferenceDumper dumper);
1187 
1188 }  // namespace art
1189 
1190 #endif  // ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
1191