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