1 //===----- CGCall.h - Encapsulate calling convention details ----*- C++ -*-===// 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 // These classes wrap the information about a call or function 11 // definition used to handle ABI compliancy. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CGCall.h" 16 #include "CodeGenFunction.h" 17 #include "CodeGenModule.h" 18 #include "clang/Basic/TargetInfo.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/Frontend/CompileOptions.h" 23 #include "llvm/Attributes.h" 24 #include "llvm/Support/CallSite.h" 25 #include "llvm/Target/TargetData.h" 26 27 #include "ABIInfo.h" 28 29 using namespace clang; 30 using namespace CodeGen; 31 32 /***/ 33 34 // FIXME: Use iterator and sidestep silly type array creation. 35 36 const 37 CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) { 38 return getFunctionInfo(FTNP->getResultType(), 39 llvm::SmallVector<QualType, 16>()); 40 } 41 42 const 43 CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) { 44 llvm::SmallVector<QualType, 16> ArgTys; 45 // FIXME: Kill copy. 46 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 47 ArgTys.push_back(FTP->getArgType(i)); 48 return getFunctionInfo(FTP->getResultType(), ArgTys); 49 } 50 51 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) { 52 llvm::SmallVector<QualType, 16> ArgTys; 53 // Add the 'this' pointer unless this is a static method. 54 if (MD->isInstance()) 55 ArgTys.push_back(MD->getThisType(Context)); 56 57 const FunctionProtoType *FTP = MD->getType()->getAsFunctionProtoType(); 58 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 59 ArgTys.push_back(FTP->getArgType(i)); 60 return getFunctionInfo(FTP->getResultType(), ArgTys); 61 } 62 63 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) { 64 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 65 if (MD->isInstance()) 66 return getFunctionInfo(MD); 67 68 const FunctionType *FTy = FD->getType()->getAsFunctionType(); 69 if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FTy)) 70 return getFunctionInfo(FTP); 71 return getFunctionInfo(cast<FunctionNoProtoType>(FTy)); 72 } 73 74 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) { 75 llvm::SmallVector<QualType, 16> ArgTys; 76 ArgTys.push_back(MD->getSelfDecl()->getType()); 77 ArgTys.push_back(Context.getObjCSelType()); 78 // FIXME: Kill copy? 79 for (ObjCMethodDecl::param_iterator i = MD->param_begin(), 80 e = MD->param_end(); i != e; ++i) 81 ArgTys.push_back((*i)->getType()); 82 return getFunctionInfo(MD->getResultType(), ArgTys); 83 } 84 85 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, 86 const CallArgList &Args) { 87 // FIXME: Kill copy. 88 llvm::SmallVector<QualType, 16> ArgTys; 89 for (CallArgList::const_iterator i = Args.begin(), e = Args.end(); 90 i != e; ++i) 91 ArgTys.push_back(i->second); 92 return getFunctionInfo(ResTy, ArgTys); 93 } 94 95 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, 96 const FunctionArgList &Args) { 97 // FIXME: Kill copy. 98 llvm::SmallVector<QualType, 16> ArgTys; 99 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 100 i != e; ++i) 101 ArgTys.push_back(i->second); 102 return getFunctionInfo(ResTy, ArgTys); 103 } 104 105 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, 106 const llvm::SmallVector<QualType, 16> &ArgTys) { 107 // Lookup or create unique function info. 108 llvm::FoldingSetNodeID ID; 109 CGFunctionInfo::Profile(ID, ResTy, ArgTys.begin(), ArgTys.end()); 110 111 void *InsertPos = 0; 112 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos); 113 if (FI) 114 return *FI; 115 116 // Construct the function info. 117 FI = new CGFunctionInfo(ResTy, ArgTys); 118 FunctionInfos.InsertNode(FI, InsertPos); 119 120 // Compute ABI information. 121 getABIInfo().computeInfo(*FI, getContext(), TheModule.getContext()); 122 123 return *FI; 124 } 125 126 CGFunctionInfo::CGFunctionInfo(QualType ResTy, 127 const llvm::SmallVector<QualType, 16> &ArgTys) { 128 NumArgs = ArgTys.size(); 129 Args = new ArgInfo[1 + NumArgs]; 130 Args[0].type = ResTy; 131 for (unsigned i = 0; i < NumArgs; ++i) 132 Args[1 + i].type = ArgTys[i]; 133 } 134 135 /***/ 136 137 void CodeGenTypes::GetExpandedTypes(QualType Ty, 138 std::vector<const llvm::Type*> &ArgTys) { 139 const RecordType *RT = Ty->getAsStructureType(); 140 assert(RT && "Can only expand structure types."); 141 const RecordDecl *RD = RT->getDecl(); 142 assert(!RD->hasFlexibleArrayMember() && 143 "Cannot expand structure with flexible array."); 144 145 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 146 i != e; ++i) { 147 const FieldDecl *FD = *i; 148 assert(!FD->isBitField() && 149 "Cannot expand structure with bit-field members."); 150 151 QualType FT = FD->getType(); 152 if (CodeGenFunction::hasAggregateLLVMType(FT)) { 153 GetExpandedTypes(FT, ArgTys); 154 } else { 155 ArgTys.push_back(ConvertType(FT)); 156 } 157 } 158 } 159 160 llvm::Function::arg_iterator 161 CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV, 162 llvm::Function::arg_iterator AI) { 163 const RecordType *RT = Ty->getAsStructureType(); 164 assert(RT && "Can only expand structure types."); 165 166 RecordDecl *RD = RT->getDecl(); 167 assert(LV.isSimple() && 168 "Unexpected non-simple lvalue during struct expansion."); 169 llvm::Value *Addr = LV.getAddress(); 170 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 171 i != e; ++i) { 172 FieldDecl *FD = *i; 173 QualType FT = FD->getType(); 174 175 // FIXME: What are the right qualifiers here? 176 LValue LV = EmitLValueForField(Addr, FD, false, 0); 177 if (CodeGenFunction::hasAggregateLLVMType(FT)) { 178 AI = ExpandTypeFromArgs(FT, LV, AI); 179 } else { 180 EmitStoreThroughLValue(RValue::get(AI), LV, FT); 181 ++AI; 182 } 183 } 184 185 return AI; 186 } 187 188 void 189 CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, 190 llvm::SmallVector<llvm::Value*, 16> &Args) { 191 const RecordType *RT = Ty->getAsStructureType(); 192 assert(RT && "Can only expand structure types."); 193 194 RecordDecl *RD = RT->getDecl(); 195 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion"); 196 llvm::Value *Addr = RV.getAggregateAddr(); 197 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 198 i != e; ++i) { 199 FieldDecl *FD = *i; 200 QualType FT = FD->getType(); 201 202 // FIXME: What are the right qualifiers here? 203 LValue LV = EmitLValueForField(Addr, FD, false, 0); 204 if (CodeGenFunction::hasAggregateLLVMType(FT)) { 205 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args); 206 } else { 207 RValue RV = EmitLoadOfLValue(LV, FT); 208 assert(RV.isScalar() && 209 "Unexpected non-scalar rvalue during struct expansion."); 210 Args.push_back(RV.getScalarVal()); 211 } 212 } 213 } 214 215 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as 216 /// a pointer to an object of type \arg Ty. 217 /// 218 /// This safely handles the case when the src type is smaller than the 219 /// destination type; in this situation the values of bits which not 220 /// present in the src are undefined. 221 static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr, 222 const llvm::Type *Ty, 223 CodeGenFunction &CGF) { 224 const llvm::Type *SrcTy = 225 cast<llvm::PointerType>(SrcPtr->getType())->getElementType(); 226 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); 227 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty); 228 229 // If load is legal, just bitcast the src pointer. 230 if (SrcSize >= DstSize) { 231 // Generally SrcSize is never greater than DstSize, since this means we are 232 // losing bits. However, this can happen in cases where the structure has 233 // additional padding, for example due to a user specified alignment. 234 // 235 // FIXME: Assert that we aren't truncating non-padding bits when have access 236 // to that information. 237 llvm::Value *Casted = 238 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty)); 239 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); 240 // FIXME: Use better alignment / avoid requiring aligned load. 241 Load->setAlignment(1); 242 return Load; 243 } else { 244 // Otherwise do coercion through memory. This is stupid, but 245 // simple. 246 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty); 247 llvm::Value *Casted = 248 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy)); 249 llvm::StoreInst *Store = 250 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted); 251 // FIXME: Use better alignment / avoid requiring aligned store. 252 Store->setAlignment(1); 253 return CGF.Builder.CreateLoad(Tmp); 254 } 255 } 256 257 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 258 /// where the source and destination may have different types. 259 /// 260 /// This safely handles the case when the src type is larger than the 261 /// destination type; the upper bits of the src will be lost. 262 static void CreateCoercedStore(llvm::Value *Src, 263 llvm::Value *DstPtr, 264 CodeGenFunction &CGF) { 265 const llvm::Type *SrcTy = Src->getType(); 266 const llvm::Type *DstTy = 267 cast<llvm::PointerType>(DstPtr->getType())->getElementType(); 268 269 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); 270 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy); 271 272 // If store is legal, just bitcast the src pointer. 273 if (SrcSize <= DstSize) { 274 llvm::Value *Casted = 275 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy)); 276 // FIXME: Use better alignment / avoid requiring aligned store. 277 CGF.Builder.CreateStore(Src, Casted)->setAlignment(1); 278 } else { 279 // Otherwise do coercion through memory. This is stupid, but 280 // simple. 281 282 // Generally SrcSize is never greater than DstSize, since this means we are 283 // losing bits. However, this can happen in cases where the structure has 284 // additional padding, for example due to a user specified alignment. 285 // 286 // FIXME: Assert that we aren't truncating non-padding bits when have access 287 // to that information. 288 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy); 289 CGF.Builder.CreateStore(Src, Tmp); 290 llvm::Value *Casted = 291 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy)); 292 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); 293 // FIXME: Use better alignment / avoid requiring aligned load. 294 Load->setAlignment(1); 295 CGF.Builder.CreateStore(Load, DstPtr); 296 } 297 } 298 299 /***/ 300 301 bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) { 302 return FI.getReturnInfo().isIndirect(); 303 } 304 305 const llvm::FunctionType * 306 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) { 307 std::vector<const llvm::Type*> ArgTys; 308 309 const llvm::Type *ResultType = 0; 310 311 QualType RetTy = FI.getReturnType(); 312 const ABIArgInfo &RetAI = FI.getReturnInfo(); 313 switch (RetAI.getKind()) { 314 case ABIArgInfo::Expand: 315 assert(0 && "Invalid ABI kind for return argument"); 316 317 case ABIArgInfo::Extend: 318 case ABIArgInfo::Direct: 319 ResultType = ConvertType(RetTy); 320 break; 321 322 case ABIArgInfo::Indirect: { 323 assert(!RetAI.getIndirectAlign() && "Align unused on indirect return."); 324 ResultType = llvm::Type::VoidTy; 325 const llvm::Type *STy = ConvertType(RetTy); 326 ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace())); 327 break; 328 } 329 330 case ABIArgInfo::Ignore: 331 ResultType = llvm::Type::VoidTy; 332 break; 333 334 case ABIArgInfo::Coerce: 335 ResultType = RetAI.getCoerceToType(); 336 break; 337 } 338 339 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 340 ie = FI.arg_end(); it != ie; ++it) { 341 const ABIArgInfo &AI = it->info; 342 343 switch (AI.getKind()) { 344 case ABIArgInfo::Ignore: 345 break; 346 347 case ABIArgInfo::Coerce: 348 ArgTys.push_back(AI.getCoerceToType()); 349 break; 350 351 case ABIArgInfo::Indirect: { 352 // indirect arguments are always on the stack, which is addr space #0. 353 const llvm::Type *LTy = ConvertTypeForMem(it->type); 354 ArgTys.push_back(llvm::PointerType::getUnqual(LTy)); 355 break; 356 } 357 358 case ABIArgInfo::Extend: 359 case ABIArgInfo::Direct: 360 ArgTys.push_back(ConvertType(it->type)); 361 break; 362 363 case ABIArgInfo::Expand: 364 GetExpandedTypes(it->type, ArgTys); 365 break; 366 } 367 } 368 369 return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic); 370 } 371 372 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, 373 const Decl *TargetDecl, 374 AttributeListType &PAL) { 375 unsigned FuncAttrs = 0; 376 unsigned RetAttrs = 0; 377 378 // FIXME: handle sseregparm someday... 379 if (TargetDecl) { 380 if (TargetDecl->hasAttr<NoThrowAttr>()) 381 FuncAttrs |= llvm::Attribute::NoUnwind; 382 if (TargetDecl->hasAttr<NoReturnAttr>()) 383 FuncAttrs |= llvm::Attribute::NoReturn; 384 if (TargetDecl->hasAttr<ConstAttr>()) 385 FuncAttrs |= llvm::Attribute::ReadNone; 386 else if (TargetDecl->hasAttr<PureAttr>()) 387 FuncAttrs |= llvm::Attribute::ReadOnly; 388 } 389 390 if (CompileOpts.DisableRedZone) 391 FuncAttrs |= llvm::Attribute::NoRedZone; 392 if (CompileOpts.NoImplicitFloat) 393 FuncAttrs |= llvm::Attribute::NoImplicitFloat; 394 395 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 396 FuncAttrs |= llvm::Attribute::StackProtect; 397 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 398 FuncAttrs |= llvm::Attribute::StackProtectReq; 399 400 QualType RetTy = FI.getReturnType(); 401 unsigned Index = 1; 402 const ABIArgInfo &RetAI = FI.getReturnInfo(); 403 switch (RetAI.getKind()) { 404 case ABIArgInfo::Extend: 405 if (RetTy->isSignedIntegerType()) { 406 RetAttrs |= llvm::Attribute::SExt; 407 } else if (RetTy->isUnsignedIntegerType()) { 408 RetAttrs |= llvm::Attribute::ZExt; 409 } 410 // FALLTHROUGH 411 case ABIArgInfo::Direct: 412 break; 413 414 case ABIArgInfo::Indirect: 415 PAL.push_back(llvm::AttributeWithIndex::get(Index, 416 llvm::Attribute::StructRet | 417 llvm::Attribute::NoAlias)); 418 ++Index; 419 // sret disables readnone and readonly 420 FuncAttrs &= ~(llvm::Attribute::ReadOnly | 421 llvm::Attribute::ReadNone); 422 break; 423 424 case ABIArgInfo::Ignore: 425 case ABIArgInfo::Coerce: 426 break; 427 428 case ABIArgInfo::Expand: 429 assert(0 && "Invalid ABI kind for return argument"); 430 } 431 432 if (RetAttrs) 433 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs)); 434 435 // FIXME: we need to honour command line settings also... 436 // FIXME: RegParm should be reduced in case of nested functions and/or global 437 // register variable. 438 signed RegParm = 0; 439 if (TargetDecl) 440 if (const RegparmAttr *RegParmAttr 441 = TargetDecl->getAttr<RegparmAttr>()) 442 RegParm = RegParmAttr->getNumParams(); 443 444 unsigned PointerWidth = getContext().Target.getPointerWidth(0); 445 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 446 ie = FI.arg_end(); it != ie; ++it) { 447 QualType ParamType = it->type; 448 const ABIArgInfo &AI = it->info; 449 unsigned Attributes = 0; 450 451 switch (AI.getKind()) { 452 case ABIArgInfo::Coerce: 453 break; 454 455 case ABIArgInfo::Indirect: 456 Attributes |= llvm::Attribute::ByVal; 457 Attributes |= 458 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign()); 459 // byval disables readnone and readonly. 460 FuncAttrs &= ~(llvm::Attribute::ReadOnly | 461 llvm::Attribute::ReadNone); 462 break; 463 464 case ABIArgInfo::Extend: 465 if (ParamType->isSignedIntegerType()) { 466 Attributes |= llvm::Attribute::SExt; 467 } else if (ParamType->isUnsignedIntegerType()) { 468 Attributes |= llvm::Attribute::ZExt; 469 } 470 // FALLS THROUGH 471 case ABIArgInfo::Direct: 472 if (RegParm > 0 && 473 (ParamType->isIntegerType() || ParamType->isPointerType())) { 474 RegParm -= 475 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth; 476 if (RegParm >= 0) 477 Attributes |= llvm::Attribute::InReg; 478 } 479 // FIXME: handle sseregparm someday... 480 break; 481 482 case ABIArgInfo::Ignore: 483 // Skip increment, no matching LLVM parameter. 484 continue; 485 486 case ABIArgInfo::Expand: { 487 std::vector<const llvm::Type*> Tys; 488 // FIXME: This is rather inefficient. Do we ever actually need to do 489 // anything here? The result should be just reconstructed on the other 490 // side, so extension should be a non-issue. 491 getTypes().GetExpandedTypes(ParamType, Tys); 492 Index += Tys.size(); 493 continue; 494 } 495 } 496 497 if (Attributes) 498 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes)); 499 ++Index; 500 } 501 if (FuncAttrs) 502 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs)); 503 } 504 505 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 506 llvm::Function *Fn, 507 const FunctionArgList &Args) { 508 // If this is an implicit-return-zero function, go ahead and 509 // initialize the return value. TODO: it might be nice to have 510 // a more general mechanism for this that didn't require synthesized 511 // return statements. 512 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(CurFuncDecl)) { 513 if (FD->hasImplicitReturnZero()) { 514 QualType RetTy = FD->getResultType().getUnqualifiedType(); 515 const llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 516 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 517 Builder.CreateStore(Zero, ReturnValue); 518 } 519 } 520 521 // FIXME: We no longer need the types from FunctionArgList; lift up and 522 // simplify. 523 524 // Emit allocs for param decls. Give the LLVM Argument nodes names. 525 llvm::Function::arg_iterator AI = Fn->arg_begin(); 526 527 // Name the struct return argument. 528 if (CGM.ReturnTypeUsesSret(FI)) { 529 AI->setName("agg.result"); 530 ++AI; 531 } 532 533 assert(FI.arg_size() == Args.size() && 534 "Mismatch between function signature & arguments."); 535 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 536 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 537 i != e; ++i, ++info_it) { 538 const VarDecl *Arg = i->first; 539 QualType Ty = info_it->type; 540 const ABIArgInfo &ArgI = info_it->info; 541 542 switch (ArgI.getKind()) { 543 case ABIArgInfo::Indirect: { 544 llvm::Value* V = AI; 545 if (hasAggregateLLVMType(Ty)) { 546 // Do nothing, aggregates and complex variables are accessed by 547 // reference. 548 } else { 549 // Load scalar value from indirect argument. 550 V = EmitLoadOfScalar(V, false, Ty); 551 if (!getContext().typesAreCompatible(Ty, Arg->getType())) { 552 // This must be a promotion, for something like 553 // "void a(x) short x; {..." 554 V = EmitScalarConversion(V, Ty, Arg->getType()); 555 } 556 } 557 EmitParmDecl(*Arg, V); 558 break; 559 } 560 561 case ABIArgInfo::Extend: 562 case ABIArgInfo::Direct: { 563 assert(AI != Fn->arg_end() && "Argument mismatch!"); 564 llvm::Value* V = AI; 565 if (hasAggregateLLVMType(Ty)) { 566 // Create a temporary alloca to hold the argument; the rest of 567 // codegen expects to access aggregates & complex values by 568 // reference. 569 V = CreateTempAlloca(ConvertTypeForMem(Ty)); 570 Builder.CreateStore(AI, V); 571 } else { 572 if (!getContext().typesAreCompatible(Ty, Arg->getType())) { 573 // This must be a promotion, for something like 574 // "void a(x) short x; {..." 575 V = EmitScalarConversion(V, Ty, Arg->getType()); 576 } 577 } 578 EmitParmDecl(*Arg, V); 579 break; 580 } 581 582 case ABIArgInfo::Expand: { 583 // If this structure was expanded into multiple arguments then 584 // we need to create a temporary and reconstruct it from the 585 // arguments. 586 std::string Name = Arg->getNameAsString(); 587 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty), 588 (Name + ".addr").c_str()); 589 // FIXME: What are the right qualifiers here? 590 llvm::Function::arg_iterator End = 591 ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI); 592 EmitParmDecl(*Arg, Temp); 593 594 // Name the arguments used in expansion and increment AI. 595 unsigned Index = 0; 596 for (; AI != End; ++AI, ++Index) 597 AI->setName(Name + "." + llvm::Twine(Index)); 598 continue; 599 } 600 601 case ABIArgInfo::Ignore: 602 // Initialize the local variable appropriately. 603 if (hasAggregateLLVMType(Ty)) { 604 EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty))); 605 } else { 606 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType()))); 607 } 608 609 // Skip increment, no matching LLVM parameter. 610 continue; 611 612 case ABIArgInfo::Coerce: { 613 assert(AI != Fn->arg_end() && "Argument mismatch!"); 614 // FIXME: This is very wasteful; EmitParmDecl is just going to drop the 615 // result in a new alloca anyway, so we could just store into that 616 // directly if we broke the abstraction down more. 617 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce"); 618 CreateCoercedStore(AI, V, *this); 619 // Match to what EmitParmDecl is expecting for this type. 620 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) { 621 V = EmitLoadOfScalar(V, false, Ty); 622 if (!getContext().typesAreCompatible(Ty, Arg->getType())) { 623 // This must be a promotion, for something like 624 // "void a(x) short x; {..." 625 V = EmitScalarConversion(V, Ty, Arg->getType()); 626 } 627 } 628 EmitParmDecl(*Arg, V); 629 break; 630 } 631 } 632 633 ++AI; 634 } 635 assert(AI == Fn->arg_end() && "Argument mismatch!"); 636 } 637 638 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 639 llvm::Value *ReturnValue) { 640 llvm::Value *RV = 0; 641 642 // Functions with no result always return void. 643 if (ReturnValue) { 644 QualType RetTy = FI.getReturnType(); 645 const ABIArgInfo &RetAI = FI.getReturnInfo(); 646 647 switch (RetAI.getKind()) { 648 case ABIArgInfo::Indirect: 649 if (RetTy->isAnyComplexType()) { 650 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false); 651 StoreComplexToAddr(RT, CurFn->arg_begin(), false); 652 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { 653 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy); 654 } else { 655 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(), 656 false, RetTy); 657 } 658 break; 659 660 case ABIArgInfo::Extend: 661 case ABIArgInfo::Direct: 662 // The internal return value temp always will have 663 // pointer-to-return-type type. 664 RV = Builder.CreateLoad(ReturnValue); 665 break; 666 667 case ABIArgInfo::Ignore: 668 break; 669 670 case ABIArgInfo::Coerce: 671 RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this); 672 break; 673 674 case ABIArgInfo::Expand: 675 assert(0 && "Invalid ABI kind for return argument"); 676 } 677 } 678 679 if (RV) { 680 Builder.CreateRet(RV); 681 } else { 682 Builder.CreateRetVoid(); 683 } 684 } 685 686 RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) { 687 if (ArgType->isReferenceType()) 688 return EmitReferenceBindingToExpr(E, ArgType); 689 690 return EmitAnyExprToTemp(E); 691 } 692 693 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 694 llvm::Value *Callee, 695 const CallArgList &CallArgs, 696 const Decl *TargetDecl) { 697 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 698 llvm::SmallVector<llvm::Value*, 16> Args; 699 700 // Handle struct-return functions by passing a pointer to the 701 // location that we would like to return into. 702 QualType RetTy = CallInfo.getReturnType(); 703 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 704 705 706 // If the call returns a temporary with struct return, create a temporary 707 // alloca to hold the result. 708 if (CGM.ReturnTypeUsesSret(CallInfo)) 709 Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy))); 710 711 assert(CallInfo.arg_size() == CallArgs.size() && 712 "Mismatch between function signature & arguments."); 713 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 714 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 715 I != E; ++I, ++info_it) { 716 const ABIArgInfo &ArgInfo = info_it->info; 717 RValue RV = I->first; 718 719 switch (ArgInfo.getKind()) { 720 case ABIArgInfo::Indirect: 721 if (RV.isScalar() || RV.isComplex()) { 722 // Make a temporary alloca to pass the argument. 723 Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second))); 724 if (RV.isScalar()) 725 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second); 726 else 727 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false); 728 } else { 729 Args.push_back(RV.getAggregateAddr()); 730 } 731 break; 732 733 case ABIArgInfo::Extend: 734 case ABIArgInfo::Direct: 735 if (RV.isScalar()) { 736 Args.push_back(RV.getScalarVal()); 737 } else if (RV.isComplex()) { 738 llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second)); 739 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0); 740 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1); 741 Args.push_back(Tmp); 742 } else { 743 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr())); 744 } 745 break; 746 747 case ABIArgInfo::Ignore: 748 break; 749 750 case ABIArgInfo::Coerce: { 751 // FIXME: Avoid the conversion through memory if possible. 752 llvm::Value *SrcPtr; 753 if (RV.isScalar()) { 754 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce"); 755 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, I->second); 756 } else if (RV.isComplex()) { 757 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce"); 758 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false); 759 } else 760 SrcPtr = RV.getAggregateAddr(); 761 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), 762 *this)); 763 break; 764 } 765 766 case ABIArgInfo::Expand: 767 ExpandTypeToArgs(I->second, RV, Args); 768 break; 769 } 770 } 771 772 // If the callee is a bitcast of a function to a varargs pointer to function 773 // type, check to see if we can remove the bitcast. This handles some cases 774 // with unprototyped functions. 775 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee)) 776 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) { 777 const llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType()); 778 const llvm::FunctionType *CurFT = 779 cast<llvm::FunctionType>(CurPT->getElementType()); 780 const llvm::FunctionType *ActualFT = CalleeF->getFunctionType(); 781 782 if (CE->getOpcode() == llvm::Instruction::BitCast && 783 ActualFT->getReturnType() == CurFT->getReturnType() && 784 ActualFT->getNumParams() == CurFT->getNumParams() && 785 ActualFT->getNumParams() == Args.size()) { 786 bool ArgsMatch = true; 787 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i) 788 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) { 789 ArgsMatch = false; 790 break; 791 } 792 793 // Strip the cast if we can get away with it. This is a nice cleanup, 794 // but also allows us to inline the function at -O0 if it is marked 795 // always_inline. 796 if (ArgsMatch) 797 Callee = CalleeF; 798 } 799 } 800 801 802 llvm::BasicBlock *InvokeDest = getInvokeDest(); 803 CodeGen::AttributeListType AttributeList; 804 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList); 805 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(), 806 AttributeList.end()); 807 808 llvm::CallSite CS; 809 if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) { 810 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size()); 811 } else { 812 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 813 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, 814 Args.data(), Args.data()+Args.size()); 815 EmitBlock(Cont); 816 } 817 818 CS.setAttributes(Attrs); 819 if (const llvm::Function *F = 820 dyn_cast<llvm::Function>(Callee->stripPointerCasts())) 821 CS.setCallingConv(F->getCallingConv()); 822 823 // If the call doesn't return, finish the basic block and clear the 824 // insertion point; this allows the rest of IRgen to discard 825 // unreachable code. 826 if (CS.doesNotReturn()) { 827 Builder.CreateUnreachable(); 828 Builder.ClearInsertionPoint(); 829 830 // FIXME: For now, emit a dummy basic block because expr emitters in 831 // generally are not ready to handle emitting expressions at unreachable 832 // points. 833 EnsureInsertPoint(); 834 835 // Return a reasonable RValue. 836 return GetUndefRValue(RetTy); 837 } 838 839 llvm::Instruction *CI = CS.getInstruction(); 840 if (Builder.isNamePreserving() && CI->getType() != llvm::Type::VoidTy) 841 CI->setName("call"); 842 843 switch (RetAI.getKind()) { 844 case ABIArgInfo::Indirect: 845 if (RetTy->isAnyComplexType()) 846 return RValue::getComplex(LoadComplexFromAddr(Args[0], false)); 847 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) 848 return RValue::getAggregate(Args[0]); 849 return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy)); 850 851 case ABIArgInfo::Extend: 852 case ABIArgInfo::Direct: 853 if (RetTy->isAnyComplexType()) { 854 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 855 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 856 return RValue::getComplex(std::make_pair(Real, Imag)); 857 } 858 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { 859 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp"); 860 Builder.CreateStore(CI, V); 861 return RValue::getAggregate(V); 862 } 863 return RValue::get(CI); 864 865 case ABIArgInfo::Ignore: 866 // If we are ignoring an argument that had a result, make sure to 867 // construct the appropriate return value for our caller. 868 return GetUndefRValue(RetTy); 869 870 case ABIArgInfo::Coerce: { 871 // FIXME: Avoid the conversion through memory if possible. 872 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce"); 873 CreateCoercedStore(CI, V, *this); 874 if (RetTy->isAnyComplexType()) 875 return RValue::getComplex(LoadComplexFromAddr(V, false)); 876 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) 877 return RValue::getAggregate(V); 878 return RValue::get(EmitLoadOfScalar(V, false, RetTy)); 879 } 880 881 case ABIArgInfo::Expand: 882 assert(0 && "Invalid ABI kind for return argument"); 883 } 884 885 assert(0 && "Unhandled ABIArgInfo::Kind"); 886 return RValue::get(0); 887 } 888 889 /* VarArg handling */ 890 891 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) { 892 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this); 893 } 894