1 //===----------- rtl.cpp - Target independent OpenMP target RTL -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Functionality for handling RTL plugins.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "rtl.h"
14 #include "device.h"
15 #include "private.h"
16 
17 #include <cassert>
18 #include <cstdlib>
19 #include <cstring>
20 #include <dlfcn.h>
21 #include <mutex>
22 #include <string>
23 
24 // List of all plugins that can support offloading.
25 static const char *RTLNames[] = {
26     /* PowerPC target       */ "libomptarget.rtl.ppc64.so",
27     /* x86_64 target        */ "libomptarget.rtl.x86_64.so",
28     /* CUDA target          */ "libomptarget.rtl.cuda.so",
29     /* AArch64 target       */ "libomptarget.rtl.aarch64.so",
30     /* SX-Aurora VE target  */ "libomptarget.rtl.ve.so",
31     /* AMDGPU target        */ "libomptarget.rtl.amdgpu.so",
32     /* Remote target        */ "libomptarget.rtl.rpc.so",
33 };
34 
35 PluginManager *PM;
36 
37 #if OMPTARGET_PROFILE_ENABLED
38 static char *ProfileTraceFile = nullptr;
39 #endif
40 
41 __attribute__((constructor(101))) void init() {
42   DP("Init target library!\n");
43   PM = new PluginManager();
44 
45 #ifdef OMPTARGET_PROFILE_ENABLED
46   ProfileTraceFile = getenv("LIBOMPTARGET_PROFILE");
47   // TODO: add a configuration option for time granularity
48   if (ProfileTraceFile)
49     llvm::timeTraceProfilerInitialize(500 /* us */, "libomptarget");
50 #endif
51 }
52 
53 __attribute__((destructor(101))) void deinit() {
54   DP("Deinit target library!\n");
55   delete PM;
56 
57 #ifdef OMPTARGET_PROFILE_ENABLED
58   if (ProfileTraceFile) {
59     // TODO: add env var for file output
60     if (auto E = llvm::timeTraceProfilerWrite(ProfileTraceFile, "-"))
61       fprintf(stderr, "Error writing out the time trace\n");
62 
63     llvm::timeTraceProfilerCleanup();
64   }
65 #endif
66 }
67 
68 void RTLsTy::LoadRTLs() {
69   // Parse environment variable OMP_TARGET_OFFLOAD (if set)
70   PM->TargetOffloadPolicy =
71       (kmp_target_offload_kind_t)__kmpc_get_target_offload();
72   if (PM->TargetOffloadPolicy == tgt_disabled) {
73     return;
74   }
75 
76   DP("Loading RTLs...\n");
77 
78   // Attempt to open all the plugins and, if they exist, check if the interface
79   // is correct and if they are supporting any devices.
80   for (auto *Name : RTLNames) {
81     DP("Loading library '%s'...\n", Name);
82     void *dynlib_handle = dlopen(Name, RTLD_NOW);
83 
84     if (!dynlib_handle) {
85       // Library does not exist or cannot be found.
86       DP("Unable to load library '%s': %s!\n", Name, dlerror());
87       continue;
88     }
89 
90     DP("Successfully loaded library '%s'!\n", Name);
91 
92     AllRTLs.emplace_back();
93 
94     // Retrieve the RTL information from the runtime library.
95     RTLInfoTy &R = AllRTLs.back();
96 
97     bool ValidPlugin = true;
98 
99     if (!(*((void **)&R.is_valid_binary) =
100               dlsym(dynlib_handle, "__tgt_rtl_is_valid_binary")))
101       ValidPlugin = false;
102     if (!(*((void **)&R.number_of_devices) =
103               dlsym(dynlib_handle, "__tgt_rtl_number_of_devices")))
104       ValidPlugin = false;
105     if (!(*((void **)&R.init_device) =
106               dlsym(dynlib_handle, "__tgt_rtl_init_device")))
107       ValidPlugin = false;
108     if (!(*((void **)&R.load_binary) =
109               dlsym(dynlib_handle, "__tgt_rtl_load_binary")))
110       ValidPlugin = false;
111     if (!(*((void **)&R.data_alloc) =
112               dlsym(dynlib_handle, "__tgt_rtl_data_alloc")))
113       ValidPlugin = false;
114     if (!(*((void **)&R.data_submit) =
115               dlsym(dynlib_handle, "__tgt_rtl_data_submit")))
116       ValidPlugin = false;
117     if (!(*((void **)&R.data_retrieve) =
118               dlsym(dynlib_handle, "__tgt_rtl_data_retrieve")))
119       ValidPlugin = false;
120     if (!(*((void **)&R.data_delete) =
121               dlsym(dynlib_handle, "__tgt_rtl_data_delete")))
122       ValidPlugin = false;
123     if (!(*((void **)&R.run_region) =
124               dlsym(dynlib_handle, "__tgt_rtl_run_target_region")))
125       ValidPlugin = false;
126     if (!(*((void **)&R.run_team_region) =
127               dlsym(dynlib_handle, "__tgt_rtl_run_target_team_region")))
128       ValidPlugin = false;
129 
130     // Invalid plugin
131     if (!ValidPlugin) {
132       DP("Invalid plugin as necessary interface is not found.\n");
133       AllRTLs.pop_back();
134       continue;
135     }
136 
137     // No devices are supported by this RTL?
138     if (!(R.NumberOfDevices = R.number_of_devices())) {
139       // The RTL is invalid! Will pop the object from the RTLs list.
140       DP("No devices supported in this RTL\n");
141       AllRTLs.pop_back();
142       continue;
143     }
144 
145     R.LibraryHandler = dynlib_handle;
146 
147 #ifdef OMPTARGET_DEBUG
148     R.RTLName = Name;
149 #endif
150 
151     DP("Registering RTL %s supporting %d devices!\n", R.RTLName.c_str(),
152        R.NumberOfDevices);
153 
154     // Optional functions
155     *((void **)&R.init_requires) =
156         dlsym(dynlib_handle, "__tgt_rtl_init_requires");
157     *((void **)&R.data_submit_async) =
158         dlsym(dynlib_handle, "__tgt_rtl_data_submit_async");
159     *((void **)&R.data_retrieve_async) =
160         dlsym(dynlib_handle, "__tgt_rtl_data_retrieve_async");
161     *((void **)&R.run_region_async) =
162         dlsym(dynlib_handle, "__tgt_rtl_run_target_region_async");
163     *((void **)&R.run_team_region_async) =
164         dlsym(dynlib_handle, "__tgt_rtl_run_target_team_region_async");
165     *((void **)&R.synchronize) = dlsym(dynlib_handle, "__tgt_rtl_synchronize");
166     *((void **)&R.data_exchange) =
167         dlsym(dynlib_handle, "__tgt_rtl_data_exchange");
168     *((void **)&R.data_exchange_async) =
169         dlsym(dynlib_handle, "__tgt_rtl_data_exchange_async");
170     *((void **)&R.is_data_exchangable) =
171         dlsym(dynlib_handle, "__tgt_rtl_is_data_exchangable");
172     *((void **)&R.register_lib) =
173         dlsym(dynlib_handle, "__tgt_rtl_register_lib");
174     *((void **)&R.unregister_lib) =
175         dlsym(dynlib_handle, "__tgt_rtl_unregister_lib");
176     *((void **)&R.supports_empty_images) =
177         dlsym(dynlib_handle, "__tgt_rtl_supports_empty_images");
178     *((void **)&R.set_info_flag) =
179         dlsym(dynlib_handle, "__tgt_rtl_set_info_flag");
180   }
181 
182   DP("RTLs loaded!\n");
183 
184   return;
185 }
186 
187 ////////////////////////////////////////////////////////////////////////////////
188 // Functionality for registering libs
189 
190 static void RegisterImageIntoTranslationTable(TranslationTable &TT,
191                                               RTLInfoTy &RTL,
192                                               __tgt_device_image *image) {
193 
194   // same size, as when we increase one, we also increase the other.
195   assert(TT.TargetsTable.size() == TT.TargetsImages.size() &&
196          "We should have as many images as we have tables!");
197 
198   // Resize the Targets Table and Images to accommodate the new targets if
199   // required
200   unsigned TargetsTableMinimumSize = RTL.Idx + RTL.NumberOfDevices;
201 
202   if (TT.TargetsTable.size() < TargetsTableMinimumSize) {
203     TT.TargetsImages.resize(TargetsTableMinimumSize, 0);
204     TT.TargetsTable.resize(TargetsTableMinimumSize, 0);
205   }
206 
207   // Register the image in all devices for this target type.
208   for (int32_t i = 0; i < RTL.NumberOfDevices; ++i) {
209     // If we are changing the image we are also invalidating the target table.
210     if (TT.TargetsImages[RTL.Idx + i] != image) {
211       TT.TargetsImages[RTL.Idx + i] = image;
212       TT.TargetsTable[RTL.Idx + i] = 0; // lazy initialization of target table.
213     }
214   }
215 }
216 
217 ////////////////////////////////////////////////////////////////////////////////
218 // Functionality for registering Ctors/Dtors
219 
220 static void RegisterGlobalCtorsDtorsForImage(__tgt_bin_desc *desc,
221                                              __tgt_device_image *img,
222                                              RTLInfoTy *RTL) {
223 
224   for (int32_t i = 0; i < RTL->NumberOfDevices; ++i) {
225     DeviceTy &Device = PM->Devices[RTL->Idx + i];
226     Device.PendingGlobalsMtx.lock();
227     Device.HasPendingGlobals = true;
228     for (__tgt_offload_entry *entry = img->EntriesBegin;
229          entry != img->EntriesEnd; ++entry) {
230       if (entry->flags & OMP_DECLARE_TARGET_CTOR) {
231         DP("Adding ctor " DPxMOD " to the pending list.\n",
232            DPxPTR(entry->addr));
233         Device.PendingCtorsDtors[desc].PendingCtors.push_back(entry->addr);
234       } else if (entry->flags & OMP_DECLARE_TARGET_DTOR) {
235         // Dtors are pushed in reverse order so they are executed from end
236         // to beginning when unregistering the library!
237         DP("Adding dtor " DPxMOD " to the pending list.\n",
238            DPxPTR(entry->addr));
239         Device.PendingCtorsDtors[desc].PendingDtors.push_front(entry->addr);
240       }
241 
242       if (entry->flags & OMP_DECLARE_TARGET_LINK) {
243         DP("The \"link\" attribute is not yet supported!\n");
244       }
245     }
246     Device.PendingGlobalsMtx.unlock();
247   }
248 }
249 
250 void RTLsTy::RegisterRequires(int64_t flags) {
251   // TODO: add more elaborate check.
252   // Minimal check: only set requires flags if previous value
253   // is undefined. This ensures that only the first call to this
254   // function will set the requires flags. All subsequent calls
255   // will be checked for compatibility.
256   assert(flags != OMP_REQ_UNDEFINED &&
257          "illegal undefined flag for requires directive!");
258   if (RequiresFlags == OMP_REQ_UNDEFINED) {
259     RequiresFlags = flags;
260     return;
261   }
262 
263   // If multiple compilation units are present enforce
264   // consistency across all of them for require clauses:
265   //  - reverse_offload
266   //  - unified_address
267   //  - unified_shared_memory
268   if ((RequiresFlags & OMP_REQ_REVERSE_OFFLOAD) !=
269       (flags & OMP_REQ_REVERSE_OFFLOAD)) {
270     FATAL_MESSAGE0(
271         1, "'#pragma omp requires reverse_offload' not used consistently!");
272   }
273   if ((RequiresFlags & OMP_REQ_UNIFIED_ADDRESS) !=
274       (flags & OMP_REQ_UNIFIED_ADDRESS)) {
275     FATAL_MESSAGE0(
276         1, "'#pragma omp requires unified_address' not used consistently!");
277   }
278   if ((RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) !=
279       (flags & OMP_REQ_UNIFIED_SHARED_MEMORY)) {
280     FATAL_MESSAGE0(
281         1,
282         "'#pragma omp requires unified_shared_memory' not used consistently!");
283   }
284 
285   // TODO: insert any other missing checks
286 
287   DP("New requires flags %" PRId64 " compatible with existing %" PRId64 "!\n",
288      flags, RequiresFlags);
289 }
290 
291 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) {
292   PM->RTLsMtx.lock();
293   // Register the images with the RTLs that understand them, if any.
294   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
295     // Obtain the image.
296     __tgt_device_image *img = &desc->DeviceImages[i];
297 
298     RTLInfoTy *FoundRTL = NULL;
299 
300     // Scan the RTLs that have associated images until we find one that supports
301     // the current image.
302     for (auto &R : AllRTLs) {
303       if (!R.is_valid_binary(img)) {
304         DP("Image " DPxMOD " is NOT compatible with RTL %s!\n",
305            DPxPTR(img->ImageStart), R.RTLName.c_str());
306         continue;
307       }
308 
309       DP("Image " DPxMOD " is compatible with RTL %s!\n",
310          DPxPTR(img->ImageStart), R.RTLName.c_str());
311 
312       // If this RTL is not already in use, initialize it.
313       if (!R.isUsed) {
314         // Initialize the device information for the RTL we are about to use.
315         DeviceTy device(&R);
316         size_t Start = PM->Devices.size();
317         PM->Devices.resize(Start + R.NumberOfDevices, device);
318         for (int32_t device_id = 0; device_id < R.NumberOfDevices;
319              device_id++) {
320           // global device ID
321           PM->Devices[Start + device_id].DeviceID = Start + device_id;
322           // RTL local device ID
323           PM->Devices[Start + device_id].RTLDeviceID = device_id;
324         }
325 
326         // Initialize the index of this RTL and save it in the used RTLs.
327         R.Idx = (UsedRTLs.empty())
328                     ? 0
329                     : UsedRTLs.back()->Idx + UsedRTLs.back()->NumberOfDevices;
330         assert((size_t)R.Idx == Start &&
331                "RTL index should equal the number of devices used so far.");
332         R.isUsed = true;
333         UsedRTLs.push_back(&R);
334 
335         DP("RTL " DPxMOD " has index %d!\n", DPxPTR(R.LibraryHandler), R.Idx);
336       }
337 
338       // Initialize (if necessary) translation table for this library.
339       PM->TrlTblMtx.lock();
340       if (!PM->HostEntriesBeginToTransTable.count(desc->HostEntriesBegin)) {
341         PM->HostEntriesBeginRegistrationOrder.push_back(desc->HostEntriesBegin);
342         TranslationTable &TransTable =
343             (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
344         TransTable.HostTable.EntriesBegin = desc->HostEntriesBegin;
345         TransTable.HostTable.EntriesEnd = desc->HostEntriesEnd;
346       }
347 
348       // Retrieve translation table for this library.
349       TranslationTable &TransTable =
350           (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
351 
352       DP("Registering image " DPxMOD " with RTL %s!\n", DPxPTR(img->ImageStart),
353          R.RTLName.c_str());
354       RegisterImageIntoTranslationTable(TransTable, R, img);
355       PM->TrlTblMtx.unlock();
356       FoundRTL = &R;
357 
358       // Load ctors/dtors for static objects
359       RegisterGlobalCtorsDtorsForImage(desc, img, FoundRTL);
360 
361       // if an RTL was found we are done - proceed to register the next image
362       break;
363     }
364 
365     if (!FoundRTL) {
366       DP("No RTL found for image " DPxMOD "!\n", DPxPTR(img->ImageStart));
367     }
368   }
369   PM->RTLsMtx.unlock();
370 
371   DP("Done registering entries!\n");
372 }
373 
374 void RTLsTy::UnregisterLib(__tgt_bin_desc *desc) {
375   DP("Unloading target library!\n");
376 
377   PM->RTLsMtx.lock();
378   // Find which RTL understands each image, if any.
379   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
380     // Obtain the image.
381     __tgt_device_image *img = &desc->DeviceImages[i];
382 
383     RTLInfoTy *FoundRTL = NULL;
384 
385     // Scan the RTLs that have associated images until we find one that supports
386     // the current image. We only need to scan RTLs that are already being used.
387     for (auto *R : UsedRTLs) {
388 
389       assert(R->isUsed && "Expecting used RTLs.");
390 
391       if (!R->is_valid_binary(img)) {
392         DP("Image " DPxMOD " is NOT compatible with RTL " DPxMOD "!\n",
393            DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
394         continue;
395       }
396 
397       DP("Image " DPxMOD " is compatible with RTL " DPxMOD "!\n",
398          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
399 
400       FoundRTL = R;
401 
402       // Execute dtors for static objects if the device has been used, i.e.
403       // if its PendingCtors list has been emptied.
404       for (int32_t i = 0; i < FoundRTL->NumberOfDevices; ++i) {
405         DeviceTy &Device = PM->Devices[FoundRTL->Idx + i];
406         Device.PendingGlobalsMtx.lock();
407         if (Device.PendingCtorsDtors[desc].PendingCtors.empty()) {
408           AsyncInfoTy AsyncInfo(Device);
409           for (auto &dtor : Device.PendingCtorsDtors[desc].PendingDtors) {
410             int rc = target(nullptr, Device, dtor, 0, nullptr, nullptr, nullptr,
411                             nullptr, nullptr, nullptr, 1, 1, true /*team*/,
412                             AsyncInfo);
413             if (rc != OFFLOAD_SUCCESS) {
414               DP("Running destructor " DPxMOD " failed.\n", DPxPTR(dtor));
415             }
416           }
417           // Remove this library's entry from PendingCtorsDtors
418           Device.PendingCtorsDtors.erase(desc);
419           // All constructors have been issued, wait for them now.
420           if (AsyncInfo.synchronize() != OFFLOAD_SUCCESS)
421             DP("Failed synchronizing destructors kernels.\n");
422         }
423         Device.PendingGlobalsMtx.unlock();
424       }
425 
426       DP("Unregistered image " DPxMOD " from RTL " DPxMOD "!\n",
427          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
428 
429       break;
430     }
431 
432     // if no RTL was found proceed to unregister the next image
433     if (!FoundRTL) {
434       DP("No RTLs in use support the image " DPxMOD "!\n",
435          DPxPTR(img->ImageStart));
436     }
437   }
438   PM->RTLsMtx.unlock();
439   DP("Done unregistering images!\n");
440 
441   // Remove entries from PM->HostPtrToTableMap
442   PM->TblMapMtx.lock();
443   for (__tgt_offload_entry *cur = desc->HostEntriesBegin;
444        cur < desc->HostEntriesEnd; ++cur) {
445     PM->HostPtrToTableMap.erase(cur->addr);
446   }
447 
448   // Remove translation table for this descriptor.
449   auto TransTable =
450       PM->HostEntriesBeginToTransTable.find(desc->HostEntriesBegin);
451   if (TransTable != PM->HostEntriesBeginToTransTable.end()) {
452     DP("Removing translation table for descriptor " DPxMOD "\n",
453        DPxPTR(desc->HostEntriesBegin));
454     PM->HostEntriesBeginToTransTable.erase(TransTable);
455   } else {
456     DP("Translation table for descriptor " DPxMOD " cannot be found, probably "
457        "it has been already removed.\n",
458        DPxPTR(desc->HostEntriesBegin));
459   }
460 
461   PM->TblMapMtx.unlock();
462 
463   // TODO: Remove RTL and the devices it manages if it's not used anymore?
464   // TODO: Write some RTL->unload_image(...) function?
465 
466   DP("Done unregistering library!\n");
467 }
468