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