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