File: | tools/lli/lli.cpp |
Warning: | line 395, column 5 Use of memory after it is freed |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This utility provides a simple wrapper around the LLVM Execution Engines, | |||
11 | // which allow the direct execution of LLVM programs through a Just-In-Time | |||
12 | // compiler, or through an interpreter if no JIT is available for this platform. | |||
13 | // | |||
14 | //===----------------------------------------------------------------------===// | |||
15 | ||||
16 | #include "OrcLazyJIT.h" | |||
17 | #include "RemoteJITUtils.h" | |||
18 | #include "llvm/ADT/StringExtras.h" | |||
19 | #include "llvm/ADT/Triple.h" | |||
20 | #include "llvm/Bitcode/BitcodeReader.h" | |||
21 | #include "llvm/CodeGen/CommandFlags.def" | |||
22 | #include "llvm/CodeGen/LinkAllCodegenComponents.h" | |||
23 | #include "llvm/ExecutionEngine/GenericValue.h" | |||
24 | #include "llvm/ExecutionEngine/Interpreter.h" | |||
25 | #include "llvm/ExecutionEngine/JITEventListener.h" | |||
26 | #include "llvm/ExecutionEngine/MCJIT.h" | |||
27 | #include "llvm/ExecutionEngine/ObjectCache.h" | |||
28 | #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h" | |||
29 | #include "llvm/ExecutionEngine/OrcMCJITReplacement.h" | |||
30 | #include "llvm/ExecutionEngine/SectionMemoryManager.h" | |||
31 | #include "llvm/IR/IRBuilder.h" | |||
32 | #include "llvm/IR/LLVMContext.h" | |||
33 | #include "llvm/IR/Module.h" | |||
34 | #include "llvm/IR/Type.h" | |||
35 | #include "llvm/IR/TypeBuilder.h" | |||
36 | #include "llvm/IRReader/IRReader.h" | |||
37 | #include "llvm/Object/Archive.h" | |||
38 | #include "llvm/Object/ObjectFile.h" | |||
39 | #include "llvm/Support/CommandLine.h" | |||
40 | #include "llvm/Support/Debug.h" | |||
41 | #include "llvm/Support/DynamicLibrary.h" | |||
42 | #include "llvm/Support/Format.h" | |||
43 | #include "llvm/Support/ManagedStatic.h" | |||
44 | #include "llvm/Support/MathExtras.h" | |||
45 | #include "llvm/Support/Memory.h" | |||
46 | #include "llvm/Support/MemoryBuffer.h" | |||
47 | #include "llvm/Support/Path.h" | |||
48 | #include "llvm/Support/PluginLoader.h" | |||
49 | #include "llvm/Support/PrettyStackTrace.h" | |||
50 | #include "llvm/Support/Process.h" | |||
51 | #include "llvm/Support/Program.h" | |||
52 | #include "llvm/Support/Signals.h" | |||
53 | #include "llvm/Support/SourceMgr.h" | |||
54 | #include "llvm/Support/TargetSelect.h" | |||
55 | #include "llvm/Support/raw_ostream.h" | |||
56 | #include "llvm/Transforms/Instrumentation.h" | |||
57 | #include <cerrno> | |||
58 | ||||
59 | #ifdef __CYGWIN__ | |||
60 | #include <cygwin/version.h> | |||
61 | #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 | |||
62 | #define DO_NOTHING_ATEXIT 1 | |||
63 | #endif | |||
64 | #endif | |||
65 | ||||
66 | using namespace llvm; | |||
67 | ||||
68 | #define DEBUG_TYPE"lli" "lli" | |||
69 | ||||
70 | namespace { | |||
71 | ||||
72 | enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy }; | |||
73 | ||||
74 | cl::opt<std::string> | |||
75 | InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); | |||
76 | ||||
77 | cl::list<std::string> | |||
78 | InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); | |||
79 | ||||
80 | cl::opt<bool> ForceInterpreter("force-interpreter", | |||
81 | cl::desc("Force interpretation: disable JIT"), | |||
82 | cl::init(false)); | |||
83 | ||||
84 | cl::opt<JITKind> UseJITKind("jit-kind", | |||
85 | cl::desc("Choose underlying JIT kind."), | |||
86 | cl::init(JITKind::MCJIT), | |||
87 | cl::values( | |||
88 | clEnumValN(JITKind::MCJIT, "mcjit",llvm::cl::OptionEnumValue { "mcjit", int(JITKind::MCJIT), "MCJIT" } | |||
89 | "MCJIT")llvm::cl::OptionEnumValue { "mcjit", int(JITKind::MCJIT), "MCJIT" }, | |||
90 | clEnumValN(JITKind::OrcMCJITReplacement,llvm::cl::OptionEnumValue { "orc-mcjit", int(JITKind::OrcMCJITReplacement ), "Orc-based MCJIT replacement" } | |||
91 | "orc-mcjit",llvm::cl::OptionEnumValue { "orc-mcjit", int(JITKind::OrcMCJITReplacement ), "Orc-based MCJIT replacement" } | |||
92 | "Orc-based MCJIT replacement")llvm::cl::OptionEnumValue { "orc-mcjit", int(JITKind::OrcMCJITReplacement ), "Orc-based MCJIT replacement" }, | |||
93 | clEnumValN(JITKind::OrcLazy,llvm::cl::OptionEnumValue { "orc-lazy", int(JITKind::OrcLazy) , "Orc-based lazy JIT." } | |||
94 | "orc-lazy",llvm::cl::OptionEnumValue { "orc-lazy", int(JITKind::OrcLazy) , "Orc-based lazy JIT." } | |||
95 | "Orc-based lazy JIT.")llvm::cl::OptionEnumValue { "orc-lazy", int(JITKind::OrcLazy) , "Orc-based lazy JIT." })); | |||
96 | ||||
97 | // The MCJIT supports building for a target address space separate from | |||
98 | // the JIT compilation process. Use a forked process and a copying | |||
99 | // memory manager with IPC to execute using this functionality. | |||
100 | cl::opt<bool> RemoteMCJIT("remote-mcjit", | |||
101 | cl::desc("Execute MCJIT'ed code in a separate process."), | |||
102 | cl::init(false)); | |||
103 | ||||
104 | // Manually specify the child process for remote execution. This overrides | |||
105 | // the simulated remote execution that allocates address space for child | |||
106 | // execution. The child process will be executed and will communicate with | |||
107 | // lli via stdin/stdout pipes. | |||
108 | cl::opt<std::string> | |||
109 | ChildExecPath("mcjit-remote-process", | |||
110 | cl::desc("Specify the filename of the process to launch " | |||
111 | "for remote MCJIT execution. If none is specified," | |||
112 | "\n\tremote execution will be simulated in-process."), | |||
113 | cl::value_desc("filename"), cl::init("")); | |||
114 | ||||
115 | // Determine optimization level. | |||
116 | cl::opt<char> | |||
117 | OptLevel("O", | |||
118 | cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " | |||
119 | "(default = '-O2')"), | |||
120 | cl::Prefix, | |||
121 | cl::ZeroOrMore, | |||
122 | cl::init(' ')); | |||
123 | ||||
124 | cl::opt<std::string> | |||
125 | TargetTriple("mtriple", cl::desc("Override target triple for module")); | |||
126 | ||||
127 | cl::opt<std::string> | |||
128 | EntryFunc("entry-function", | |||
129 | cl::desc("Specify the entry function (default = 'main') " | |||
130 | "of the executable"), | |||
131 | cl::value_desc("function"), | |||
132 | cl::init("main")); | |||
133 | ||||
134 | cl::list<std::string> | |||
135 | ExtraModules("extra-module", | |||
136 | cl::desc("Extra modules to be loaded"), | |||
137 | cl::value_desc("input bitcode")); | |||
138 | ||||
139 | cl::list<std::string> | |||
140 | ExtraObjects("extra-object", | |||
141 | cl::desc("Extra object files to be loaded"), | |||
142 | cl::value_desc("input object")); | |||
143 | ||||
144 | cl::list<std::string> | |||
145 | ExtraArchives("extra-archive", | |||
146 | cl::desc("Extra archive files to be loaded"), | |||
147 | cl::value_desc("input archive")); | |||
148 | ||||
149 | cl::opt<bool> | |||
150 | EnableCacheManager("enable-cache-manager", | |||
151 | cl::desc("Use cache manager to save/load mdoules"), | |||
152 | cl::init(false)); | |||
153 | ||||
154 | cl::opt<std::string> | |||
155 | ObjectCacheDir("object-cache-dir", | |||
156 | cl::desc("Directory to store cached object files " | |||
157 | "(must be user writable)"), | |||
158 | cl::init("")); | |||
159 | ||||
160 | cl::opt<std::string> | |||
161 | FakeArgv0("fake-argv0", | |||
162 | cl::desc("Override the 'argv[0]' value passed into the executing" | |||
163 | " program"), cl::value_desc("executable")); | |||
164 | ||||
165 | cl::opt<bool> | |||
166 | DisableCoreFiles("disable-core-files", cl::Hidden, | |||
167 | cl::desc("Disable emission of core files if possible")); | |||
168 | ||||
169 | cl::opt<bool> | |||
170 | NoLazyCompilation("disable-lazy-compilation", | |||
171 | cl::desc("Disable JIT lazy compilation"), | |||
172 | cl::init(false)); | |||
173 | ||||
174 | cl::opt<bool> | |||
175 | GenerateSoftFloatCalls("soft-float", | |||
176 | cl::desc("Generate software floating point library calls"), | |||
177 | cl::init(false)); | |||
178 | ||||
179 | ExitOnError ExitOnErr; | |||
180 | } | |||
181 | ||||
182 | //===----------------------------------------------------------------------===// | |||
183 | // Object cache | |||
184 | // | |||
185 | // This object cache implementation writes cached objects to disk to the | |||
186 | // directory specified by CacheDir, using a filename provided in the module | |||
187 | // descriptor. The cache tries to load a saved object using that path if the | |||
188 | // file exists. CacheDir defaults to "", in which case objects are cached | |||
189 | // alongside their originating bitcodes. | |||
190 | // | |||
191 | class LLIObjectCache : public ObjectCache { | |||
192 | public: | |||
193 | LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) { | |||
194 | // Add trailing '/' to cache dir if necessary. | |||
195 | if (!this->CacheDir.empty() && | |||
196 | this->CacheDir[this->CacheDir.size() - 1] != '/') | |||
197 | this->CacheDir += '/'; | |||
198 | } | |||
199 | ~LLIObjectCache() override {} | |||
200 | ||||
201 | void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override { | |||
202 | const std::string &ModuleID = M->getModuleIdentifier(); | |||
203 | std::string CacheName; | |||
204 | if (!getCacheFilename(ModuleID, CacheName)) | |||
205 | return; | |||
206 | if (!CacheDir.empty()) { // Create user-defined cache dir. | |||
207 | SmallString<128> dir(sys::path::parent_path(CacheName)); | |||
208 | sys::fs::create_directories(Twine(dir)); | |||
209 | } | |||
210 | std::error_code EC; | |||
211 | raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None); | |||
212 | outfile.write(Obj.getBufferStart(), Obj.getBufferSize()); | |||
213 | outfile.close(); | |||
214 | } | |||
215 | ||||
216 | std::unique_ptr<MemoryBuffer> getObject(const Module* M) override { | |||
217 | const std::string &ModuleID = M->getModuleIdentifier(); | |||
218 | std::string CacheName; | |||
219 | if (!getCacheFilename(ModuleID, CacheName)) | |||
220 | return nullptr; | |||
221 | // Load the object from the cache filename | |||
222 | ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer = | |||
223 | MemoryBuffer::getFile(CacheName, -1, false); | |||
224 | // If the file isn't there, that's OK. | |||
225 | if (!IRObjectBuffer) | |||
226 | return nullptr; | |||
227 | // MCJIT will want to write into this buffer, and we don't want that | |||
228 | // because the file has probably just been mmapped. Instead we make | |||
229 | // a copy. The filed-based buffer will be released when it goes | |||
230 | // out of scope. | |||
231 | return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer()); | |||
232 | } | |||
233 | ||||
234 | private: | |||
235 | std::string CacheDir; | |||
236 | ||||
237 | bool getCacheFilename(const std::string &ModID, std::string &CacheName) { | |||
238 | std::string Prefix("file:"); | |||
239 | size_t PrefixLength = Prefix.length(); | |||
240 | if (ModID.substr(0, PrefixLength) != Prefix) | |||
241 | return false; | |||
242 | std::string CacheSubdir = ModID.substr(PrefixLength); | |||
243 | #if defined(_WIN32) | |||
244 | // Transform "X:\foo" => "/X\foo" for convenience. | |||
245 | if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') { | |||
246 | CacheSubdir[1] = CacheSubdir[0]; | |||
247 | CacheSubdir[0] = '/'; | |||
248 | } | |||
249 | #endif | |||
250 | CacheName = CacheDir + CacheSubdir; | |||
251 | size_t pos = CacheName.rfind('.'); | |||
252 | CacheName.replace(pos, CacheName.length() - pos, ".o"); | |||
253 | return true; | |||
254 | } | |||
255 | }; | |||
256 | ||||
257 | // On Mingw and Cygwin, an external symbol named '__main' is called from the | |||
258 | // generated 'main' function to allow static initialization. To avoid linking | |||
259 | // problems with remote targets (because lli's remote target support does not | |||
260 | // currently handle external linking) we add a secondary module which defines | |||
261 | // an empty '__main' function. | |||
262 | static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context, | |||
263 | StringRef TargetTripleStr) { | |||
264 | IRBuilder<> Builder(Context); | |||
265 | Triple TargetTriple(TargetTripleStr); | |||
266 | ||||
267 | // Create a new module. | |||
268 | std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context); | |||
269 | M->setTargetTriple(TargetTripleStr); | |||
270 | ||||
271 | // Create an empty function named "__main". | |||
272 | Function *Result; | |||
273 | if (TargetTriple.isArch64Bit()) { | |||
274 | Result = Function::Create( | |||
275 | TypeBuilder<int64_t(void), false>::get(Context), | |||
276 | GlobalValue::ExternalLinkage, "__main", M.get()); | |||
277 | } else { | |||
278 | Result = Function::Create( | |||
279 | TypeBuilder<int32_t(void), false>::get(Context), | |||
280 | GlobalValue::ExternalLinkage, "__main", M.get()); | |||
281 | } | |||
282 | BasicBlock *BB = BasicBlock::Create(Context, "__main", Result); | |||
283 | Builder.SetInsertPoint(BB); | |||
284 | Value *ReturnVal; | |||
285 | if (TargetTriple.isArch64Bit()) | |||
286 | ReturnVal = ConstantInt::get(Context, APInt(64, 0)); | |||
287 | else | |||
288 | ReturnVal = ConstantInt::get(Context, APInt(32, 0)); | |||
289 | Builder.CreateRet(ReturnVal); | |||
290 | ||||
291 | // Add this new module to the ExecutionEngine. | |||
292 | EE.addModule(std::move(M)); | |||
293 | } | |||
294 | ||||
295 | CodeGenOpt::Level getOptLevel() { | |||
296 | switch (OptLevel) { | |||
297 | default: | |||
298 | errs() << "lli: Invalid optimization level.\n"; | |||
299 | exit(1); | |||
300 | case '0': return CodeGenOpt::None; | |||
301 | case '1': return CodeGenOpt::Less; | |||
302 | case ' ': | |||
303 | case '2': return CodeGenOpt::Default; | |||
304 | case '3': return CodeGenOpt::Aggressive; | |||
305 | } | |||
306 | llvm_unreachable("Unrecognized opt level.")::llvm::llvm_unreachable_internal("Unrecognized opt level.", "/build/llvm-toolchain-snapshot-7~svn329677/tools/lli/lli.cpp" , 306); | |||
307 | } | |||
308 | ||||
309 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) | |||
310 | static void reportError(SMDiagnostic Err, const char *ProgName) { | |||
311 | Err.print(ProgName, errs()); | |||
312 | exit(1); | |||
313 | } | |||
314 | ||||
315 | //===----------------------------------------------------------------------===// | |||
316 | // main Driver function | |||
317 | // | |||
318 | int main(int argc, char **argv, char * const *envp) { | |||
319 | sys::PrintStackTraceOnErrorSignal(argv[0]); | |||
320 | PrettyStackTraceProgram X(argc, argv); | |||
321 | ||||
322 | atexit(llvm_shutdown); // Call llvm_shutdown() on exit. | |||
323 | ||||
324 | if (argc > 1) | |||
| ||||
325 | ExitOnErr.setBanner(std::string(argv[0]) + ": "); | |||
326 | ||||
327 | // If we have a native target, initialize it to ensure it is linked in and | |||
328 | // usable by the JIT. | |||
329 | InitializeNativeTarget(); | |||
330 | InitializeNativeTargetAsmPrinter(); | |||
331 | InitializeNativeTargetAsmParser(); | |||
332 | ||||
333 | cl::ParseCommandLineOptions(argc, argv, | |||
334 | "llvm interpreter & dynamic compiler\n"); | |||
335 | ||||
336 | // If the user doesn't want core files, disable them. | |||
337 | if (DisableCoreFiles) | |||
338 | sys::Process::PreventCoreFiles(); | |||
339 | ||||
340 | LLVMContext Context; | |||
341 | ||||
342 | // Load the bitcode... | |||
343 | SMDiagnostic Err; | |||
344 | std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context); | |||
345 | Module *Mod = Owner.get(); | |||
346 | if (!Mod) | |||
347 | reportError(Err, argv[0]); | |||
348 | ||||
349 | if (UseJITKind == JITKind::OrcLazy) { | |||
350 | std::vector<std::unique_ptr<Module>> Ms; | |||
351 | Ms.push_back(std::move(Owner)); | |||
352 | for (auto &ExtraMod : ExtraModules) { | |||
353 | Ms.push_back(parseIRFile(ExtraMod, Err, Context)); | |||
354 | if (!Ms.back()) | |||
355 | reportError(Err, argv[0]); | |||
356 | } | |||
357 | std::vector<std::string> Args; | |||
358 | Args.push_back(InputFile); | |||
359 | for (auto &Arg : InputArgv) | |||
360 | Args.push_back(Arg); | |||
361 | return runOrcLazyJIT(std::move(Ms), Args); | |||
362 | } | |||
363 | ||||
364 | if (EnableCacheManager) { | |||
365 | std::string CacheName("file:"); | |||
366 | CacheName.append(InputFile); | |||
367 | Mod->setModuleIdentifier(CacheName); | |||
368 | } | |||
369 | ||||
370 | // If not jitting lazily, load the whole bitcode file eagerly too. | |||
371 | if (NoLazyCompilation) { | |||
372 | // Use *argv instead of argv[0] to work around a wrong GCC warning. | |||
373 | ExitOnError ExitOnErr(std::string(*argv) + | |||
374 | ": bitcode didn't read correctly: "); | |||
375 | ExitOnErr(Mod->materializeAll()); | |||
376 | } | |||
377 | ||||
378 | std::string ErrorMsg; | |||
379 | EngineBuilder builder(std::move(Owner)); | |||
380 | builder.setMArch(MArch); | |||
381 | builder.setMCPU(getCPUStr()); | |||
382 | builder.setMAttrs(getFeatureList()); | |||
383 | if (RelocModel.getNumOccurrences()) | |||
384 | builder.setRelocationModel(RelocModel); | |||
385 | if (CMModel.getNumOccurrences()) | |||
386 | builder.setCodeModel(CMModel); | |||
387 | builder.setErrorStr(&ErrorMsg); | |||
388 | builder.setEngineKind(ForceInterpreter | |||
389 | ? EngineKind::Interpreter | |||
390 | : EngineKind::JIT); | |||
391 | builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement); | |||
392 | ||||
393 | // If we are supposed to override the target triple, do so now. | |||
394 | if (!TargetTriple.empty()) | |||
395 | Mod->setTargetTriple(Triple::normalize(TargetTriple)); | |||
| ||||
396 | ||||
397 | // Enable MCJIT if desired. | |||
398 | RTDyldMemoryManager *RTDyldMM = nullptr; | |||
399 | if (!ForceInterpreter) { | |||
400 | if (RemoteMCJIT) | |||
401 | RTDyldMM = new ForwardingMemoryManager(); | |||
402 | else | |||
403 | RTDyldMM = new SectionMemoryManager(); | |||
404 | ||||
405 | // Deliberately construct a temp std::unique_ptr to pass in. Do not null out | |||
406 | // RTDyldMM: We still use it below, even though we don't own it. | |||
407 | builder.setMCJITMemoryManager( | |||
408 | std::unique_ptr<RTDyldMemoryManager>(RTDyldMM)); | |||
409 | } else if (RemoteMCJIT) { | |||
410 | errs() << "error: Remote process execution does not work with the " | |||
411 | "interpreter.\n"; | |||
412 | exit(1); | |||
413 | } | |||
414 | ||||
415 | builder.setOptLevel(getOptLevel()); | |||
416 | ||||
417 | TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); | |||
418 | if (FloatABIForCalls != FloatABI::Default) | |||
419 | Options.FloatABIType = FloatABIForCalls; | |||
420 | ||||
421 | builder.setTargetOptions(Options); | |||
422 | ||||
423 | std::unique_ptr<ExecutionEngine> EE(builder.create()); | |||
424 | if (!EE) { | |||
425 | if (!ErrorMsg.empty()) | |||
426 | errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; | |||
427 | else | |||
428 | errs() << argv[0] << ": unknown error creating EE!\n"; | |||
429 | exit(1); | |||
430 | } | |||
431 | ||||
432 | std::unique_ptr<LLIObjectCache> CacheManager; | |||
433 | if (EnableCacheManager) { | |||
434 | CacheManager.reset(new LLIObjectCache(ObjectCacheDir)); | |||
435 | EE->setObjectCache(CacheManager.get()); | |||
436 | } | |||
437 | ||||
438 | // Load any additional modules specified on the command line. | |||
439 | for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) { | |||
440 | std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context); | |||
441 | if (!XMod) | |||
442 | reportError(Err, argv[0]); | |||
443 | if (EnableCacheManager) { | |||
444 | std::string CacheName("file:"); | |||
445 | CacheName.append(ExtraModules[i]); | |||
446 | XMod->setModuleIdentifier(CacheName); | |||
447 | } | |||
448 | EE->addModule(std::move(XMod)); | |||
449 | } | |||
450 | ||||
451 | for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) { | |||
452 | Expected<object::OwningBinary<object::ObjectFile>> Obj = | |||
453 | object::ObjectFile::createObjectFile(ExtraObjects[i]); | |||
454 | if (!Obj) { | |||
455 | // TODO: Actually report errors helpfully. | |||
456 | consumeError(Obj.takeError()); | |||
457 | reportError(Err, argv[0]); | |||
458 | } | |||
459 | object::OwningBinary<object::ObjectFile> &O = Obj.get(); | |||
460 | EE->addObjectFile(std::move(O)); | |||
461 | } | |||
462 | ||||
463 | for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) { | |||
464 | ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr = | |||
465 | MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]); | |||
466 | if (!ArBufOrErr) | |||
467 | reportError(Err, argv[0]); | |||
468 | std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get(); | |||
469 | ||||
470 | Expected<std::unique_ptr<object::Archive>> ArOrErr = | |||
471 | object::Archive::create(ArBuf->getMemBufferRef()); | |||
472 | if (!ArOrErr) { | |||
473 | std::string Buf; | |||
474 | raw_string_ostream OS(Buf); | |||
475 | logAllUnhandledErrors(ArOrErr.takeError(), OS, ""); | |||
476 | OS.flush(); | |||
477 | errs() << Buf; | |||
478 | exit(1); | |||
479 | } | |||
480 | std::unique_ptr<object::Archive> &Ar = ArOrErr.get(); | |||
481 | ||||
482 | object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf)); | |||
483 | ||||
484 | EE->addArchive(std::move(OB)); | |||
485 | } | |||
486 | ||||
487 | // If the target is Cygwin/MingW and we are generating remote code, we | |||
488 | // need an extra module to help out with linking. | |||
489 | if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) { | |||
490 | addCygMingExtraModule(*EE, Context, Mod->getTargetTriple()); | |||
491 | } | |||
492 | ||||
493 | // The following functions have no effect if their respective profiling | |||
494 | // support wasn't enabled in the build configuration. | |||
495 | EE->RegisterJITEventListener( | |||
496 | JITEventListener::createOProfileJITEventListener()); | |||
497 | EE->RegisterJITEventListener( | |||
498 | JITEventListener::createIntelJITEventListener()); | |||
499 | ||||
500 | if (!NoLazyCompilation && RemoteMCJIT) { | |||
501 | errs() << "warning: remote mcjit does not support lazy compilation\n"; | |||
502 | NoLazyCompilation = true; | |||
503 | } | |||
504 | EE->DisableLazyCompilation(NoLazyCompilation); | |||
505 | ||||
506 | // If the user specifically requested an argv[0] to pass into the program, | |||
507 | // do it now. | |||
508 | if (!FakeArgv0.empty()) { | |||
509 | InputFile = static_cast<std::string>(FakeArgv0); | |||
510 | } else { | |||
511 | // Otherwise, if there is a .bc suffix on the executable strip it off, it | |||
512 | // might confuse the program. | |||
513 | if (StringRef(InputFile).endswith(".bc")) | |||
514 | InputFile.erase(InputFile.length() - 3); | |||
515 | } | |||
516 | ||||
517 | // Add the module's name to the start of the vector of arguments to main(). | |||
518 | InputArgv.insert(InputArgv.begin(), InputFile); | |||
519 | ||||
520 | // Call the main function from M as if its signature were: | |||
521 | // int main (int argc, char **argv, const char **envp) | |||
522 | // using the contents of Args to determine argc & argv, and the contents of | |||
523 | // EnvVars to determine envp. | |||
524 | // | |||
525 | Function *EntryFn = Mod->getFunction(EntryFunc); | |||
526 | if (!EntryFn) { | |||
527 | errs() << '\'' << EntryFunc << "\' function not found in module.\n"; | |||
528 | return -1; | |||
529 | } | |||
530 | ||||
531 | // Reset errno to zero on entry to main. | |||
532 | errno(*__errno_location ()) = 0; | |||
533 | ||||
534 | int Result = -1; | |||
535 | ||||
536 | // Sanity check use of remote-jit: LLI currently only supports use of the | |||
537 | // remote JIT on Unix platforms. | |||
538 | if (RemoteMCJIT) { | |||
539 | #ifndef LLVM_ON_UNIX1 | |||
540 | errs() << "Warning: host does not support external remote targets.\n" | |||
541 | << " Defaulting to local execution\n"; | |||
542 | return -1; | |||
543 | #else | |||
544 | if (ChildExecPath.empty()) { | |||
545 | errs() << "-remote-mcjit requires -mcjit-remote-process.\n"; | |||
546 | exit(1); | |||
547 | } else if (!sys::fs::can_execute(ChildExecPath)) { | |||
548 | errs() << "Unable to find usable child executable: '" << ChildExecPath | |||
549 | << "'\n"; | |||
550 | return -1; | |||
551 | } | |||
552 | #endif | |||
553 | } | |||
554 | ||||
555 | if (!RemoteMCJIT) { | |||
556 | // If the program doesn't explicitly call exit, we will need the Exit | |||
557 | // function later on to make an explicit call, so get the function now. | |||
558 | Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), | |||
559 | Type::getInt32Ty(Context)); | |||
560 | ||||
561 | // Run static constructors. | |||
562 | if (!ForceInterpreter) { | |||
563 | // Give MCJIT a chance to apply relocations and set page permissions. | |||
564 | EE->finalizeObject(); | |||
565 | } | |||
566 | EE->runStaticConstructorsDestructors(false); | |||
567 | ||||
568 | // Trigger compilation separately so code regions that need to be | |||
569 | // invalidated will be known. | |||
570 | (void)EE->getPointerToFunction(EntryFn); | |||
571 | // Clear instruction cache before code will be executed. | |||
572 | if (RTDyldMM) | |||
573 | static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache(); | |||
574 | ||||
575 | // Run main. | |||
576 | Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); | |||
577 | ||||
578 | // Run static destructors. | |||
579 | EE->runStaticConstructorsDestructors(true); | |||
580 | ||||
581 | // If the program didn't call exit explicitly, we should call it now. | |||
582 | // This ensures that any atexit handlers get called correctly. | |||
583 | if (Function *ExitF = dyn_cast<Function>(Exit)) { | |||
584 | std::vector<GenericValue> Args; | |||
585 | GenericValue ResultGV; | |||
586 | ResultGV.IntVal = APInt(32, Result); | |||
587 | Args.push_back(ResultGV); | |||
588 | EE->runFunction(ExitF, Args); | |||
589 | errs() << "ERROR: exit(" << Result << ") returned!\n"; | |||
590 | abort(); | |||
591 | } else { | |||
592 | errs() << "ERROR: exit defined with wrong prototype!\n"; | |||
593 | abort(); | |||
594 | } | |||
595 | } else { | |||
596 | // else == "if (RemoteMCJIT)" | |||
597 | ||||
598 | // Remote target MCJIT doesn't (yet) support static constructors. No reason | |||
599 | // it couldn't. This is a limitation of the LLI implementation, not the | |||
600 | // MCJIT itself. FIXME. | |||
601 | ||||
602 | // Lanch the remote process and get a channel to it. | |||
603 | std::unique_ptr<FDRawChannel> C = launchRemote(); | |||
604 | if (!C) { | |||
605 | errs() << "Failed to launch remote JIT.\n"; | |||
606 | exit(1); | |||
607 | } | |||
608 | ||||
609 | // Create a remote target client running over the channel. | |||
610 | typedef orc::remote::OrcRemoteTargetClient MyRemote; | |||
611 | auto R = ExitOnErr(MyRemote::Create(*C, ExitOnErr)); | |||
612 | ||||
613 | // Create a remote memory manager. | |||
614 | auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager()); | |||
615 | ||||
616 | // Forward MCJIT's memory manager calls to the remote memory manager. | |||
617 | static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr( | |||
618 | std::move(RemoteMM)); | |||
619 | ||||
620 | // Forward MCJIT's symbol resolution calls to the remote. | |||
621 | static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver( | |||
622 | orc::createLambdaResolver( | |||
623 | [](const std::string &Name) { return nullptr; }, | |||
624 | [&](const std::string &Name) { | |||
625 | if (auto Addr = ExitOnErr(R->getSymbolAddress(Name))) | |||
626 | return JITSymbol(Addr, JITSymbolFlags::Exported); | |||
627 | return JITSymbol(nullptr); | |||
628 | })); | |||
629 | ||||
630 | // Grab the target address of the JIT'd main function on the remote and call | |||
631 | // it. | |||
632 | // FIXME: argv and envp handling. | |||
633 | JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str()); | |||
634 | EE->finalizeObject(); | |||
635 | DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("lli")) { dbgs() << "Executing '" << EntryFn-> getName() << "' at 0x" << format("%llx", Entry) << "\n"; } } while (false) | |||
636 | << format("%llx", Entry) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("lli")) { dbgs() << "Executing '" << EntryFn-> getName() << "' at 0x" << format("%llx", Entry) << "\n"; } } while (false); | |||
637 | Result = ExitOnErr(R->callIntVoid(Entry)); | |||
638 | ||||
639 | // Like static constructors, the remote target MCJIT support doesn't handle | |||
640 | // this yet. It could. FIXME. | |||
641 | ||||
642 | // Delete the EE - we need to tear it down *before* we terminate the session | |||
643 | // with the remote, otherwise it'll crash when it tries to release resources | |||
644 | // on a remote that has already been disconnected. | |||
645 | EE.reset(); | |||
646 | ||||
647 | // Signal the remote target that we're done JITing. | |||
648 | ExitOnErr(R->terminateSession()); | |||
649 | } | |||
650 | ||||
651 | return Result; | |||
652 | } | |||
653 | ||||
654 | std::unique_ptr<FDRawChannel> launchRemote() { | |||
655 | #ifndef LLVM_ON_UNIX1 | |||
656 | llvm_unreachable("launchRemote not supported on non-Unix platforms")::llvm::llvm_unreachable_internal("launchRemote not supported on non-Unix platforms" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/lli/lli.cpp" , 656); | |||
657 | #else | |||
658 | int PipeFD[2][2]; | |||
659 | pid_t ChildPID; | |||
660 | ||||
661 | // Create two pipes. | |||
662 | if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0) | |||
663 | perror("Error creating pipe: "); | |||
664 | ||||
665 | ChildPID = fork(); | |||
666 | ||||
667 | if (ChildPID == 0) { | |||
668 | // In the child... | |||
669 | ||||
670 | // Close the parent ends of the pipes | |||
671 | close(PipeFD[0][1]); | |||
672 | close(PipeFD[1][0]); | |||
673 | ||||
674 | ||||
675 | // Execute the child process. | |||
676 | std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut; | |||
677 | { | |||
678 | ChildPath.reset(new char[ChildExecPath.size() + 1]); | |||
679 | std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]); | |||
680 | ChildPath[ChildExecPath.size()] = '\0'; | |||
681 | std::string ChildInStr = utostr(PipeFD[0][0]); | |||
682 | ChildIn.reset(new char[ChildInStr.size() + 1]); | |||
683 | std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]); | |||
684 | ChildIn[ChildInStr.size()] = '\0'; | |||
685 | std::string ChildOutStr = utostr(PipeFD[1][1]); | |||
686 | ChildOut.reset(new char[ChildOutStr.size() + 1]); | |||
687 | std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]); | |||
688 | ChildOut[ChildOutStr.size()] = '\0'; | |||
689 | } | |||
690 | ||||
691 | char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr }; | |||
692 | int rc = execv(ChildExecPath.c_str(), args); | |||
693 | if (rc != 0) | |||
694 | perror("Error executing child process: "); | |||
695 | llvm_unreachable("Error executing child process")::llvm::llvm_unreachable_internal("Error executing child process" , "/build/llvm-toolchain-snapshot-7~svn329677/tools/lli/lli.cpp" , 695); | |||
696 | } | |||
697 | // else we're the parent... | |||
698 | ||||
699 | // Close the child ends of the pipes | |||
700 | close(PipeFD[0][0]); | |||
701 | close(PipeFD[1][1]); | |||
702 | ||||
703 | // Return an RPC channel connected to our end of the pipes. | |||
704 | return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]); | |||
705 | #endif | |||
706 | } |
1 | // unique_ptr implementation -*- C++ -*- |
2 | |
3 | // Copyright (C) 2008-2017 Free Software Foundation, Inc. |
4 | // |
5 | // This file is part of the GNU ISO C++ Library. This library is free |
6 | // software; you can redistribute it and/or modify it under the |
7 | // terms of the GNU General Public License as published by the |
8 | // Free Software Foundation; either version 3, or (at your option) |
9 | // any later version. |
10 | |
11 | // This library is distributed in the hope that it will be useful, |
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14 | // GNU General Public License for more details. |
15 | |
16 | // Under Section 7 of GPL version 3, you are granted additional |
17 | // permissions described in the GCC Runtime Library Exception, version |
18 | // 3.1, as published by the Free Software Foundation. |
19 | |
20 | // You should have received a copy of the GNU General Public License and |
21 | // a copy of the GCC Runtime Library Exception along with this program; |
22 | // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see |
23 | // <http://www.gnu.org/licenses/>. |
24 | |
25 | /** @file bits/unique_ptr.h |
26 | * This is an internal header file, included by other library headers. |
27 | * Do not attempt to use it directly. @headername{memory} |
28 | */ |
29 | |
30 | #ifndef _UNIQUE_PTR_H1 |
31 | #define _UNIQUE_PTR_H1 1 |
32 | |
33 | #include <bits/c++config.h> |
34 | #include <debug/assertions.h> |
35 | #include <type_traits> |
36 | #include <utility> |
37 | #include <tuple> |
38 | #include <bits/stl_function.h> |
39 | #include <bits/functional_hash.h> |
40 | |
41 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
42 | { |
43 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
44 | |
45 | /** |
46 | * @addtogroup pointer_abstractions |
47 | * @{ |
48 | */ |
49 | |
50 | #if _GLIBCXX_USE_DEPRECATED1 |
51 | template<typename> class auto_ptr; |
52 | #endif |
53 | |
54 | /// Primary template of default_delete, used by unique_ptr |
55 | template<typename _Tp> |
56 | struct default_delete |
57 | { |
58 | /// Default constructor |
59 | constexpr default_delete() noexcept = default; |
60 | |
61 | /** @brief Converting constructor. |
62 | * |
63 | * Allows conversion from a deleter for arrays of another type, @p _Up, |
64 | * only if @p _Up* is convertible to @p _Tp*. |
65 | */ |
66 | template<typename _Up, typename = typename |
67 | enable_if<is_convertible<_Up*, _Tp*>::value>::type> |
68 | default_delete(const default_delete<_Up>&) noexcept { } |
69 | |
70 | /// Calls @c delete @p __ptr |
71 | void |
72 | operator()(_Tp* __ptr) const |
73 | { |
74 | static_assert(!is_void<_Tp>::value, |
75 | "can't delete pointer to incomplete type"); |
76 | static_assert(sizeof(_Tp)>0, |
77 | "can't delete pointer to incomplete type"); |
78 | delete __ptr; |
79 | } |
80 | }; |
81 | |
82 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
83 | // DR 740 - omit specialization for array objects with a compile time length |
84 | /// Specialization for arrays, default_delete. |
85 | template<typename _Tp> |
86 | struct default_delete<_Tp[]> |
87 | { |
88 | public: |
89 | /// Default constructor |
90 | constexpr default_delete() noexcept = default; |
91 | |
92 | /** @brief Converting constructor. |
93 | * |
94 | * Allows conversion from a deleter for arrays of another type, such as |
95 | * a const-qualified version of @p _Tp. |
96 | * |
97 | * Conversions from types derived from @c _Tp are not allowed because |
98 | * it is unsafe to @c delete[] an array of derived types through a |
99 | * pointer to the base type. |
100 | */ |
101 | template<typename _Up, typename = typename |
102 | enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type> |
103 | default_delete(const default_delete<_Up[]>&) noexcept { } |
104 | |
105 | /// Calls @c delete[] @p __ptr |
106 | template<typename _Up> |
107 | typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type |
108 | operator()(_Up* __ptr) const |
109 | { |
110 | static_assert(sizeof(_Tp)>0, |
111 | "can't delete pointer to incomplete type"); |
112 | delete [] __ptr; |
113 | } |
114 | }; |
115 | |
116 | template <typename _Tp, typename _Dp> |
117 | class __uniq_ptr_impl |
118 | { |
119 | template <typename _Up, typename _Ep, typename = void> |
120 | struct _Ptr |
121 | { |
122 | using type = _Up*; |
123 | }; |
124 | |
125 | template <typename _Up, typename _Ep> |
126 | struct |
127 | _Ptr<_Up, _Ep, __void_t<typename remove_reference<_Ep>::type::pointer>> |
128 | { |
129 | using type = typename remove_reference<_Ep>::type::pointer; |
130 | }; |
131 | |
132 | public: |
133 | using _DeleterConstraint = enable_if< |
134 | __and_<__not_<is_pointer<_Dp>>, |
135 | is_default_constructible<_Dp>>::value>; |
136 | |
137 | using pointer = typename _Ptr<_Tp, _Dp>::type; |
138 | |
139 | __uniq_ptr_impl() = default; |
140 | __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; } |
141 | |
142 | template<typename _Del> |
143 | __uniq_ptr_impl(pointer __p, _Del&& __d) |
144 | : _M_t(__p, std::forward<_Del>(__d)) { } |
145 | |
146 | pointer& _M_ptr() { return std::get<0>(_M_t); } |
147 | pointer _M_ptr() const { return std::get<0>(_M_t); } |
148 | _Dp& _M_deleter() { return std::get<1>(_M_t); } |
149 | const _Dp& _M_deleter() const { return std::get<1>(_M_t); } |
150 | |
151 | private: |
152 | tuple<pointer, _Dp> _M_t; |
153 | }; |
154 | |
155 | /// 20.7.1.2 unique_ptr for single objects. |
156 | template <typename _Tp, typename _Dp = default_delete<_Tp>> |
157 | class unique_ptr |
158 | { |
159 | template <class _Up> |
160 | using _DeleterConstraint = |
161 | typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type; |
162 | |
163 | __uniq_ptr_impl<_Tp, _Dp> _M_t; |
164 | |
165 | public: |
166 | using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer; |
167 | using element_type = _Tp; |
168 | using deleter_type = _Dp; |
169 | |
170 | // helper template for detecting a safe conversion from another |
171 | // unique_ptr |
172 | template<typename _Up, typename _Ep> |
173 | using __safe_conversion_up = __and_< |
174 | is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>, |
175 | __not_<is_array<_Up>>, |
176 | __or_<__and_<is_reference<deleter_type>, |
177 | is_same<deleter_type, _Ep>>, |
178 | __and_<__not_<is_reference<deleter_type>>, |
179 | is_convertible<_Ep, deleter_type>> |
180 | > |
181 | >; |
182 | |
183 | // Constructors. |
184 | |
185 | /// Default constructor, creates a unique_ptr that owns nothing. |
186 | template <typename _Up = _Dp, |
187 | typename = _DeleterConstraint<_Up>> |
188 | constexpr unique_ptr() noexcept |
189 | : _M_t() |
190 | { } |
191 | |
192 | /** Takes ownership of a pointer. |
193 | * |
194 | * @param __p A pointer to an object of @c element_type |
195 | * |
196 | * The deleter will be value-initialized. |
197 | */ |
198 | template <typename _Up = _Dp, |
199 | typename = _DeleterConstraint<_Up>> |
200 | explicit |
201 | unique_ptr(pointer __p) noexcept |
202 | : _M_t(__p) |
203 | { } |
204 | |
205 | /** Takes ownership of a pointer. |
206 | * |
207 | * @param __p A pointer to an object of @c element_type |
208 | * @param __d A reference to a deleter. |
209 | * |
210 | * The deleter will be initialized with @p __d |
211 | */ |
212 | unique_ptr(pointer __p, |
213 | typename conditional<is_reference<deleter_type>::value, |
214 | deleter_type, const deleter_type&>::type __d) noexcept |
215 | : _M_t(__p, __d) { } |
216 | |
217 | /** Takes ownership of a pointer. |
218 | * |
219 | * @param __p A pointer to an object of @c element_type |
220 | * @param __d An rvalue reference to a deleter. |
221 | * |
222 | * The deleter will be initialized with @p std::move(__d) |
223 | */ |
224 | unique_ptr(pointer __p, |
225 | typename remove_reference<deleter_type>::type&& __d) noexcept |
226 | : _M_t(std::move(__p), std::move(__d)) |
227 | { static_assert(!std::is_reference<deleter_type>::value, |
228 | "rvalue deleter bound to reference"); } |
229 | |
230 | /// Creates a unique_ptr that owns nothing. |
231 | template <typename _Up = _Dp, |
232 | typename = _DeleterConstraint<_Up>> |
233 | constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { } |
234 | |
235 | // Move constructors. |
236 | |
237 | /// Move constructor. |
238 | unique_ptr(unique_ptr&& __u) noexcept |
239 | : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { } |
240 | |
241 | /** @brief Converting constructor from another type |
242 | * |
243 | * Requires that the pointer owned by @p __u is convertible to the |
244 | * type of pointer owned by this object, @p __u does not own an array, |
245 | * and @p __u has a compatible deleter type. |
246 | */ |
247 | template<typename _Up, typename _Ep, typename = _Require< |
248 | __safe_conversion_up<_Up, _Ep>, |
249 | typename conditional<is_reference<_Dp>::value, |
250 | is_same<_Ep, _Dp>, |
251 | is_convertible<_Ep, _Dp>>::type>> |
252 | unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept |
253 | : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter())) |
254 | { } |
255 | |
256 | #if _GLIBCXX_USE_DEPRECATED1 |
257 | /// Converting constructor from @c auto_ptr |
258 | template<typename _Up, typename = _Require< |
259 | is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>> |
260 | unique_ptr(auto_ptr<_Up>&& __u) noexcept; |
261 | #endif |
262 | |
263 | /// Destructor, invokes the deleter if the stored pointer is not null. |
264 | ~unique_ptr() noexcept |
265 | { |
266 | auto& __ptr = _M_t._M_ptr(); |
267 | if (__ptr != nullptr) |
268 | get_deleter()(__ptr); |
269 | __ptr = pointer(); |
270 | } |
271 | |
272 | // Assignment. |
273 | |
274 | /** @brief Move assignment operator. |
275 | * |
276 | * @param __u The object to transfer ownership from. |
277 | * |
278 | * Invokes the deleter first if this object owns a pointer. |
279 | */ |
280 | unique_ptr& |
281 | operator=(unique_ptr&& __u) noexcept |
282 | { |
283 | reset(__u.release()); |
284 | get_deleter() = std::forward<deleter_type>(__u.get_deleter()); |
285 | return *this; |
286 | } |
287 | |
288 | /** @brief Assignment from another type. |
289 | * |
290 | * @param __u The object to transfer ownership from, which owns a |
291 | * convertible pointer to a non-array object. |
292 | * |
293 | * Invokes the deleter first if this object owns a pointer. |
294 | */ |
295 | template<typename _Up, typename _Ep> |
296 | typename enable_if< __and_< |
297 | __safe_conversion_up<_Up, _Ep>, |
298 | is_assignable<deleter_type&, _Ep&&> |
299 | >::value, |
300 | unique_ptr&>::type |
301 | operator=(unique_ptr<_Up, _Ep>&& __u) noexcept |
302 | { |
303 | reset(__u.release()); |
304 | get_deleter() = std::forward<_Ep>(__u.get_deleter()); |
305 | return *this; |
306 | } |
307 | |
308 | /// Reset the %unique_ptr to empty, invoking the deleter if necessary. |
309 | unique_ptr& |
310 | operator=(nullptr_t) noexcept |
311 | { |
312 | reset(); |
313 | return *this; |
314 | } |
315 | |
316 | // Observers. |
317 | |
318 | /// Dereference the stored pointer. |
319 | typename add_lvalue_reference<element_type>::type |
320 | operator*() const |
321 | { |
322 | __glibcxx_assert(get() != pointer()); |
323 | return *get(); |
324 | } |
325 | |
326 | /// Return the stored pointer. |
327 | pointer |
328 | operator->() const noexcept |
329 | { |
330 | _GLIBCXX_DEBUG_PEDASSERT(get() != pointer()); |
331 | return get(); |
332 | } |
333 | |
334 | /// Return the stored pointer. |
335 | pointer |
336 | get() const noexcept |
337 | { return _M_t._M_ptr(); } |
338 | |
339 | /// Return a reference to the stored deleter. |
340 | deleter_type& |
341 | get_deleter() noexcept |
342 | { return _M_t._M_deleter(); } |
343 | |
344 | /// Return a reference to the stored deleter. |
345 | const deleter_type& |
346 | get_deleter() const noexcept |
347 | { return _M_t._M_deleter(); } |
348 | |
349 | /// Return @c true if the stored pointer is not null. |
350 | explicit operator bool() const noexcept |
351 | { return get() == pointer() ? false : true; } |
352 | |
353 | // Modifiers. |
354 | |
355 | /// Release ownership of any stored pointer. |
356 | pointer |
357 | release() noexcept |
358 | { |
359 | pointer __p = get(); |
360 | _M_t._M_ptr() = pointer(); |
361 | return __p; |
362 | } |
363 | |
364 | /** @brief Replace the stored pointer. |
365 | * |
366 | * @param __p The new pointer to store. |
367 | * |
368 | * The deleter will be invoked if a pointer is already owned. |
369 | */ |
370 | void |
371 | reset(pointer __p = pointer()) noexcept |
372 | { |
373 | using std::swap; |
374 | swap(_M_t._M_ptr(), __p); |
375 | if (__p != pointer()) |
376 | get_deleter()(__p); |
377 | } |
378 | |
379 | /// Exchange the pointer and deleter with another object. |
380 | void |
381 | swap(unique_ptr& __u) noexcept |
382 | { |
383 | using std::swap; |
384 | swap(_M_t, __u._M_t); |
385 | } |
386 | |
387 | // Disable copy from lvalue. |
388 | unique_ptr(const unique_ptr&) = delete; |
389 | unique_ptr& operator=(const unique_ptr&) = delete; |
390 | }; |
391 | |
392 | /// 20.7.1.3 unique_ptr for array objects with a runtime length |
393 | // [unique.ptr.runtime] |
394 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
395 | // DR 740 - omit specialization for array objects with a compile time length |
396 | template<typename _Tp, typename _Dp> |
397 | class unique_ptr<_Tp[], _Dp> |
398 | { |
399 | template <typename _Up> |
400 | using _DeleterConstraint = |
401 | typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type; |
402 | |
403 | __uniq_ptr_impl<_Tp, _Dp> _M_t; |
404 | |
405 | template<typename _Up> |
406 | using __remove_cv = typename remove_cv<_Up>::type; |
407 | |
408 | // like is_base_of<_Tp, _Up> but false if unqualified types are the same |
409 | template<typename _Up> |
410 | using __is_derived_Tp |
411 | = __and_< is_base_of<_Tp, _Up>, |
412 | __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >; |
413 | |
414 | public: |
415 | using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer; |
416 | using element_type = _Tp; |
417 | using deleter_type = _Dp; |
418 | |
419 | // helper template for detecting a safe conversion from another |
420 | // unique_ptr |
421 | template<typename _Up, typename _Ep, |
422 | typename _Up_up = unique_ptr<_Up, _Ep>, |
423 | typename _Up_element_type = typename _Up_up::element_type> |
424 | using __safe_conversion_up = __and_< |
425 | is_array<_Up>, |
426 | is_same<pointer, element_type*>, |
427 | is_same<typename _Up_up::pointer, _Up_element_type*>, |
428 | is_convertible<_Up_element_type(*)[], element_type(*)[]>, |
429 | __or_<__and_<is_reference<deleter_type>, is_same<deleter_type, _Ep>>, |
430 | __and_<__not_<is_reference<deleter_type>>, |
431 | is_convertible<_Ep, deleter_type>>> |
432 | >; |
433 | |
434 | // helper template for detecting a safe conversion from a raw pointer |
435 | template<typename _Up> |
436 | using __safe_conversion_raw = __and_< |
437 | __or_<__or_<is_same<_Up, pointer>, |
438 | is_same<_Up, nullptr_t>>, |
439 | __and_<is_pointer<_Up>, |
440 | is_same<pointer, element_type*>, |
441 | is_convertible< |
442 | typename remove_pointer<_Up>::type(*)[], |
443 | element_type(*)[]> |
444 | > |
445 | > |
446 | >; |
447 | |
448 | // Constructors. |
449 | |
450 | /// Default constructor, creates a unique_ptr that owns nothing. |
451 | template <typename _Up = _Dp, |
452 | typename = _DeleterConstraint<_Up>> |
453 | constexpr unique_ptr() noexcept |
454 | : _M_t() |
455 | { } |
456 | |
457 | /** Takes ownership of a pointer. |
458 | * |
459 | * @param __p A pointer to an array of a type safely convertible |
460 | * to an array of @c element_type |
461 | * |
462 | * The deleter will be value-initialized. |
463 | */ |
464 | template<typename _Up, |
465 | typename _Vp = _Dp, |
466 | typename = _DeleterConstraint<_Vp>, |
467 | typename = typename enable_if< |
468 | __safe_conversion_raw<_Up>::value, bool>::type> |
469 | explicit |
470 | unique_ptr(_Up __p) noexcept |
471 | : _M_t(__p) |
472 | { } |
473 | |
474 | /** Takes ownership of a pointer. |
475 | * |
476 | * @param __p A pointer to an array of a type safely convertible |
477 | * to an array of @c element_type |
478 | * @param __d A reference to a deleter. |
479 | * |
480 | * The deleter will be initialized with @p __d |
481 | */ |
482 | template<typename _Up, |
483 | typename = typename enable_if< |
484 | __safe_conversion_raw<_Up>::value, bool>::type> |
485 | unique_ptr(_Up __p, |
486 | typename conditional<is_reference<deleter_type>::value, |
487 | deleter_type, const deleter_type&>::type __d) noexcept |
488 | : _M_t(__p, __d) { } |
489 | |
490 | /** Takes ownership of a pointer. |
491 | * |
492 | * @param __p A pointer to an array of a type safely convertible |
493 | * to an array of @c element_type |
494 | * @param __d A reference to a deleter. |
495 | * |
496 | * The deleter will be initialized with @p std::move(__d) |
497 | */ |
498 | template<typename _Up, |
499 | typename = typename enable_if< |
500 | __safe_conversion_raw<_Up>::value, bool>::type> |
501 | unique_ptr(_Up __p, typename |
502 | remove_reference<deleter_type>::type&& __d) noexcept |
503 | : _M_t(std::move(__p), std::move(__d)) |
504 | { static_assert(!is_reference<deleter_type>::value, |
505 | "rvalue deleter bound to reference"); } |
506 | |
507 | /// Move constructor. |
508 | unique_ptr(unique_ptr&& __u) noexcept |
509 | : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { } |
510 | |
511 | /// Creates a unique_ptr that owns nothing. |
512 | template <typename _Up = _Dp, |
513 | typename = _DeleterConstraint<_Up>> |
514 | constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { } |
515 | |
516 | template<typename _Up, typename _Ep, |
517 | typename = _Require<__safe_conversion_up<_Up, _Ep>>> |
518 | unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept |
519 | : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter())) |
520 | { } |
521 | |
522 | /// Destructor, invokes the deleter if the stored pointer is not null. |
523 | ~unique_ptr() |
524 | { |
525 | auto& __ptr = _M_t._M_ptr(); |
526 | if (__ptr != nullptr) |
527 | get_deleter()(__ptr); |
528 | __ptr = pointer(); |
529 | } |
530 | |
531 | // Assignment. |
532 | |
533 | /** @brief Move assignment operator. |
534 | * |
535 | * @param __u The object to transfer ownership from. |
536 | * |
537 | * Invokes the deleter first if this object owns a pointer. |
538 | */ |
539 | unique_ptr& |
540 | operator=(unique_ptr&& __u) noexcept |
541 | { |
542 | reset(__u.release()); |
543 | get_deleter() = std::forward<deleter_type>(__u.get_deleter()); |
544 | return *this; |
545 | } |
546 | |
547 | /** @brief Assignment from another type. |
548 | * |
549 | * @param __u The object to transfer ownership from, which owns a |
550 | * convertible pointer to an array object. |
551 | * |
552 | * Invokes the deleter first if this object owns a pointer. |
553 | */ |
554 | template<typename _Up, typename _Ep> |
555 | typename |
556 | enable_if<__and_<__safe_conversion_up<_Up, _Ep>, |
557 | is_assignable<deleter_type&, _Ep&&> |
558 | >::value, |
559 | unique_ptr&>::type |
560 | operator=(unique_ptr<_Up, _Ep>&& __u) noexcept |
561 | { |
562 | reset(__u.release()); |
563 | get_deleter() = std::forward<_Ep>(__u.get_deleter()); |
564 | return *this; |
565 | } |
566 | |
567 | /// Reset the %unique_ptr to empty, invoking the deleter if necessary. |
568 | unique_ptr& |
569 | operator=(nullptr_t) noexcept |
570 | { |
571 | reset(); |
572 | return *this; |
573 | } |
574 | |
575 | // Observers. |
576 | |
577 | /// Access an element of owned array. |
578 | typename std::add_lvalue_reference<element_type>::type |
579 | operator[](size_t __i) const |
580 | { |
581 | __glibcxx_assert(get() != pointer()); |
582 | return get()[__i]; |
583 | } |
584 | |
585 | /// Return the stored pointer. |
586 | pointer |
587 | get() const noexcept |
588 | { return _M_t._M_ptr(); } |
589 | |
590 | /// Return a reference to the stored deleter. |
591 | deleter_type& |
592 | get_deleter() noexcept |
593 | { return _M_t._M_deleter(); } |
594 | |
595 | /// Return a reference to the stored deleter. |
596 | const deleter_type& |
597 | get_deleter() const noexcept |
598 | { return _M_t._M_deleter(); } |
599 | |
600 | /// Return @c true if the stored pointer is not null. |
601 | explicit operator bool() const noexcept |
602 | { return get() == pointer() ? false : true; } |
603 | |
604 | // Modifiers. |
605 | |
606 | /// Release ownership of any stored pointer. |
607 | pointer |
608 | release() noexcept |
609 | { |
610 | pointer __p = get(); |
611 | _M_t._M_ptr() = pointer(); |
612 | return __p; |
613 | } |
614 | |
615 | /** @brief Replace the stored pointer. |
616 | * |
617 | * @param __p The new pointer to store. |
618 | * |
619 | * The deleter will be invoked if a pointer is already owned. |
620 | */ |
621 | template <typename _Up, |
622 | typename = _Require< |
623 | __or_<is_same<_Up, pointer>, |
624 | __and_<is_same<pointer, element_type*>, |
625 | is_pointer<_Up>, |
626 | is_convertible< |
627 | typename remove_pointer<_Up>::type(*)[], |
628 | element_type(*)[] |
629 | > |
630 | > |
631 | > |
632 | >> |
633 | void |
634 | reset(_Up __p) noexcept |
635 | { |
636 | pointer __ptr = __p; |
637 | using std::swap; |
638 | swap(_M_t._M_ptr(), __ptr); |
639 | if (__ptr != nullptr) |
640 | get_deleter()(__ptr); |
641 | } |
642 | |
643 | void reset(nullptr_t = nullptr) noexcept |
644 | { |
645 | reset(pointer()); |
646 | } |
647 | |
648 | /// Exchange the pointer and deleter with another object. |
649 | void |
650 | swap(unique_ptr& __u) noexcept |
651 | { |
652 | using std::swap; |
653 | swap(_M_t, __u._M_t); |
654 | } |
655 | |
656 | // Disable copy from lvalue. |
657 | unique_ptr(const unique_ptr&) = delete; |
658 | unique_ptr& operator=(const unique_ptr&) = delete; |
659 | }; |
660 | |
661 | template<typename _Tp, typename _Dp> |
662 | inline |
663 | #if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11 |
664 | // Constrained free swap overload, see p0185r1 |
665 | typename enable_if<__is_swappable<_Dp>::value>::type |
666 | #else |
667 | void |
668 | #endif |
669 | swap(unique_ptr<_Tp, _Dp>& __x, |
670 | unique_ptr<_Tp, _Dp>& __y) noexcept |
671 | { __x.swap(__y); } |
672 | |
673 | #if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11 |
674 | template<typename _Tp, typename _Dp> |
675 | typename enable_if<!__is_swappable<_Dp>::value>::type |
676 | swap(unique_ptr<_Tp, _Dp>&, |
677 | unique_ptr<_Tp, _Dp>&) = delete; |
678 | #endif |
679 | |
680 | template<typename _Tp, typename _Dp, |
681 | typename _Up, typename _Ep> |
682 | inline bool |
683 | operator==(const unique_ptr<_Tp, _Dp>& __x, |
684 | const unique_ptr<_Up, _Ep>& __y) |
685 | { return __x.get() == __y.get(); } |
686 | |
687 | template<typename _Tp, typename _Dp> |
688 | inline bool |
689 | operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept |
690 | { return !__x; } |
691 | |
692 | template<typename _Tp, typename _Dp> |
693 | inline bool |
694 | operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept |
695 | { return !__x; } |
696 | |
697 | template<typename _Tp, typename _Dp, |
698 | typename _Up, typename _Ep> |
699 | inline bool |
700 | operator!=(const unique_ptr<_Tp, _Dp>& __x, |
701 | const unique_ptr<_Up, _Ep>& __y) |
702 | { return __x.get() != __y.get(); } |
703 | |
704 | template<typename _Tp, typename _Dp> |
705 | inline bool |
706 | operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept |
707 | { return (bool)__x; } |
708 | |
709 | template<typename _Tp, typename _Dp> |
710 | inline bool |
711 | operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept |
712 | { return (bool)__x; } |
713 | |
714 | template<typename _Tp, typename _Dp, |
715 | typename _Up, typename _Ep> |
716 | inline bool |
717 | operator<(const unique_ptr<_Tp, _Dp>& __x, |
718 | const unique_ptr<_Up, _Ep>& __y) |
719 | { |
720 | typedef typename |
721 | std::common_type<typename unique_ptr<_Tp, _Dp>::pointer, |
722 | typename unique_ptr<_Up, _Ep>::pointer>::type _CT; |
723 | return std::less<_CT>()(__x.get(), __y.get()); |
724 | } |
725 | |
726 | template<typename _Tp, typename _Dp> |
727 | inline bool |
728 | operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) |
729 | { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(), |
730 | nullptr); } |
731 | |
732 | template<typename _Tp, typename _Dp> |
733 | inline bool |
734 | operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) |
735 | { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr, |
736 | __x.get()); } |
737 | |
738 | template<typename _Tp, typename _Dp, |
739 | typename _Up, typename _Ep> |
740 | inline bool |
741 | operator<=(const unique_ptr<_Tp, _Dp>& __x, |
742 | const unique_ptr<_Up, _Ep>& __y) |
743 | { return !(__y < __x); } |
744 | |
745 | template<typename _Tp, typename _Dp> |
746 | inline bool |
747 | operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) |
748 | { return !(nullptr < __x); } |
749 | |
750 | template<typename _Tp, typename _Dp> |
751 | inline bool |
752 | operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) |
753 | { return !(__x < nullptr); } |
754 | |
755 | template<typename _Tp, typename _Dp, |
756 | typename _Up, typename _Ep> |
757 | inline bool |
758 | operator>(const unique_ptr<_Tp, _Dp>& __x, |
759 | const unique_ptr<_Up, _Ep>& __y) |
760 | { return (__y < __x); } |
761 | |
762 | template<typename _Tp, typename _Dp> |
763 | inline bool |
764 | operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) |
765 | { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr, |
766 | __x.get()); } |
767 | |
768 | template<typename _Tp, typename _Dp> |
769 | inline bool |
770 | operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) |
771 | { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(), |
772 | nullptr); } |
773 | |
774 | template<typename _Tp, typename _Dp, |
775 | typename _Up, typename _Ep> |
776 | inline bool |
777 | operator>=(const unique_ptr<_Tp, _Dp>& __x, |
778 | const unique_ptr<_Up, _Ep>& __y) |
779 | { return !(__x < __y); } |
780 | |
781 | template<typename _Tp, typename _Dp> |
782 | inline bool |
783 | operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) |
784 | { return !(__x < nullptr); } |
785 | |
786 | template<typename _Tp, typename _Dp> |
787 | inline bool |
788 | operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) |
789 | { return !(nullptr < __x); } |
790 | |
791 | /// std::hash specialization for unique_ptr. |
792 | template<typename _Tp, typename _Dp> |
793 | struct hash<unique_ptr<_Tp, _Dp>> |
794 | : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>, |
795 | private __poison_hash<typename unique_ptr<_Tp, _Dp>::pointer> |
796 | { |
797 | size_t |
798 | operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept |
799 | { |
800 | typedef unique_ptr<_Tp, _Dp> _UP; |
801 | return std::hash<typename _UP::pointer>()(__u.get()); |
802 | } |
803 | }; |
804 | |
805 | #if __cplusplus201103L > 201103L |
806 | |
807 | #define __cpp_lib_make_unique 201304 |
808 | |
809 | template<typename _Tp> |
810 | struct _MakeUniq |
811 | { typedef unique_ptr<_Tp> __single_object; }; |
812 | |
813 | template<typename _Tp> |
814 | struct _MakeUniq<_Tp[]> |
815 | { typedef unique_ptr<_Tp[]> __array; }; |
816 | |
817 | template<typename _Tp, size_t _Bound> |
818 | struct _MakeUniq<_Tp[_Bound]> |
819 | { struct __invalid_type { }; }; |
820 | |
821 | /// std::make_unique for single objects |
822 | template<typename _Tp, typename... _Args> |
823 | inline typename _MakeUniq<_Tp>::__single_object |
824 | make_unique(_Args&&... __args) |
825 | { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); } |
826 | |
827 | /// std::make_unique for arrays of unknown bound |
828 | template<typename _Tp> |
829 | inline typename _MakeUniq<_Tp>::__array |
830 | make_unique(size_t __num) |
831 | { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); } |
832 | |
833 | /// Disable std::make_unique for arrays of known bound |
834 | template<typename _Tp, typename... _Args> |
835 | inline typename _MakeUniq<_Tp>::__invalid_type |
836 | make_unique(_Args&&...) = delete; |
837 | #endif |
838 | |
839 | // @} group pointer_abstractions |
840 | |
841 | _GLIBCXX_END_NAMESPACE_VERSION |
842 | } // namespace |
843 | |
844 | #endif /* _UNIQUE_PTR_H */ |