1//===- BuildLibCalls.cpp - Utility builder for libcalls -------------------===//
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 file implements some functions that will create standard C libcalls.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/BuildLibCalls.h"
15#include "llvm/ADT/SmallString.h"
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/Function.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/Intrinsics.h"
21#include "llvm/IR/LLVMContext.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/Type.h"
24#include "llvm/Analysis/TargetLibraryInfo.h"
25
26using namespace llvm;
27
28/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
29Value *llvm::CastToCStr(Value *V, IRBuilder<> &B) {
30  unsigned AS = V->getType()->getPointerAddressSpace();
31  return B.CreateBitCast(V, B.getInt8PtrTy(AS), "cstr");
32}
33
34/// EmitStrLen - Emit a call to the strlen function to the builder, for the
35/// specified pointer.  This always returns an integer value of size intptr_t.
36Value *llvm::EmitStrLen(Value *Ptr, IRBuilder<> &B, const DataLayout &DL,
37                        const TargetLibraryInfo *TLI) {
38  if (!TLI->has(LibFunc::strlen))
39    return nullptr;
40
41  Module *M = B.GetInsertBlock()->getParent()->getParent();
42  AttributeSet AS[2];
43  AS[0] = AttributeSet::get(M->getContext(), 1, Attribute::NoCapture);
44  Attribute::AttrKind AVs[2] = { Attribute::ReadOnly, Attribute::NoUnwind };
45  AS[1] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex, AVs);
46
47  LLVMContext &Context = B.GetInsertBlock()->getContext();
48  Constant *StrLen = M->getOrInsertFunction(
49      "strlen", AttributeSet::get(M->getContext(), AS),
50      DL.getIntPtrType(Context), B.getInt8PtrTy(), nullptr);
51  CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
52  if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
53    CI->setCallingConv(F->getCallingConv());
54
55  return CI;
56}
57
58/// EmitStrNLen - Emit a call to the strnlen function to the builder, for the
59/// specified pointer.  Ptr is required to be some pointer type, MaxLen must
60/// be of size_t type, and the return value has 'intptr_t' type.
61Value *llvm::EmitStrNLen(Value *Ptr, Value *MaxLen, IRBuilder<> &B,
62                         const DataLayout &DL, const TargetLibraryInfo *TLI) {
63  if (!TLI->has(LibFunc::strnlen))
64    return nullptr;
65
66  Module *M = B.GetInsertBlock()->getParent()->getParent();
67  AttributeSet AS[2];
68  AS[0] = AttributeSet::get(M->getContext(), 1, Attribute::NoCapture);
69  Attribute::AttrKind AVs[2] = { Attribute::ReadOnly, Attribute::NoUnwind };
70  AS[1] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex, AVs);
71
72  LLVMContext &Context = B.GetInsertBlock()->getContext();
73  Constant *StrNLen =
74      M->getOrInsertFunction("strnlen", AttributeSet::get(M->getContext(), AS),
75                             DL.getIntPtrType(Context), B.getInt8PtrTy(),
76                             DL.getIntPtrType(Context), nullptr);
77  CallInst *CI = B.CreateCall2(StrNLen, CastToCStr(Ptr, B), MaxLen, "strnlen");
78  if (const Function *F = dyn_cast<Function>(StrNLen->stripPointerCasts()))
79    CI->setCallingConv(F->getCallingConv());
80
81  return CI;
82}
83
84/// EmitStrChr - Emit a call to the strchr function to the builder, for the
85/// specified pointer and character.  Ptr is required to be some pointer type,
86/// and the return value has 'i8*' type.
87Value *llvm::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B,
88                        const TargetLibraryInfo *TLI) {
89  if (!TLI->has(LibFunc::strchr))
90    return nullptr;
91
92  Module *M = B.GetInsertBlock()->getParent()->getParent();
93  Attribute::AttrKind AVs[2] = { Attribute::ReadOnly, Attribute::NoUnwind };
94  AttributeSet AS =
95    AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex, AVs);
96
97  Type *I8Ptr = B.getInt8PtrTy();
98  Type *I32Ty = B.getInt32Ty();
99  Constant *StrChr = M->getOrInsertFunction("strchr",
100                                            AttributeSet::get(M->getContext(),
101                                                             AS),
102                                            I8Ptr, I8Ptr, I32Ty, nullptr);
103  CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
104                               ConstantInt::get(I32Ty, C), "strchr");
105  if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
106    CI->setCallingConv(F->getCallingConv());
107  return CI;
108}
109
110/// EmitStrNCmp - Emit a call to the strncmp function to the builder.
111Value *llvm::EmitStrNCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B,
112                         const DataLayout &DL, const TargetLibraryInfo *TLI) {
113  if (!TLI->has(LibFunc::strncmp))
114    return nullptr;
115
116  Module *M = B.GetInsertBlock()->getParent()->getParent();
117  AttributeSet AS[3];
118  AS[0] = AttributeSet::get(M->getContext(), 1, Attribute::NoCapture);
119  AS[1] = AttributeSet::get(M->getContext(), 2, Attribute::NoCapture);
120  Attribute::AttrKind AVs[2] = { Attribute::ReadOnly, Attribute::NoUnwind };
121  AS[2] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex, AVs);
122
123  LLVMContext &Context = B.GetInsertBlock()->getContext();
124  Value *StrNCmp = M->getOrInsertFunction(
125      "strncmp", AttributeSet::get(M->getContext(), AS), B.getInt32Ty(),
126      B.getInt8PtrTy(), B.getInt8PtrTy(), DL.getIntPtrType(Context), nullptr);
127  CallInst *CI = B.CreateCall3(StrNCmp, CastToCStr(Ptr1, B),
128                               CastToCStr(Ptr2, B), Len, "strncmp");
129
130  if (const Function *F = dyn_cast<Function>(StrNCmp->stripPointerCasts()))
131    CI->setCallingConv(F->getCallingConv());
132
133  return CI;
134}
135
136/// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
137/// specified pointer arguments.
138Value *llvm::EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B,
139                        const TargetLibraryInfo *TLI, StringRef Name) {
140  if (!TLI->has(LibFunc::strcpy))
141    return nullptr;
142
143  Module *M = B.GetInsertBlock()->getParent()->getParent();
144  AttributeSet AS[2];
145  AS[0] = AttributeSet::get(M->getContext(), 2, Attribute::NoCapture);
146  AS[1] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex,
147                            Attribute::NoUnwind);
148  Type *I8Ptr = B.getInt8PtrTy();
149  Value *StrCpy = M->getOrInsertFunction(Name,
150                                         AttributeSet::get(M->getContext(), AS),
151                                         I8Ptr, I8Ptr, I8Ptr, nullptr);
152  CallInst *CI = B.CreateCall2(StrCpy, CastToCStr(Dst, B), CastToCStr(Src, B),
153                               Name);
154  if (const Function *F = dyn_cast<Function>(StrCpy->stripPointerCasts()))
155    CI->setCallingConv(F->getCallingConv());
156  return CI;
157}
158
159/// EmitStrNCpy - Emit a call to the strncpy function to the builder, for the
160/// specified pointer arguments.
161Value *llvm::EmitStrNCpy(Value *Dst, Value *Src, Value *Len, IRBuilder<> &B,
162                         const TargetLibraryInfo *TLI, StringRef Name) {
163  if (!TLI->has(LibFunc::strncpy))
164    return nullptr;
165
166  Module *M = B.GetInsertBlock()->getParent()->getParent();
167  AttributeSet AS[2];
168  AS[0] = AttributeSet::get(M->getContext(), 2, Attribute::NoCapture);
169  AS[1] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex,
170                            Attribute::NoUnwind);
171  Type *I8Ptr = B.getInt8PtrTy();
172  Value *StrNCpy = M->getOrInsertFunction(Name,
173                                          AttributeSet::get(M->getContext(),
174                                                            AS),
175                                          I8Ptr, I8Ptr, I8Ptr,
176                                          Len->getType(), nullptr);
177  CallInst *CI = B.CreateCall3(StrNCpy, CastToCStr(Dst, B), CastToCStr(Src, B),
178                               Len, "strncpy");
179  if (const Function *F = dyn_cast<Function>(StrNCpy->stripPointerCasts()))
180    CI->setCallingConv(F->getCallingConv());
181  return CI;
182}
183
184/// EmitMemCpyChk - Emit a call to the __memcpy_chk function to the builder.
185/// This expects that the Len and ObjSize have type 'intptr_t' and Dst/Src
186/// are pointers.
187Value *llvm::EmitMemCpyChk(Value *Dst, Value *Src, Value *Len, Value *ObjSize,
188                           IRBuilder<> &B, const DataLayout &DL,
189                           const TargetLibraryInfo *TLI) {
190  if (!TLI->has(LibFunc::memcpy_chk))
191    return nullptr;
192
193  Module *M = B.GetInsertBlock()->getParent()->getParent();
194  AttributeSet AS;
195  AS = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex,
196                         Attribute::NoUnwind);
197  LLVMContext &Context = B.GetInsertBlock()->getContext();
198  Value *MemCpy = M->getOrInsertFunction(
199      "__memcpy_chk", AttributeSet::get(M->getContext(), AS), B.getInt8PtrTy(),
200      B.getInt8PtrTy(), B.getInt8PtrTy(), DL.getIntPtrType(Context),
201      DL.getIntPtrType(Context), nullptr);
202  Dst = CastToCStr(Dst, B);
203  Src = CastToCStr(Src, B);
204  CallInst *CI = B.CreateCall4(MemCpy, Dst, Src, Len, ObjSize);
205  if (const Function *F = dyn_cast<Function>(MemCpy->stripPointerCasts()))
206    CI->setCallingConv(F->getCallingConv());
207  return CI;
208}
209
210/// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
211/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
212Value *llvm::EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B,
213                        const DataLayout &DL, const TargetLibraryInfo *TLI) {
214  if (!TLI->has(LibFunc::memchr))
215    return nullptr;
216
217  Module *M = B.GetInsertBlock()->getParent()->getParent();
218  AttributeSet AS;
219  Attribute::AttrKind AVs[2] = { Attribute::ReadOnly, Attribute::NoUnwind };
220  AS = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex, AVs);
221  LLVMContext &Context = B.GetInsertBlock()->getContext();
222  Value *MemChr = M->getOrInsertFunction(
223      "memchr", AttributeSet::get(M->getContext(), AS), B.getInt8PtrTy(),
224      B.getInt8PtrTy(), B.getInt32Ty(), DL.getIntPtrType(Context), nullptr);
225  CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
226
227  if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
228    CI->setCallingConv(F->getCallingConv());
229
230  return CI;
231}
232
233/// EmitMemCmp - Emit a call to the memcmp function.
234Value *llvm::EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B,
235                        const DataLayout &DL, const TargetLibraryInfo *TLI) {
236  if (!TLI->has(LibFunc::memcmp))
237    return nullptr;
238
239  Module *M = B.GetInsertBlock()->getParent()->getParent();
240  AttributeSet AS[3];
241  AS[0] = AttributeSet::get(M->getContext(), 1, Attribute::NoCapture);
242  AS[1] = AttributeSet::get(M->getContext(), 2, Attribute::NoCapture);
243  Attribute::AttrKind AVs[2] = { Attribute::ReadOnly, Attribute::NoUnwind };
244  AS[2] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex, AVs);
245
246  LLVMContext &Context = B.GetInsertBlock()->getContext();
247  Value *MemCmp = M->getOrInsertFunction(
248      "memcmp", AttributeSet::get(M->getContext(), AS), B.getInt32Ty(),
249      B.getInt8PtrTy(), B.getInt8PtrTy(), DL.getIntPtrType(Context), nullptr);
250  CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
251                               Len, "memcmp");
252
253  if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
254    CI->setCallingConv(F->getCallingConv());
255
256  return CI;
257}
258
259/// Append a suffix to the function name according to the type of 'Op'.
260static void AppendTypeSuffix(Value *Op, StringRef &Name, SmallString<20> &NameBuffer) {
261  if (!Op->getType()->isDoubleTy()) {
262      NameBuffer += Name;
263
264    if (Op->getType()->isFloatTy())
265      NameBuffer += 'f';
266    else
267      NameBuffer += 'l';
268
269    Name = NameBuffer;
270  }
271  return;
272}
273
274/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
275/// 'floor').  This function is known to take a single of type matching 'Op' and
276/// returns one value with the same type.  If 'Op' is a long double, 'l' is
277/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
278Value *llvm::EmitUnaryFloatFnCall(Value *Op, StringRef Name, IRBuilder<> &B,
279                                  const AttributeSet &Attrs) {
280  SmallString<20> NameBuffer;
281  AppendTypeSuffix(Op, Name, NameBuffer);
282
283  Module *M = B.GetInsertBlock()->getParent()->getParent();
284  Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
285                                         Op->getType(), nullptr);
286  CallInst *CI = B.CreateCall(Callee, Op, Name);
287  CI->setAttributes(Attrs);
288  if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
289    CI->setCallingConv(F->getCallingConv());
290
291  return CI;
292}
293
294/// EmitBinaryFloatFnCall - Emit a call to the binary function named 'Name'
295/// (e.g. 'fmin').  This function is known to take type matching 'Op1' and 'Op2'
296/// and return one value with the same type.  If 'Op1/Op2' are long double, 'l'
297/// is added as the suffix of name, if 'Op1/Op2' is a float, we add a 'f'
298/// suffix.
299Value *llvm::EmitBinaryFloatFnCall(Value *Op1, Value *Op2, StringRef Name,
300                                  IRBuilder<> &B, const AttributeSet &Attrs) {
301  SmallString<20> NameBuffer;
302  AppendTypeSuffix(Op1, Name, NameBuffer);
303
304  Module *M = B.GetInsertBlock()->getParent()->getParent();
305  Value *Callee = M->getOrInsertFunction(Name, Op1->getType(),
306                                         Op1->getType(), Op2->getType(), nullptr);
307  CallInst *CI = B.CreateCall2(Callee, Op1, Op2, Name);
308  CI->setAttributes(Attrs);
309  if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
310    CI->setCallingConv(F->getCallingConv());
311
312  return CI;
313}
314
315/// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
316/// is an integer.
317Value *llvm::EmitPutChar(Value *Char, IRBuilder<> &B,
318                         const TargetLibraryInfo *TLI) {
319  if (!TLI->has(LibFunc::putchar))
320    return nullptr;
321
322  Module *M = B.GetInsertBlock()->getParent()->getParent();
323  Value *PutChar = M->getOrInsertFunction("putchar", B.getInt32Ty(),
324                                          B.getInt32Ty(), nullptr);
325  CallInst *CI = B.CreateCall(PutChar,
326                              B.CreateIntCast(Char,
327                              B.getInt32Ty(),
328                              /*isSigned*/true,
329                              "chari"),
330                              "putchar");
331
332  if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
333    CI->setCallingConv(F->getCallingConv());
334  return CI;
335}
336
337/// EmitPutS - Emit a call to the puts function.  This assumes that Str is
338/// some pointer.
339Value *llvm::EmitPutS(Value *Str, IRBuilder<> &B,
340                      const TargetLibraryInfo *TLI) {
341  if (!TLI->has(LibFunc::puts))
342    return nullptr;
343
344  Module *M = B.GetInsertBlock()->getParent()->getParent();
345  AttributeSet AS[2];
346  AS[0] = AttributeSet::get(M->getContext(), 1, Attribute::NoCapture);
347  AS[1] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex,
348                            Attribute::NoUnwind);
349
350  Value *PutS = M->getOrInsertFunction("puts",
351                                       AttributeSet::get(M->getContext(), AS),
352                                       B.getInt32Ty(),
353                                       B.getInt8PtrTy(),
354                                       nullptr);
355  CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
356  if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
357    CI->setCallingConv(F->getCallingConv());
358  return CI;
359}
360
361/// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
362/// an integer and File is a pointer to FILE.
363Value *llvm::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B,
364                       const TargetLibraryInfo *TLI) {
365  if (!TLI->has(LibFunc::fputc))
366    return nullptr;
367
368  Module *M = B.GetInsertBlock()->getParent()->getParent();
369  AttributeSet AS[2];
370  AS[0] = AttributeSet::get(M->getContext(), 2, Attribute::NoCapture);
371  AS[1] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex,
372                            Attribute::NoUnwind);
373  Constant *F;
374  if (File->getType()->isPointerTy())
375    F = M->getOrInsertFunction("fputc",
376                               AttributeSet::get(M->getContext(), AS),
377                               B.getInt32Ty(),
378                               B.getInt32Ty(), File->getType(),
379                               nullptr);
380  else
381    F = M->getOrInsertFunction("fputc",
382                               B.getInt32Ty(),
383                               B.getInt32Ty(),
384                               File->getType(), nullptr);
385  Char = B.CreateIntCast(Char, B.getInt32Ty(), /*isSigned*/true,
386                         "chari");
387  CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
388
389  if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
390    CI->setCallingConv(Fn->getCallingConv());
391  return CI;
392}
393
394/// EmitFPutS - Emit a call to the puts function.  Str is required to be a
395/// pointer and File is a pointer to FILE.
396Value *llvm::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B,
397                       const TargetLibraryInfo *TLI) {
398  if (!TLI->has(LibFunc::fputs))
399    return nullptr;
400
401  Module *M = B.GetInsertBlock()->getParent()->getParent();
402  AttributeSet AS[3];
403  AS[0] = AttributeSet::get(M->getContext(), 1, Attribute::NoCapture);
404  AS[1] = AttributeSet::get(M->getContext(), 2, Attribute::NoCapture);
405  AS[2] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex,
406                            Attribute::NoUnwind);
407  StringRef FPutsName = TLI->getName(LibFunc::fputs);
408  Constant *F;
409  if (File->getType()->isPointerTy())
410    F = M->getOrInsertFunction(FPutsName,
411                               AttributeSet::get(M->getContext(), AS),
412                               B.getInt32Ty(),
413                               B.getInt8PtrTy(),
414                               File->getType(), nullptr);
415  else
416    F = M->getOrInsertFunction(FPutsName, B.getInt32Ty(),
417                               B.getInt8PtrTy(),
418                               File->getType(), nullptr);
419  CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
420
421  if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
422    CI->setCallingConv(Fn->getCallingConv());
423  return CI;
424}
425
426/// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
427/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
428Value *llvm::EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B,
429                        const DataLayout &DL, const TargetLibraryInfo *TLI) {
430  if (!TLI->has(LibFunc::fwrite))
431    return nullptr;
432
433  Module *M = B.GetInsertBlock()->getParent()->getParent();
434  AttributeSet AS[3];
435  AS[0] = AttributeSet::get(M->getContext(), 1, Attribute::NoCapture);
436  AS[1] = AttributeSet::get(M->getContext(), 4, Attribute::NoCapture);
437  AS[2] = AttributeSet::get(M->getContext(), AttributeSet::FunctionIndex,
438                            Attribute::NoUnwind);
439  LLVMContext &Context = B.GetInsertBlock()->getContext();
440  StringRef FWriteName = TLI->getName(LibFunc::fwrite);
441  Constant *F;
442  if (File->getType()->isPointerTy())
443    F = M->getOrInsertFunction(
444        FWriteName, AttributeSet::get(M->getContext(), AS),
445        DL.getIntPtrType(Context), B.getInt8PtrTy(), DL.getIntPtrType(Context),
446        DL.getIntPtrType(Context), File->getType(), nullptr);
447  else
448    F = M->getOrInsertFunction(FWriteName, DL.getIntPtrType(Context),
449                               B.getInt8PtrTy(), DL.getIntPtrType(Context),
450                               DL.getIntPtrType(Context), File->getType(),
451                               nullptr);
452  CallInst *CI =
453      B.CreateCall4(F, CastToCStr(Ptr, B), Size,
454                    ConstantInt::get(DL.getIntPtrType(Context), 1), File);
455
456  if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
457    CI->setCallingConv(Fn->getCallingConv());
458  return CI;
459}
460