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   }
179 
180   DP("RTLs loaded!\n");
181 
182   return;
183 }
184 
185 ////////////////////////////////////////////////////////////////////////////////
186 // Functionality for registering libs
187 
188 static void RegisterImageIntoTranslationTable(TranslationTable &TT,
189                                               RTLInfoTy &RTL,
190                                               __tgt_device_image *image) {
191 
192   // same size, as when we increase one, we also increase the other.
193   assert(TT.TargetsTable.size() == TT.TargetsImages.size() &&
194          "We should have as many images as we have tables!");
195 
196   // Resize the Targets Table and Images to accommodate the new targets if
197   // required
198   unsigned TargetsTableMinimumSize = RTL.Idx + RTL.NumberOfDevices;
199 
200   if (TT.TargetsTable.size() < TargetsTableMinimumSize) {
201     TT.TargetsImages.resize(TargetsTableMinimumSize, 0);
202     TT.TargetsTable.resize(TargetsTableMinimumSize, 0);
203   }
204 
205   // Register the image in all devices for this target type.
206   for (int32_t i = 0; i < RTL.NumberOfDevices; ++i) {
207     // If we are changing the image we are also invalidating the target table.
208     if (TT.TargetsImages[RTL.Idx + i] != image) {
209       TT.TargetsImages[RTL.Idx + i] = image;
210       TT.TargetsTable[RTL.Idx + i] = 0; // lazy initialization of target table.
211     }
212   }
213 }
214 
215 ////////////////////////////////////////////////////////////////////////////////
216 // Functionality for registering Ctors/Dtors
217 
218 static void RegisterGlobalCtorsDtorsForImage(__tgt_bin_desc *desc,
219                                              __tgt_device_image *img,
220                                              RTLInfoTy *RTL) {
221 
222   for (int32_t i = 0; i < RTL->NumberOfDevices; ++i) {
223     DeviceTy &Device = PM->Devices[RTL->Idx + i];
224     Device.PendingGlobalsMtx.lock();
225     Device.HasPendingGlobals = true;
226     for (__tgt_offload_entry *entry = img->EntriesBegin;
227          entry != img->EntriesEnd; ++entry) {
228       if (entry->flags & OMP_DECLARE_TARGET_CTOR) {
229         DP("Adding ctor " DPxMOD " to the pending list.\n",
230            DPxPTR(entry->addr));
231         Device.PendingCtorsDtors[desc].PendingCtors.push_back(entry->addr);
232       } else if (entry->flags & OMP_DECLARE_TARGET_DTOR) {
233         // Dtors are pushed in reverse order so they are executed from end
234         // to beginning when unregistering the library!
235         DP("Adding dtor " DPxMOD " to the pending list.\n",
236            DPxPTR(entry->addr));
237         Device.PendingCtorsDtors[desc].PendingDtors.push_front(entry->addr);
238       }
239 
240       if (entry->flags & OMP_DECLARE_TARGET_LINK) {
241         DP("The \"link\" attribute is not yet supported!\n");
242       }
243     }
244     Device.PendingGlobalsMtx.unlock();
245   }
246 }
247 
248 void RTLsTy::RegisterRequires(int64_t flags) {
249   // TODO: add more elaborate check.
250   // Minimal check: only set requires flags if previous value
251   // is undefined. This ensures that only the first call to this
252   // function will set the requires flags. All subsequent calls
253   // will be checked for compatibility.
254   assert(flags != OMP_REQ_UNDEFINED &&
255          "illegal undefined flag for requires directive!");
256   if (RequiresFlags == OMP_REQ_UNDEFINED) {
257     RequiresFlags = flags;
258     return;
259   }
260 
261   // If multiple compilation units are present enforce
262   // consistency across all of them for require clauses:
263   //  - reverse_offload
264   //  - unified_address
265   //  - unified_shared_memory
266   if ((RequiresFlags & OMP_REQ_REVERSE_OFFLOAD) !=
267       (flags & OMP_REQ_REVERSE_OFFLOAD)) {
268     FATAL_MESSAGE0(
269         1, "'#pragma omp requires reverse_offload' not used consistently!");
270   }
271   if ((RequiresFlags & OMP_REQ_UNIFIED_ADDRESS) !=
272       (flags & OMP_REQ_UNIFIED_ADDRESS)) {
273     FATAL_MESSAGE0(
274         1, "'#pragma omp requires unified_address' not used consistently!");
275   }
276   if ((RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) !=
277       (flags & OMP_REQ_UNIFIED_SHARED_MEMORY)) {
278     FATAL_MESSAGE0(
279         1,
280         "'#pragma omp requires unified_shared_memory' not used consistently!");
281   }
282 
283   // TODO: insert any other missing checks
284 
285   DP("New requires flags %" PRId64 " compatible with existing %" PRId64 "!\n",
286      flags, RequiresFlags);
287 }
288 
289 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) {
290   PM->RTLsMtx.lock();
291   // Register the images with the RTLs that understand them, if any.
292   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
293     // Obtain the image.
294     __tgt_device_image *img = &desc->DeviceImages[i];
295 
296     RTLInfoTy *FoundRTL = NULL;
297 
298     // Scan the RTLs that have associated images until we find one that supports
299     // the current image.
300     for (auto &R : AllRTLs) {
301       if (!R.is_valid_binary(img)) {
302         DP("Image " DPxMOD " is NOT compatible with RTL %s!\n",
303            DPxPTR(img->ImageStart), R.RTLName.c_str());
304         continue;
305       }
306 
307       DP("Image " DPxMOD " is compatible with RTL %s!\n",
308          DPxPTR(img->ImageStart), R.RTLName.c_str());
309 
310       // If this RTL is not already in use, initialize it.
311       if (!R.isUsed) {
312         // Initialize the device information for the RTL we are about to use.
313         DeviceTy device(&R);
314         size_t Start = PM->Devices.size();
315         PM->Devices.resize(Start + R.NumberOfDevices, device);
316         for (int32_t device_id = 0; device_id < R.NumberOfDevices;
317              device_id++) {
318           // global device ID
319           PM->Devices[Start + device_id].DeviceID = Start + device_id;
320           // RTL local device ID
321           PM->Devices[Start + device_id].RTLDeviceID = device_id;
322         }
323 
324         // Initialize the index of this RTL and save it in the used RTLs.
325         R.Idx = (UsedRTLs.empty())
326                     ? 0
327                     : UsedRTLs.back()->Idx + UsedRTLs.back()->NumberOfDevices;
328         assert((size_t)R.Idx == Start &&
329                "RTL index should equal the number of devices used so far.");
330         R.isUsed = true;
331         UsedRTLs.push_back(&R);
332 
333         DP("RTL " DPxMOD " has index %d!\n", DPxPTR(R.LibraryHandler), R.Idx);
334       }
335 
336       // Initialize (if necessary) translation table for this library.
337       PM->TrlTblMtx.lock();
338       if (!PM->HostEntriesBeginToTransTable.count(desc->HostEntriesBegin)) {
339         PM->HostEntriesBeginRegistrationOrder.push_back(desc->HostEntriesBegin);
340         TranslationTable &TransTable =
341             (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
342         TransTable.HostTable.EntriesBegin = desc->HostEntriesBegin;
343         TransTable.HostTable.EntriesEnd = desc->HostEntriesEnd;
344       }
345 
346       // Retrieve translation table for this library.
347       TranslationTable &TransTable =
348           (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
349 
350       DP("Registering image " DPxMOD " with RTL %s!\n", DPxPTR(img->ImageStart),
351          R.RTLName.c_str());
352       RegisterImageIntoTranslationTable(TransTable, R, img);
353       PM->TrlTblMtx.unlock();
354       FoundRTL = &R;
355 
356       // Load ctors/dtors for static objects
357       RegisterGlobalCtorsDtorsForImage(desc, img, FoundRTL);
358 
359       // if an RTL was found we are done - proceed to register the next image
360       break;
361     }
362 
363     if (!FoundRTL) {
364       DP("No RTL found for image " DPxMOD "!\n", DPxPTR(img->ImageStart));
365     }
366   }
367   PM->RTLsMtx.unlock();
368 
369   DP("Done registering entries!\n");
370 }
371 
372 void RTLsTy::UnregisterLib(__tgt_bin_desc *desc) {
373   DP("Unloading target library!\n");
374 
375   PM->RTLsMtx.lock();
376   // Find which RTL understands each image, if any.
377   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
378     // Obtain the image.
379     __tgt_device_image *img = &desc->DeviceImages[i];
380 
381     RTLInfoTy *FoundRTL = NULL;
382 
383     // Scan the RTLs that have associated images until we find one that supports
384     // the current image. We only need to scan RTLs that are already being used.
385     for (auto *R : UsedRTLs) {
386 
387       assert(R->isUsed && "Expecting used RTLs.");
388 
389       if (!R->is_valid_binary(img)) {
390         DP("Image " DPxMOD " is NOT compatible with RTL " DPxMOD "!\n",
391            DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
392         continue;
393       }
394 
395       DP("Image " DPxMOD " is compatible with RTL " DPxMOD "!\n",
396          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
397 
398       FoundRTL = R;
399 
400       // Execute dtors for static objects if the device has been used, i.e.
401       // if its PendingCtors list has been emptied.
402       for (int32_t i = 0; i < FoundRTL->NumberOfDevices; ++i) {
403         DeviceTy &Device = PM->Devices[FoundRTL->Idx + i];
404         Device.PendingGlobalsMtx.lock();
405         if (Device.PendingCtorsDtors[desc].PendingCtors.empty()) {
406           AsyncInfoTy AsyncInfo(Device);
407           for (auto &dtor : Device.PendingCtorsDtors[desc].PendingDtors) {
408             int rc = target(nullptr, Device, dtor, 0, nullptr, nullptr, nullptr,
409                             nullptr, nullptr, nullptr, 1, 1, true /*team*/,
410                             AsyncInfo);
411             if (rc != OFFLOAD_SUCCESS) {
412               DP("Running destructor " DPxMOD " failed.\n", DPxPTR(dtor));
413             }
414           }
415           // Remove this library's entry from PendingCtorsDtors
416           Device.PendingCtorsDtors.erase(desc);
417           // All constructors have been issued, wait for them now.
418           if (AsyncInfo.synchronize() != OFFLOAD_SUCCESS)
419             DP("Failed synchronizing destructors kernels.\n");
420         }
421         Device.PendingGlobalsMtx.unlock();
422       }
423 
424       DP("Unregistered image " DPxMOD " from RTL " DPxMOD "!\n",
425          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
426 
427       break;
428     }
429 
430     // if no RTL was found proceed to unregister the next image
431     if (!FoundRTL) {
432       DP("No RTLs in use support the image " DPxMOD "!\n",
433          DPxPTR(img->ImageStart));
434     }
435   }
436   PM->RTLsMtx.unlock();
437   DP("Done unregistering images!\n");
438 
439   // Remove entries from PM->HostPtrToTableMap
440   PM->TblMapMtx.lock();
441   for (__tgt_offload_entry *cur = desc->HostEntriesBegin;
442        cur < desc->HostEntriesEnd; ++cur) {
443     PM->HostPtrToTableMap.erase(cur->addr);
444   }
445 
446   // Remove translation table for this descriptor.
447   auto TransTable =
448       PM->HostEntriesBeginToTransTable.find(desc->HostEntriesBegin);
449   if (TransTable != PM->HostEntriesBeginToTransTable.end()) {
450     DP("Removing translation table for descriptor " DPxMOD "\n",
451        DPxPTR(desc->HostEntriesBegin));
452     PM->HostEntriesBeginToTransTable.erase(TransTable);
453   } else {
454     DP("Translation table for descriptor " DPxMOD " cannot be found, probably "
455        "it has been already removed.\n",
456        DPxPTR(desc->HostEntriesBegin));
457   }
458 
459   PM->TblMapMtx.unlock();
460 
461   // TODO: Remove RTL and the devices it manages if it's not used anymore?
462   // TODO: Write some RTL->unload_image(...) function?
463 
464   DP("Done unregistering library!\n");
465 }
466