CGExprAgg.cpp revision 7e91627301b05cd8f2324795e19d87a62f444c31
1//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 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 contains code to emit Aggregate Expr nodes as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CodeGenModule.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/StmtVisitor.h" 18#include "llvm/Constants.h" 19#include "llvm/Function.h" 20#include "llvm/GlobalVariable.h" 21#include "llvm/Support/Compiler.h" 22#include "llvm/Intrinsics.h" 23using namespace clang; 24using namespace CodeGen; 25 26//===----------------------------------------------------------------------===// 27// Aggregate Expression Emitter 28//===----------------------------------------------------------------------===// 29 30namespace { 31class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> { 32 CodeGenFunction &CGF; 33 CGBuilderTy &Builder; 34 llvm::Value *DestPtr; 35 bool VolatileDest; 36public: 37 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest) 38 : CGF(cgf), Builder(CGF.Builder), 39 DestPtr(destPtr), VolatileDest(volatileDest) { 40 } 41 42 //===--------------------------------------------------------------------===// 43 // Utilities 44 //===--------------------------------------------------------------------===// 45 46 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 47 /// represents a value lvalue, this method emits the address of the lvalue, 48 /// then loads the result into DestPtr. 49 void EmitAggLoadOfLValue(const Expr *E); 50 51 void EmitNonConstInit(InitListExpr *E); 52 53 //===--------------------------------------------------------------------===// 54 // Visitor Methods 55 //===--------------------------------------------------------------------===// 56 57 void VisitStmt(Stmt *S) { 58 CGF.ErrorUnsupported(S, "aggregate expression"); 59 } 60 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 61 62 // l-values. 63 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 64 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 65 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 66 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 67 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) 68 { EmitAggLoadOfLValue(E); } 69 70 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 71 EmitAggLoadOfLValue(E); 72 } 73 74 // Operators. 75 // case Expr::UnaryOperatorClass: 76 // case Expr::CastExprClass: 77 void VisitCStyleCastExpr(CStyleCastExpr *E); 78 void VisitImplicitCastExpr(ImplicitCastExpr *E); 79 void VisitCallExpr(const CallExpr *E); 80 void VisitStmtExpr(const StmtExpr *E); 81 void VisitBinaryOperator(const BinaryOperator *BO); 82 void VisitBinAssign(const BinaryOperator *E); 83 void VisitOverloadExpr(const OverloadExpr *E); 84 void VisitBinComma(const BinaryOperator *E); 85 86 void VisitObjCMessageExpr(ObjCMessageExpr *E); 87 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 88 EmitAggLoadOfLValue(E); 89 } 90 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 91 void VisitObjCKVCRefExpr(ObjCKVCRefExpr *E); 92 93 void VisitConditionalOperator(const ConditionalOperator *CO); 94 void VisitInitListExpr(InitListExpr *E); 95 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 96 Visit(DAE->getExpr()); 97 } 98 void VisitVAArgExpr(VAArgExpr *E); 99 100 void EmitInitializationToLValue(Expr *E, LValue Address); 101 void EmitNullInitializationToLValue(LValue Address, QualType T); 102 // case Expr::ChooseExprClass: 103 104}; 105} // end anonymous namespace. 106 107//===----------------------------------------------------------------------===// 108// Utilities 109//===----------------------------------------------------------------------===// 110 111/// EmitAggLoadOfLValue - Given an expression with aggregate type that 112/// represents a value lvalue, this method emits the address of the lvalue, 113/// then loads the result into DestPtr. 114void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 115 LValue LV = CGF.EmitLValue(E); 116 assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc"); 117 llvm::Value *SrcPtr = LV.getAddress(); 118 119 // If the result is ignored, don't copy from the value. 120 if (DestPtr == 0) 121 // FIXME: If the source is volatile, we must read from it. 122 return; 123 124 CGF.EmitAggregateCopy(DestPtr, SrcPtr, E->getType()); 125} 126 127//===----------------------------------------------------------------------===// 128// Visitor Methods 129//===----------------------------------------------------------------------===// 130 131void AggExprEmitter::VisitCStyleCastExpr(CStyleCastExpr *E) { 132 // GCC union extension 133 if (E->getType()->isUnionType()) { 134 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 135 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *SD->field_begin(), true, 0); 136 EmitInitializationToLValue(E->getSubExpr(), FieldLoc); 137 return; 138 } 139 140 Visit(E->getSubExpr()); 141} 142 143void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 144 assert(CGF.getContext().typesAreCompatible( 145 E->getSubExpr()->getType().getUnqualifiedType(), 146 E->getType().getUnqualifiedType()) && 147 "Implicit cast types must be compatible"); 148 Visit(E->getSubExpr()); 149} 150 151void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 152 RValue RV = CGF.EmitCallExpr(E); 153 assert(RV.isAggregate() && "Return value must be aggregate value!"); 154 155 // If the result is ignored, don't copy from the value. 156 if (DestPtr == 0) 157 // FIXME: If the source is volatile, we must read from it. 158 return; 159 160 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 161} 162 163void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 164 RValue RV = CGF.EmitObjCMessageExpr(E); 165 assert(RV.isAggregate() && "Return value must be aggregate value!"); 166 167 // If the result is ignored, don't copy from the value. 168 if (DestPtr == 0) 169 // FIXME: If the source is volatile, we must read from it. 170 return; 171 172 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 173} 174 175void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 176 RValue RV = CGF.EmitObjCPropertyGet(E); 177 assert(RV.isAggregate() && "Return value must be aggregate value!"); 178 179 // If the result is ignored, don't copy from the value. 180 if (DestPtr == 0) 181 // FIXME: If the source is volatile, we must read from it. 182 return; 183 184 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 185} 186 187void AggExprEmitter::VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) { 188 RValue RV = CGF.EmitObjCPropertyGet(E); 189 assert(RV.isAggregate() && "Return value must be aggregate value!"); 190 191 // If the result is ignored, don't copy from the value. 192 if (DestPtr == 0) 193 // FIXME: If the source is volatile, we must read from it. 194 return; 195 196 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 197} 198 199void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) { 200 RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(), 201 E->arg_end(CGF.getContext())); 202 203 assert(RV.isAggregate() && "Return value must be aggregate value!"); 204 205 // If the result is ignored, don't copy from the value. 206 if (DestPtr == 0) 207 // FIXME: If the source is volatile, we must read from it. 208 return; 209 210 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 211} 212 213void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 214 CGF.EmitAnyExpr(E->getLHS()); 215 CGF.EmitAggExpr(E->getRHS(), DestPtr, false); 216} 217 218void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 219 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 220} 221 222void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 223 CGF.ErrorUnsupported(E, "aggregate binary expression"); 224} 225 226void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 227 // For an assignment to work, the value on the right has 228 // to be compatible with the value on the left. 229 assert(CGF.getContext().typesAreCompatible( 230 E->getLHS()->getType().getUnqualifiedType(), 231 E->getRHS()->getType().getUnqualifiedType()) 232 && "Invalid assignment"); 233 LValue LHS = CGF.EmitLValue(E->getLHS()); 234 235 // We have to special case property setters, otherwise we must have 236 // a simple lvalue (no aggregates inside vectors, bitfields). 237 if (LHS.isPropertyRef()) { 238 // FIXME: Volatility? 239 llvm::Value *AggLoc = DestPtr; 240 if (!AggLoc) 241 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 242 CGF.EmitAggExpr(E->getRHS(), AggLoc, false); 243 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 244 RValue::getAggregate(AggLoc)); 245 } 246 else if (LHS.isKVCRef()) { 247 // FIXME: Volatility? 248 llvm::Value *AggLoc = DestPtr; 249 if (!AggLoc) 250 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 251 CGF.EmitAggExpr(E->getRHS(), AggLoc, false); 252 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 253 RValue::getAggregate(AggLoc)); 254 } else { 255 // Codegen the RHS so that it stores directly into the LHS. 256 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/); 257 258 if (DestPtr == 0) 259 return; 260 261 // If the result of the assignment is used, copy the RHS there also. 262 CGF.EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType()); 263 } 264} 265 266void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 267 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 268 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 269 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 270 271 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 272 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 273 274 CGF.EmitBlock(LHSBlock); 275 276 // Handle the GNU extension for missing LHS. 277 assert(E->getLHS() && "Must have LHS for aggregate value"); 278 279 Visit(E->getLHS()); 280 CGF.EmitBranch(ContBlock); 281 282 CGF.EmitBlock(RHSBlock); 283 284 Visit(E->getRHS()); 285 CGF.EmitBranch(ContBlock); 286 287 CGF.EmitBlock(ContBlock); 288} 289 290void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 291 llvm::Value *ArgValue = CGF.EmitLValue(VE->getSubExpr()).getAddress(); 292 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 293 294 if (!ArgPtr) { 295 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 296 return; 297 } 298 299 if (DestPtr) 300 // FIXME: volatility 301 CGF.EmitAggregateCopy(DestPtr, ArgPtr, VE->getType()); 302} 303 304void AggExprEmitter::EmitNonConstInit(InitListExpr *E) { 305 if (E->hadDesignators()) { 306 CGF.ErrorUnsupported(E, "initializer list with designators"); 307 return; 308 } 309 310 const llvm::PointerType *APType = 311 cast<llvm::PointerType>(DestPtr->getType()); 312 const llvm::Type *DestType = APType->getElementType(); 313 314 if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) { 315 unsigned NumInitElements = E->getNumInits(); 316 317 unsigned i; 318 for (i = 0; i != NumInitElements; ++i) { 319 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 320 Expr *Init = E->getInit(i); 321 if (isa<InitListExpr>(Init)) 322 CGF.EmitAggExpr(Init, NextVal, VolatileDest); 323 else 324 // FIXME: volatility 325 Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal); 326 } 327 328 // Emit remaining default initializers 329 unsigned NumArrayElements = AType->getNumElements(); 330 QualType QType = E->getInit(0)->getType(); 331 const llvm::Type *EType = AType->getElementType(); 332 for (/*Do not initialize i*/; i < NumArrayElements; ++i) { 333 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 334 if (EType->isSingleValueType()) 335 // FIXME: volatility 336 Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal); 337 else 338 CGF.EmitAggregateClear(NextVal, QType); 339 } 340 } else 341 assert(false && "Invalid initializer"); 342} 343 344void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 345 // FIXME: Are initializers affected by volatile? 346 if (E->getType()->isComplexType()) { 347 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 348 } else if (CGF.hasAggregateLLVMType(E->getType())) { 349 CGF.EmitAnyExpr(E, LV.getAddress(), false); 350 } else { 351 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 352 } 353} 354 355void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 356 if (!CGF.hasAggregateLLVMType(T)) { 357 // For non-aggregates, we can store zero 358 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 359 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 360 } else { 361 // Otherwise, just memset the whole thing to zero. This is legal 362 // because in LLVM, all default initializers are guaranteed to have a 363 // bit pattern of all zeros. 364 // There's a potential optimization opportunity in combining 365 // memsets; that would be easy for arrays, but relatively 366 // difficult for structures with the current code. 367 const llvm::Type *SizeTy = llvm::Type::Int64Ty; 368 llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset, 369 &SizeTy, 1); 370 uint64_t Size = CGF.getContext().getTypeSize(T); 371 372 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 373 llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp"); 374 Builder.CreateCall4(MemSet, DestPtr, 375 llvm::ConstantInt::get(llvm::Type::Int8Ty, 0), 376 llvm::ConstantInt::get(SizeTy, Size/8), 377 llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 378 } 379} 380 381void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 382 if (E->hadDesignators()) { 383 CGF.ErrorUnsupported(E, "initializer list with designators"); 384 return; 385 } 386 387#if 0 388 // FIXME: Disabled while we figure out what to do about 389 // test/CodeGen/bitfield.c 390 // 391 // If we can, prefer a copy from a global; this is a lot less 392 // code for long globals, and it's easier for the current optimizers 393 // to analyze. 394 // FIXME: Should we really be doing this? Should we try to avoid 395 // cases where we emit a global with a lot of zeros? Should 396 // we try to avoid short globals? 397 if (E->isConstantExpr(CGF.getContext(), 0)) { 398 llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF); 399 llvm::GlobalVariable* GV = 400 new llvm::GlobalVariable(C->getType(), true, 401 llvm::GlobalValue::InternalLinkage, 402 C, "", &CGF.CGM.getModule(), 0); 403 CGF.EmitAggregateCopy(DestPtr, GV, E->getType()); 404 return; 405 } 406#endif 407 // Handle initialization of an array. 408 if (E->getType()->isArrayType()) { 409 const llvm::PointerType *APType = 410 cast<llvm::PointerType>(DestPtr->getType()); 411 const llvm::ArrayType *AType = 412 cast<llvm::ArrayType>(APType->getElementType()); 413 414 uint64_t NumInitElements = E->getNumInits(); 415 416 if (E->getNumInits() > 0) { 417 QualType T1 = E->getType(); 418 QualType T2 = E->getInit(0)->getType(); 419 if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() == 420 CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) { 421 EmitAggLoadOfLValue(E->getInit(0)); 422 return; 423 } 424 } 425 426 uint64_t NumArrayElements = AType->getNumElements(); 427 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 428 ElementType =CGF.getContext().getAsArrayType(ElementType)->getElementType(); 429 430 unsigned CVRqualifier = ElementType.getCVRQualifiers(); 431 432 for (uint64_t i = 0; i != NumArrayElements; ++i) { 433 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 434 if (i < NumInitElements) 435 EmitInitializationToLValue(E->getInit(i), 436 LValue::MakeAddr(NextVal, CVRqualifier)); 437 else 438 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier), 439 ElementType); 440 } 441 return; 442 } 443 444 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 445 446 // Do struct initialization; this code just sets each individual member 447 // to the approprate value. This makes bitfield support automatic; 448 // the disadvantage is that the generated code is more difficult for 449 // the optimizer, especially with bitfields. 450 unsigned NumInitElements = E->getNumInits(); 451 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 452 unsigned CurInitVal = 0; 453 bool isUnion = E->getType()->isUnionType(); 454 455 // Here we iterate over the fields; this makes it simpler to both 456 // default-initialize fields and skip over unnamed fields. 457 for (RecordDecl::field_iterator Field = SD->field_begin(), 458 FieldEnd = SD->field_end(); 459 Field != FieldEnd; ++Field) { 460 // We're done once we hit the flexible array member 461 if (Field->getType()->isIncompleteArrayType()) 462 break; 463 464 if (Field->getIdentifier() == 0) { 465 // Initializers can't initialize unnamed fields, e.g. "int : 20;" 466 continue; 467 } 468 // FIXME: volatility 469 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, isUnion,0); 470 if (CurInitVal < NumInitElements) { 471 // Store the initializer into the field 472 // This will probably have to get a bit smarter when we support 473 // designators in initializers 474 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 475 } else { 476 // We're out of initalizers; default-initialize to null 477 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 478 } 479 480 // Unions only initialize one field. 481 // (things can get weird with designators, but they aren't 482 // supported yet.) 483 if (isUnion) 484 break; 485 } 486} 487 488//===----------------------------------------------------------------------===// 489// Entry Points into this File 490//===----------------------------------------------------------------------===// 491 492/// EmitAggExpr - Emit the computation of the specified expression of 493/// aggregate type. The result is computed into DestPtr. Note that if 494/// DestPtr is null, the value of the aggregate expression is not needed. 495void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 496 bool VolatileDest) { 497 assert(E && hasAggregateLLVMType(E->getType()) && 498 "Invalid aggregate expression to emit"); 499 500 AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E)); 501} 502 503void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 504 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 505 506 EmitMemSetToZero(DestPtr, Ty); 507} 508 509void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 510 llvm::Value *SrcPtr, QualType Ty) { 511 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 512 513 // Aggregate assignment turns into llvm.memmove. 514 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 515 if (DestPtr->getType() != BP) 516 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 517 if (SrcPtr->getType() != BP) 518 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 519 520 // Get size and alignment info for this aggregate. 521 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 522 523 // FIXME: Handle variable sized types. 524 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth); 525 526 Builder.CreateCall4(CGM.getMemMoveFn(), 527 DestPtr, SrcPtr, 528 // TypeInfo.first describes size in bits. 529 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 530 llvm::ConstantInt::get(llvm::Type::Int32Ty, 531 TypeInfo.second/8)); 532} 533