xref: /aosp_15_r20/art/libprofile/profile/profile_compilation_info.h (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
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-inl.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, bool flush = false);
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, bool flush = false);
481 
482   // A fallback implementation of `Save` that uses a flock.
483   bool SaveFallback(const std::string& filename, uint64_t* bytes_written, bool flush = false);
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".
677   const char* GetTypeDescriptor(const DexFile* dex_file,
678                                 dex::TypeIndex type_index,
679                                 /*out*/ size_t* utf8_length = nullptr) const {
680     DCHECK(type_index.IsValid());
681     uint32_t num_type_ids = dex_file->NumTypeIds();
682     if (type_index.index_ < num_type_ids) {
683       uint32_t utf16_length;
684       const char* descriptor = dex_file->GetStringDataAndUtf16Length(
685           dex_file->GetTypeId(type_index).descriptor_idx_, &utf16_length);
686       if (utf8_length != nullptr) {
687         *utf8_length = DexFile::Utf8Length(descriptor, utf16_length);
688       }
689       return descriptor;
690     } else {
691       const std::string& descriptor = extra_descriptors_[type_index.index_ - num_type_ids];
692       if (utf8_length != nullptr) {
693         *utf8_length = descriptor.length();
694       }
695       return descriptor.c_str();
696     }
697   }
698 
699   // Return the version of this profile.
700   const uint8_t* GetVersion() const;
701 
702   // Extracts the data that the profile has on the given dex files:
703   //  - for each method and class, a list of the corresponding annotations and flags
704   //  - the maximum number of aggregations for classes and classes across dex files with different
705   //    annotations (essentially this sums up how many different packages used the corresponding
706   //    method). This information is reconstructible from the other two pieces of info, but it's
707   //    convenient to have it precomputed.
708   std::unique_ptr<FlattenProfileData> ExtractProfileData(
709       const std::vector<std::unique_ptr<const DexFile>>& dex_files) const;
710 
711  private:
712   // Helper classes.
713   class FileHeader;
714   class FileSectionInfo;
715   enum class FileSectionType : uint32_t;
716   enum class ProfileLoadStatus : uint32_t;
717   class ProfileSource;
718   class SafeBuffer;
719 
720   // Extra descriptors are used to reference classes with `TypeIndex` between the dex
721   // file's `NumTypeIds()` and the `DexFile::kDexNoIndex16`. The range of usable
722   // extra descriptor indexes is therefore also limited by `DexFile::kDexNoIndex16`.
723   using ExtraDescriptorIndex = uint16_t;
724   static constexpr ExtraDescriptorIndex kMaxExtraDescriptors = DexFile::kDexNoIndex16;
725 
726   class ExtraDescriptorIndexEmpty {
727    public:
MakeEmpty(ExtraDescriptorIndex & index)728     void MakeEmpty(ExtraDescriptorIndex& index) const {
729       index = kMaxExtraDescriptors;
730     }
IsEmpty(const ExtraDescriptorIndex & index)731     bool IsEmpty(const ExtraDescriptorIndex& index) const {
732       return index == kMaxExtraDescriptors;
733     }
734   };
735 
736   class ExtraDescriptorHash {
737    public:
ExtraDescriptorHash(const dchecked_vector<std::string> * extra_descriptors)738     explicit ExtraDescriptorHash(const dchecked_vector<std::string>* extra_descriptors)
739         : extra_descriptors_(extra_descriptors) {}
740 
operator()741     size_t operator()(const ExtraDescriptorIndex& index) const {
742       std::string_view str = (*extra_descriptors_)[index];
743       return (*this)(str);
744     }
745 
operator()746     size_t operator()(std::string_view str) const {
747       return DataHash()(str);
748     }
749 
750    private:
751     const dchecked_vector<std::string>* extra_descriptors_;
752   };
753 
754   class ExtraDescriptorEquals {
755    public:
ExtraDescriptorEquals(const dchecked_vector<std::string> * extra_descriptors)756     explicit ExtraDescriptorEquals(const dchecked_vector<std::string>* extra_descriptors)
757         : extra_descriptors_(extra_descriptors) {}
758 
operator()759     size_t operator()(const ExtraDescriptorIndex& lhs, const ExtraDescriptorIndex& rhs) const {
760       DCHECK_EQ(lhs == rhs, (*this)(lhs, (*extra_descriptors_)[rhs]));
761       return lhs == rhs;
762     }
763 
operator()764     size_t operator()(const ExtraDescriptorIndex& lhs, std::string_view rhs_str) const {
765       std::string_view lhs_str = (*extra_descriptors_)[lhs];
766       return lhs_str == rhs_str;
767     }
768 
769    private:
770     const dchecked_vector<std::string>* extra_descriptors_;
771   };
772 
773   using ExtraDescriptorHashSet = HashSet<ExtraDescriptorIndex,
774                                          ExtraDescriptorIndexEmpty,
775                                          ExtraDescriptorHash,
776                                          ExtraDescriptorEquals>;
777 
778   // Internal representation of the profile information belonging to a dex file.
779   // Note that we could do without the profile_index (the index of the dex file
780   // in the profile) field in this struct because we can infer it from
781   // `profile_key_map_` and `info_`. However, it makes the profiles logic much
782   // simpler if we have the profile index here as well.
783   struct DexFileData : public DeletableArenaObject<kArenaAllocProfile> {
DexFileDataDexFileData784     DexFileData(ArenaAllocator* allocator,
785                 const std::string& key,
786                 uint32_t location_checksum,
787                 uint16_t index,
788                 uint32_t num_types,
789                 uint32_t num_methods,
790                 bool for_boot_image)
791         : allocator_(allocator),
792           profile_key(key),
793           profile_index(index),
794           checksum(location_checksum),
795           method_map(std::less<uint16_t>(), allocator->Adapter(kArenaAllocProfile)),
796           class_set(std::less<dex::TypeIndex>(), allocator->Adapter(kArenaAllocProfile)),
797           num_type_ids(num_types),
798           num_method_ids(num_methods),
799           bitmap_storage(allocator->Adapter(kArenaAllocProfile)),
800           is_for_boot_image(for_boot_image) {
801       bitmap_storage.resize(ComputeBitmapStorage(is_for_boot_image, num_method_ids));
802       if (!bitmap_storage.empty()) {
803         method_bitmap =
804             BitMemoryRegion(MemoryRegion(
805                 &bitmap_storage[0],
806                 bitmap_storage.size()),
807                 0,
808                 ComputeBitmapBits(is_for_boot_image, num_method_ids));
809       }
810     }
811 
ComputeBitmapBitsDexFileData812     static size_t ComputeBitmapBits(bool is_for_boot_image, uint32_t num_method_ids) {
813       size_t flag_bitmap_index = FlagBitmapIndex(is_for_boot_image
814           ? MethodHotness::kFlagLastBoot
815           : MethodHotness::kFlagLastRegular);
816       return num_method_ids * (flag_bitmap_index + 1);
817     }
ComputeBitmapStorageDexFileData818     static size_t ComputeBitmapStorage(bool is_for_boot_image, uint32_t num_method_ids) {
819       return RoundUp(ComputeBitmapBits(is_for_boot_image, num_method_ids), kBitsPerByte) /
820           kBitsPerByte;
821     }
822 
823     bool operator==(const DexFileData& other) const {
824       return checksum == other.checksum &&
825           num_method_ids == other.num_method_ids &&
826           method_map == other.method_map &&
827           class_set == other.class_set &&
828           BitMemoryRegion::Equals(method_bitmap, other.method_bitmap);
829     }
830 
831     // Mark a method as executed at least once.
832     bool AddMethod(MethodHotness::Flag flags, size_t index);
833 
MergeBitmapDexFileData834     void MergeBitmap(const DexFileData& other) {
835       DCHECK_EQ(bitmap_storage.size(), other.bitmap_storage.size());
836       for (size_t i = 0; i < bitmap_storage.size(); ++i) {
837         bitmap_storage[i] |= other.bitmap_storage[i];
838       }
839     }
840 
841     void SetMethodHotness(size_t index, MethodHotness::Flag flags);
842     MethodHotness GetHotnessInfo(uint32_t dex_method_index) const;
843 
IsStartupMethodDexFileData844     bool IsStartupMethod(uint32_t method_index) const {
845       DCHECK_LT(method_index, num_method_ids);
846       return method_bitmap.LoadBit(
847           MethodFlagBitmapIndex(MethodHotness::Flag::kFlagStartup, method_index));
848     }
849 
IsPostStartupMethodDexFileData850     bool IsPostStartupMethod(uint32_t method_index) const {
851       DCHECK_LT(method_index, num_method_ids);
852       return method_bitmap.LoadBit(
853           MethodFlagBitmapIndex(MethodHotness::Flag::kFlagPostStartup, method_index));
854     }
855 
IsHotMethodDexFileData856     bool IsHotMethod(uint32_t method_index) const {
857       DCHECK_LT(method_index, num_method_ids);
858       return method_map.find(method_index) != method_map.end();
859     }
860 
IsMethodInProfileDexFileData861     bool IsMethodInProfile(uint32_t method_index) const {
862       DCHECK_LT(method_index, num_method_ids);
863       bool has_flag = false;
864       ForMethodBitmapHotnessFlags([&](MethodHotness::Flag flag) {
865         if (method_bitmap.LoadBit(MethodFlagBitmapIndex(
866                 static_cast<MethodHotness::Flag>(flag), method_index))) {
867           has_flag = true;
868           return false;
869         }
870         return true;
871       });
872       return has_flag || IsHotMethod(method_index);
873     }
874 
875     bool ContainsClass(dex::TypeIndex type_index) const;
876 
877     uint32_t ClassesDataSize() const;
878     void WriteClasses(SafeBuffer& buffer) const;
879     ProfileLoadStatus ReadClasses(
880         SafeBuffer& buffer,
881         const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
882         std::string* error);
883     static ProfileLoadStatus SkipClasses(SafeBuffer& buffer, std::string* error);
884 
885     uint32_t MethodsDataSize(/*out*/ uint16_t* method_flags = nullptr,
886                              /*out*/ size_t* saved_bitmap_bit_size = nullptr) const;
887     void WriteMethods(SafeBuffer& buffer) const;
888     ProfileLoadStatus ReadMethods(
889         SafeBuffer& buffer,
890         const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
891         std::string* error);
892     static ProfileLoadStatus SkipMethods(SafeBuffer& buffer, std::string* error);
893 
894     // The allocator used to allocate new inline cache maps.
895     ArenaAllocator* const allocator_;
896     // The profile key this data belongs to.
897     std::string profile_key;
898     // The profile index of this dex file (matches ClassReference#dex_profile_index).
899     ProfileIndexType profile_index;
900     // The dex checksum.
901     uint32_t checksum;
902     // The methods' profile information.
903     MethodMap method_map;
904     // The classes which have been profiled. Note that these don't necessarily include
905     // all the classes that can be found in the inline caches reference.
906     ArenaSet<dex::TypeIndex> class_set;
907     // Find the inline caches of the the given method index. Add an empty entry if
908     // no previous data is found.
909     InlineCacheMap* FindOrAddHotMethod(uint16_t method_index);
910     // Num type ids.
911     uint32_t num_type_ids;
912     // Num method ids.
913     uint32_t num_method_ids;
914     ArenaVector<uint8_t> bitmap_storage;
915     BitMemoryRegion method_bitmap;
916     bool is_for_boot_image;
917 
918    private:
919     template <typename Fn>
ForMethodBitmapHotnessFlagsDexFileData920     void ForMethodBitmapHotnessFlags(Fn fn) const {
921       uint32_t lastFlag = is_for_boot_image
922           ? MethodHotness::kFlagLastBoot
923           : MethodHotness::kFlagLastRegular;
924       for (uint32_t flag = MethodHotness::kFlagFirst; flag <= lastFlag; flag = flag << 1) {
925         if (flag == MethodHotness::kFlagHot) {
926           // There's no bit for hotness in the bitmap.
927           // We store the hotness by recording the method in the method list.
928           continue;
929         }
930         bool cont = fn(enum_cast<MethodHotness::Flag>(flag));
931         if (!cont) {
932           break;
933         }
934       }
935     }
936 
MethodFlagBitmapIndexDexFileData937     size_t MethodFlagBitmapIndex(MethodHotness::Flag flag, size_t method_index) const {
938       DCHECK_LT(method_index, num_method_ids);
939       // The format is [startup bitmap][post startup bitmap][AmStartup][...]
940       // This compresses better than ([startup bit][post startup bit])*
941       return method_index + FlagBitmapIndex(flag) * num_method_ids;
942     }
943 
FlagBitmapIndexDexFileData944     static size_t FlagBitmapIndex(MethodHotness::Flag flag) {
945       DCHECK(flag != MethodHotness::kFlagHot);
946       DCHECK(IsPowerOfTwo(static_cast<uint32_t>(flag)));
947       // We arrange the method flags in order, starting with the startup flag.
948       // The kFlagHot is not encoded in the bitmap and thus not expected as an
949       // argument here. Since all the other flags start at 1 we have to subtract
950       // one from the power of 2.
951       return WhichPowerOf2(static_cast<uint32_t>(flag)) - 1;
952     }
953 
954     static void WriteClassSet(SafeBuffer& buffer, const ArenaSet<dex::TypeIndex>& class_set);
955 
956     uint16_t GetUsedBitmapFlags() const;
957   };
958 
959   // Return the profile data for the given profile key or null if the dex location
960   // already exists but has a different checksum
961   DexFileData* GetOrAddDexFileData(const std::string& profile_key,
962                                    uint32_t checksum,
963                                    uint32_t num_type_ids,
964                                    uint32_t num_method_ids);
965 
GetOrAddDexFileData(const DexFile * dex_file,const ProfileSampleAnnotation & annotation)966   DexFileData* GetOrAddDexFileData(const DexFile* dex_file,
967                                    const ProfileSampleAnnotation& annotation) {
968     return GetOrAddDexFileData(GetProfileDexFileAugmentedKey(dex_file->GetLocation(), annotation),
969                                dex_file->GetLocationChecksum(),
970                                dex_file->NumTypeIds(),
971                                dex_file->NumMethodIds());
972   }
973 
974   // Return the dex data associated with the given profile key or null if the profile
975   // doesn't contain the key.
976   const DexFileData* FindDexData(const std::string& profile_key,
977                                  uint32_t checksum,
978                                  bool verify_checksum = true) const;
979   // Same as FindDexData but performs the searching using the given annotation:
980   //   - If the annotation is kNone then the search ignores it and only looks at the base keys.
981   //     In this case only the first matching dex is searched.
982   //   - If the annotation is not kNone, the augmented key is constructed and used to invoke
983   //     the regular FindDexData.
984   const DexFileData* FindDexDataUsingAnnotations(
985       const DexFile* dex_file,
986       const ProfileSampleAnnotation& annotation) const;
987 
988   // Same as FindDexDataUsingAnnotations but extracts the data for all annotations.
989   void FindAllDexData(
990       const DexFile* dex_file,
991       /*out*/ std::vector<const ProfileCompilationInfo::DexFileData*>* result) const;
992 
993   // Add a new extra descriptor. Returns kMaxExtraDescriptors on failure.
994   ExtraDescriptorIndex AddExtraDescriptor(std::string_view extra_descriptor);
995 
996   // Parsing functionality.
997 
998   ProfileLoadStatus OpenSource(int32_t fd,
999                                /*out*/ std::unique_ptr<ProfileSource>* source,
1000                                /*out*/ std::string* error);
1001 
1002   ProfileLoadStatus ReadSectionData(ProfileSource& source,
1003                                     const FileSectionInfo& section_info,
1004                                     /*out*/ SafeBuffer* buffer,
1005                                     /*out*/ std::string* error);
1006 
1007   ProfileLoadStatus ReadDexFilesSection(
1008       ProfileSource& source,
1009       const FileSectionInfo& section_info,
1010       const ProfileLoadFilterFn& filter_fn,
1011       /*out*/ dchecked_vector<ProfileIndexType>* dex_profile_index_remap,
1012       /*out*/ std::string* error);
1013 
1014   ProfileLoadStatus ReadExtraDescriptorsSection(
1015       ProfileSource& source,
1016       const FileSectionInfo& section_info,
1017       /*out*/ dchecked_vector<ExtraDescriptorIndex>* extra_descriptors_remap,
1018       /*out*/ std::string* error);
1019 
1020   ProfileLoadStatus ReadClassesSection(
1021       ProfileSource& source,
1022       const FileSectionInfo& section_info,
1023       const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1024       const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1025       /*out*/ std::string* error);
1026 
1027   ProfileLoadStatus ReadMethodsSection(
1028       ProfileSource& source,
1029       const FileSectionInfo& section_info,
1030       const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1031       const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1032       /*out*/ std::string* error);
1033 
1034   // Entry point for profile loading functionality.
1035   ProfileLoadStatus LoadInternal(
1036       int32_t fd,
1037       std::string* error,
1038       bool merge_classes = true,
1039       const ProfileLoadFilterFn& filter_fn = ProfileFilterFnAcceptAll);
1040 
1041   // Find the data for the dex_pc in the inline cache. Adds an empty entry
1042   // if no previous data exists.
1043   static DexPcData* FindOrAddDexPc(InlineCacheMap* inline_cache, uint32_t dex_pc);
1044 
1045   // Initializes the profile version to the desired one.
1046   void InitProfileVersionInternal(const uint8_t version[]);
1047 
1048   // Returns the threshold size (in bytes) which will trigger save/load warnings.
1049   size_t GetSizeWarningThresholdBytes() const;
1050   // Returns the threshold size (in bytes) which will cause save/load failures.
1051   size_t GetSizeErrorThresholdBytes() const;
1052 
1053   // Implementation of `GetProfileDexFileBaseKey()` but returning a subview
1054   // referencing the same underlying data to avoid excessive heap allocations.
1055   static std::string_view GetProfileDexFileBaseKeyView(std::string_view dex_location);
1056 
1057   // Implementation of `GetBaseKeyFromAugmentedKey()` but returning a subview
1058   // referencing the same underlying data to avoid excessive heap allocations.
1059   static std::string_view GetBaseKeyViewFromAugmentedKey(std::string_view dex_location);
1060 
1061   // Returns the augmented profile key associated with the given dex location.
1062   // The return key will contain a serialized form of the information from the provided
1063   // annotation. If the annotation is ProfileSampleAnnotation::kNone then no extra info is
1064   // added to the key and this method is equivalent to GetProfileDexFileBaseKey.
1065   static std::string GetProfileDexFileAugmentedKey(const std::string& dex_location,
1066                                                    const ProfileSampleAnnotation& annotation);
1067 
1068   // Migrates the annotation from an augmented key to a base key.
1069   static std::string MigrateAnnotationInfo(const std::string& base_key,
1070                                            const std::string& augmented_key);
1071 
1072   friend class ProfileCompilationInfoTest;
1073   friend class CompilerDriverProfileTest;
1074   friend class ProfileAssistantTest;
1075   friend class Dex2oatLayoutTest;
1076 
1077   MallocArenaPool default_arena_pool_;
1078   ArenaAllocator allocator_;
1079 
1080   // Vector containing the actual profile info.
1081   // The vector index is the profile index of the dex data and
1082   // matched DexFileData::profile_index.
1083   ArenaVector<std::unique_ptr<DexFileData>> info_;
1084 
1085   // Cache mapping profile keys to profile index.
1086   // This is used to speed up searches since it avoids iterating
1087   // over the info_ vector when searching by profile key.
1088   // The backing storage for the `string_view` is the associated `DexFileData`.
1089   ArenaSafeMap<const std::string_view, ProfileIndexType> profile_key_map_;
1090 
1091   // Additional descriptors for referencing types not present in a dex files's `TypeId`s.
1092   dchecked_vector<std::string> extra_descriptors_;
1093   ExtraDescriptorHashSet extra_descriptors_indexes_;
1094 
1095   // The version of the profile.
1096   uint8_t version_[kProfileVersionSize];
1097 };
1098 
1099 /**
1100  * Flatten profile data that list all methods and type references together
1101  * with their metadata (such as flags or annotation list).
1102  */
1103 class FlattenProfileData {
1104  public:
1105   class ItemMetadata {
1106    public:
1107     struct InlineCacheInfo {
1108       bool is_megamorphic_ = false;
1109       bool is_missing_types_ = false;
1110       std::set<std::string> classes_;
1111     };
1112 
1113     ItemMetadata();
1114     ItemMetadata(const ItemMetadata& other) = default;
1115 
GetFlags()1116     uint16_t GetFlags() const {
1117       return flags_;
1118     }
1119 
GetAnnotations()1120     const std::list<ProfileCompilationInfo::ProfileSampleAnnotation>& GetAnnotations() const {
1121       return annotations_;
1122     }
1123 
AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag)1124     void AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag) {
1125       flags_ |= flag;
1126     }
1127 
HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag)1128     bool HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag) const {
1129       return (flags_ & flag) != 0;
1130     }
1131 
1132     // Extracts inline cache info for the given method into this instance.
1133     // Note that this will collapse all ICs with the same receiver type.
1134     void ExtractInlineCacheInfo(const ProfileCompilationInfo& profile_info,
1135                                 const DexFile* dex_file,
1136                                 uint16_t dex_method_idx);
1137 
1138     // Merges the inline cache info from the other metadata into this instance.
1139     void MergeInlineCacheInfo(
1140         const SafeMap<TypeReference, InlineCacheInfo, TypeReferenceValueComparator>& other);
1141 
GetInlineCache()1142     const SafeMap<TypeReference, InlineCacheInfo, TypeReferenceValueComparator>& GetInlineCache()
1143         const {
1144       return inline_cache_;
1145     }
1146 
1147    private:
1148     // will be 0 for classes and MethodHotness::Flags for methods.
1149     uint16_t flags_;
1150     // This is a list that may contain duplicates after a merge operation.
1151     // It represents that a method was used multiple times across different devices.
1152     std::list<ProfileCompilationInfo::ProfileSampleAnnotation> annotations_;
1153     // Inline cache map for methods.
1154     SafeMap<TypeReference, InlineCacheInfo, TypeReferenceValueComparator> inline_cache_;
1155 
1156     friend class ProfileCompilationInfo;
1157     friend class FlattenProfileData;
1158   };
1159 
1160   FlattenProfileData();
1161 
GetMethodData()1162   const SafeMap<MethodReference, ItemMetadata>& GetMethodData() const {
1163     return method_metadata_;
1164   }
1165 
GetClassData()1166   const SafeMap<TypeReference, ItemMetadata>& GetClassData() const {
1167     return class_metadata_;
1168   }
1169 
GetMaxAggregationForMethods()1170   uint32_t GetMaxAggregationForMethods() const {
1171     return max_aggregation_for_methods_;
1172   }
1173 
GetMaxAggregationForClasses()1174   uint32_t GetMaxAggregationForClasses() const {
1175     return max_aggregation_for_classes_;
1176   }
1177 
1178   void MergeData(const FlattenProfileData& other);
1179 
1180  private:
1181   // Method data.
1182   SafeMap<MethodReference, ItemMetadata> method_metadata_;
1183   // Class data.
1184   SafeMap<TypeReference, ItemMetadata> class_metadata_;
1185   // Maximum aggregation counter for all methods.
1186   // This is essentially a cache equal to the max size of any method's annotation set.
1187   // It avoids the traversal of all the methods which can be quite expensive.
1188   uint32_t max_aggregation_for_methods_;
1189   // Maximum aggregation counter for all classes.
1190   // Simillar to max_aggregation_for_methods_.
1191   uint32_t max_aggregation_for_classes_;
1192 
1193   friend class ProfileCompilationInfo;
1194 };
1195 
1196 struct ProfileCompilationInfo::DexReferenceDumper {
GetProfileKeyDexReferenceDumper1197   const std::string& GetProfileKey() {
1198     return dex_file_data->profile_key;
1199   }
1200 
GetDexChecksumDexReferenceDumper1201   uint32_t GetDexChecksum() const {
1202     return dex_file_data->checksum;
1203   }
1204 
GetNumTypeIdsDexReferenceDumper1205   uint32_t GetNumTypeIds() const {
1206     return dex_file_data->num_type_ids;
1207   }
1208 
GetNumMethodIdsDexReferenceDumper1209   uint32_t GetNumMethodIds() const {
1210     return dex_file_data->num_method_ids;
1211   }
1212 
1213   const DexFileData* dex_file_data;
1214 };
1215 
DumpDexReference(ProfileIndexType profile_index)1216 inline ProfileCompilationInfo::DexReferenceDumper ProfileCompilationInfo::DumpDexReference(
1217     ProfileIndexType profile_index) const {
1218   return DexReferenceDumper{info_[profile_index].get()};
1219 }
1220 
1221 std::ostream& operator<<(std::ostream& stream, ProfileCompilationInfo::DexReferenceDumper dumper);
1222 
1223 }  // namespace art
1224 
1225 #endif  // ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
1226