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